how to upload entire folder with exact folder structure? - c#

I am uploading an entire folder to a server.
The folder contains files and subfolders in it.
I want it to be exactly uploaded as it is in my local machine.
I tried it with FolderBrowserDialog and then the folder copying logic.
It works well on local machine but after deployment I am getting Unhandled exception.
Context: Section1
try
{var t = new Thread((ThreadStart)(() =>
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
//foreach (var path in Directory.GetFiles(fbd.SelectedPath))
//{
// //Console.WriteLine(path); // full path
// //Console.WriteLine(System.IO.Path.GetFileName(path)); // file name
//}
}
else
{
}
//fbd.RootFolder = System.Environment.SpecialFolder.MyComputer;
//fbd.ShowNewFolderButton = true;
//if (fbd.ShowDialog() == DialogResult.Cancel)
// return;
selectedPath = fbd.SelectedPath;
}));
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
// ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup();", true);
FilesBulkUpload(selectedPath);
private void FilesBulkUpload(string path)
{ try
{ if (path != null)
{
string lastFolderName = Path.GetFileName(path);
Copyfolder(path, #"D:\Sneha\test\" + lastFolderName,true);
MessageBox.Show("Folder Uploaded Successfully");
}
}
catch (Exception ex)
{
LogError(ex);
}
}
Copyfolder logic:
if (Directory.Exists(SourcePath))
{
if (Directory.Exists(DestinationPath) == false)
Directory.CreateDirectory(DestinationPath);
foreach (string fls in Directory.GetFiles(SourcePath))
{ FileInfo flinfo = new FileInfo(fls);
string ext = flinfo.Extension;
if (ext`enter code here` == ".exe" || ext == ".zip")
{
MessageBox.Show("Please exclude files like with .exe, .zip extension");
}
else
{
flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
}
}
foreach (string drs in Directory.GetDirectories(SourcePath))
{
DirectoryInfo diDi = new DirectoryInfo(drs);

Related

How can I search for a specific attachment in outlook

I am trying to retrieve a specific attachment in Outlook to save to my folder.
Everything works great but it seems to save all the attachments in the "Inbox" Folder instead of the specific one I am looking for.
This is what I have at the moment:
static void EnumerateFoldersInDefaultStore()
{
Outlook.Application Application = new Outlook.Application();
Outlook.Folder root = Application.Session.DefaultStore.GetRootFolder() as Outlook.Folder;
EnumerateFolders(root);
}
static void EnumerateFolders(Outlook.Folder folder)
{
Outlook.Folders childFolders = folder.Folders;
if (childFolders.Count > 0)
{
foreach (Outlook.Folder childFolder in childFolders)
{
if (childFolder.FolderPath.Contains("Inbox"))
{
Console.WriteLine(childFolder.FolderPath);
EnumerateFolders(childFolder);
}
}
}
Console.WriteLine("Checking in " + folder.FolderPath);
IterateMessages(folder);
}
static void IterateMessages(Outlook.Folder folder)
{
string fileName = "Reports.pdf";
var fi = folder.Items;
if (fi != null)
{
try
{
foreach (Object item in fi)
{
Outlook.MailItem mi = (Outlook.MailItem)item;
var attachments = mi.Attachments;
if (attachments.Count != 0)
{
if (!Directory.Exists(basePath + folder.FolderPath))
{
Directory.CreateDirectory(basePath + folder.FolderPath);
}
for (int i = 1; i <= mi.Attachments.Count; i++)
{
if (fileName != null)
{
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
totalfilesize = totalfilesize + mi.Attachments[i].Size;
if (!File.Exists(basePath + mi.Attachments[i].FileName))
{
Console.WriteLine("Saving " + mi.Attachments[i].FileName);
mi.Attachments[i].SaveAsFile(basePath + mi.Attachments[i].FileName);
}
else
{
Console.WriteLine("Already saved " + mi.Attachments[i].FileName);
}
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine("An error occurred: '{0}'", e);
}
}
}
So it basically searches the entire "Inbox" and saves all the attachments but like I said not the one I want only - "Reports.pdf"
What am I doing wrong here?
In static void IterateMessages(Outlook.Folder folder) you currently only check for if (fileName != null) (which should never happen as fileName is always assigned at the beginning of the method).
You need to add a condition to check if the attached file meets your fileName-Criteria, e.g.:
if (mi.Attachments[i].FileName == fileName) {
//Save your attachment
} else {
// naming-critera not met, skip...
}

How can I check the content of the FolderBrowserDialog if is it empty or not?

I'm using FolderBrowserDialog in a WPF project and it works fine, I would like to check the content of the folder selected selectedPath if is it empty or null and the extension of the existed files.
How can I do that?
try
{
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
FileText.Text = dialog.SelectedPath;
}
}
catch (Exception exp)
{
Console.WriteLine("Error : " + exp);
}
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK || result == System.Windows.Forms.DialogResult.Yes)
{
FileText.Text = dialog.SelectedPath;
var directory = new System.IO.DirectoryInfo(dialog.SelectedPath);
var files = directory.GetFiles(); // Array with information about files.
if (files.Length == 0)
Debug.WriteLine("Empty Folder.");
else
{
var filesTxt = files.Where(f => f.Extension == ".txt").ToArray(); // Array with information about TXT files.
if (filesTxt.Length == 0)
Debug.WriteLine("There is no TXT files in the folder.");
}
}
}

How can i make the method to return a List of files only and not also directories?

In constructor. filePathList is List
filePathList = SearchAccessibleFilesNoDistinct(rootDirectory, null).ToList();
And the SearchAccessibleFilesNoDistinct method
IEnumerable<string> SearchAccessibleFilesNoDistinct(string root, List<string> files)
{
if (files == null)
files = new List<string>();
if (Directory.Exists(root))
{
foreach (var file in Directory.EnumerateFiles(root))
{
string ext = Path.GetExtension(file);
if (!files.Contains(file) && ext == textBox2.Text)
{
files.Add(file);
}
}
foreach (var subDir in Directory.EnumerateDirectories(root))
{
try
{
SearchAccessibleFilesNoDistinct(subDir, files);
files.Add(subDir);
}
catch (UnauthorizedAccessException ex)
{
// ...
}
}
}
return files;
}
Then i make loop over the List filePathList
foreach (string file in filePathList)
{
try
{
_busy.WaitOne();
if (worker.CancellationPending == true)
{
e.Cancel = true;
return;
}
bool reportedFile = false;
for (int i = 0; i < textToSearch.Length; i++)
{
if (File.ReadAllText(file).IndexOf(textToSearch[i], StringComparison.InvariantCultureIgnoreCase) >= 0)
{
resultsoftextfound.Add(file + " " + textToSearch[i]);
if (!reportedFile)
{
numberoffiles++;
MyProgress myp = new MyProgress();
myp.Report1 = file;
myp.Report2 = numberoffiles.ToString();
myp.Report3 = textToSearch[i];
backgroundWorker1.ReportProgress(0, myp);
reportedFile = true;
}
}
}
numberofdirs++;
label1.Invoke((MethodInvoker)delegate
{
label1.Text = numberofdirs.ToString();
label1.Visible = true;
});
}
catch (Exception)
{
restrictedFiles.Add(file);
numberofrestrictedFiles ++;
label11.Invoke((MethodInvoker)delegate
{
label11.Text = numberofrestrictedFiles.ToString();
label11.Visible = true;
});
continue;
}
The problem is that in the catch part the restrictedFiles is just directories not files. Since filePathList contain files and directories and when it's trying to search in a directory it's getting to the catch. It's not a restricted file it's just directory and not file at all.
That's why i think the method SearchAccessibleFilesNoDistinct should return only files without directories as items.
For example in filePathList i see in index 0:
c:\temp
And in index 1
c:\temp\help.txt
The first item in index 0 will go to the catch as restricted file and the second item will not.
You have this loop to search search the subdirectories:
foreach (var subDir in Directory.EnumerateDirectories(root))
{
try
{
SearchAccessibleFilesNoDistinct(subDir, files);
files.Add(subDir); <--- remove this line
}
catch (UnauthorizedAccessException ex)
{
// ...
}
}
Remove the line that adds the subdirectory to the list of files. I've marked it in the code above.
Is it you looking for:
Directory.GetFiles(rootDir,"*.*", SearchOption.AllDirectories);
? Change . to mask form textbox only.

Problems uploading files using Chilkat

I am trying to upload a file to a Server using sftp. I have downloaded and installed Chilkat and i am downloading files without any issues. But when i try to upload files to the server, i get no error stating that the uploading files. When i check for response messages, it says "file upload success 1" and one is true But the files doesn't get uploaded to the server.
this is my code:
public void UploadAndMoveFile()
{
bool success = false;
string path = #"\\geodis\";
string archive = #"\\Archive\";
string[] files = Directory.GetFiles(path);
if (files.Count() == 0)
{
//no files
}
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
string fileSource = path + fileName;
string fileDestination = archive + fileName;
string handle;
string ftp = #"\IN\"+fileName;
handle = sftp.OpenFile(ftp, "writeOnly", "createTruncate");
if (handle == null)
{
Console.WriteLine(sftp.LastErrorText);
return;
}
success = sftp.UploadFile(handle, fileSource);
if (success == true)
{
AppendLogFile("Uploading File Succeeded", "Uploade File", fileName);
System.IO.File.Move(fileSource, fileDestination);
AppendLogFile("Moving File Succeeded", "Moving File", fileName);
}
else
{
// no files
}
}
}
Can anyone help me find out what I am doing wrong?
Found the Issue, in the upload method i had handle variable instead of the ftp variable.
here is the solution:
public void UploadAndMoveFile()
{
bool success = false;
string path = #"\\geodis\";
string archive = #"\\Archive\";
string[] files = Directory.GetFiles(path);
if (files.Count() == 0)
{
//no files
}
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
string fileSource = path + fileName;
string fileDestination = archive + fileName;
string handle;
string ftp = #"\IN\"+fileName;
handle = sftp.OpenFile(ftp, "writeOnly", "createTruncate");
if (handle == null)
{
Console.WriteLine(sftp.LastErrorText);
return;
}
success = sftp.UploadFile(ftp, fileSource);
if (success == true)
{
AppendLogFile("Uploading File Succeeded", "Uploade File", fileName);
System.IO.File.Move(fileSource, fileDestination);
AppendLogFile("Moving File Succeeded", "Moving File", fileName);
}
else
{
// no files
}
}
}

Rename some files in a folder

I have a task of changing the names of some files (that is, adding id to each name dynamically) in a folder using C#.
Example: help.txt to 1help.txt
How can I do this?
Have a look at FileInfo.
Do something like this:
void RenameThem()
{
DirectoryInfo d = new DirectoryInfo("c:/dir/");
FileInfo[] infos = d.GetFiles("*.myfiles");
foreach(FileInfo f in infos)
{
// Do the renaming here
File.Move(f.FullName, Path.Combine(f.DirectoryName, "1" + f.Name));
}
}
I'll just dump this here since I needed to write this code for my own purposes.
using System;
using System.IO;
public static class FileSystemInfoExtensions
{
public static void Rename(this FileSystemInfo item, string newName)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
FileInfo fileInfo = item as FileInfo;
if (fileInfo != null)
{
fileInfo.Rename(newName);
return;
}
DirectoryInfo directoryInfo = item as DirectoryInfo;
if (directoryInfo != null)
{
directoryInfo.Rename(newName);
return;
}
throw new ArgumentException("Item", "Unexpected subclass of FileSystemInfo " + item.GetType());
}
public static void Rename(this FileInfo file, string newName)
{
// Validate arguments.
if (file == null)
{
throw new ArgumentNullException("file");
}
else if (newName == null)
{
throw new ArgumentNullException("newName");
}
else if (newName.Length == 0)
{
throw new ArgumentException("The name is empty.", "newName");
}
else if (newName.IndexOf(Path.DirectorySeparatorChar) >= 0
|| newName.IndexOf(Path.AltDirectorySeparatorChar) >= 0)
{
throw new ArgumentException("The name contains path separators. The file would be moved.", "newName");
}
// Rename file.
string newPath = Path.Combine(file.DirectoryName, newName);
file.MoveTo(newPath);
}
public static void Rename(this DirectoryInfo directory, string newName)
{
// Validate arguments.
if (directory == null)
{
throw new ArgumentNullException("directory");
}
else if (newName == null)
{
throw new ArgumentNullException("newName");
}
else if (newName.Length == 0)
{
throw new ArgumentException("The name is empty.", "newName");
}
else if (newName.IndexOf(Path.DirectorySeparatorChar) >= 0
|| newName.IndexOf(Path.AltDirectorySeparatorChar) >= 0)
{
throw new ArgumentException("The name contains path separators. The directory would be moved.", "newName");
}
// Rename directory.
string newPath = Path.Combine(directory.Parent.FullName, newName);
directory.MoveTo(newPath);
}
}
The function that you are looking for is File.Move(source, destination) of the System.IO namespace. Also take a look at the DirectoryInfo class (of the same namespace) to access the contents of the folder.
On .NET Framework 4.0 I use FileInfo.MoveTo() method that only takes 1 argument
Just to move files my method looks like this
private void Move(string sourceDirName, string destDirName)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
FileInfo[] files = null;
files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.MoveTo(temppath);
}
}
to rename files my method looks like this
private void Rename(string folderPath)
{
int fileCount = 0;
DirectoryInfo dir = new DirectoryInfo(folderPath);
files = dir.GetFiles();
foreach (FileInfo file in files)
{
fileCount += 1;
string newFileName = fileCount.ToString() + file.Name;
string temppath = Path.Combine(folderPath, newFileName);
file.MoveTo(temppath);
}
}
AS you can see to Rename file it syntax is almost the same as to Move it, just need to modify the filename before using MoveTo() method.
Check out How can I rename a file in C#?. I didn't know that C# doesn't have a rename... It seems you have to use System.IO.File.Move(oldFileName, newFileName)
You can use File.Move, like this:
string oldFilePath = Path.Combine( Server.MapPath("~/uploads"), "oldFileName");
string newFilePath = Path.Combine( Server.MapPath("~/uploads"), "newFileName");
File.Move(oldFilePath, newFilePath);

Categories

Resources