Create a File/Directory Transferring App in C#

Reason :

One of a application I’m developing generates many PDF files daily. So we delete them normally once a week or another time. But it is difficult to search files which has generated in a particular date or date range and copy them or delete them to another place. We had to do it manually.

Solution:

SO I created a small app to do it quickly. And I created a small app to show you how to create a example app to copy and delete directories/files from one place to another.

Steps :

1 .Create User Interface.

Here is the user interface I created..

2 drop folder open dialague

Image 1 : UI

We have to select folder path to the app. So I added two folder browse dialogues to select browse folders. You can select “Folder browser dialogue” control form tool box and drag and drop it into above form.

1 folder open dialague

Image 2 : Folder browse control

Then you can see those dialogue controls in bottom panel.

2. We have to Add function to “Source” button and “Destination” button to browse and select source folder path and destination folder path.

3 select directories with delete option

Image 3 : Source and Destination selecting


private void btnSource_Click(object sender, EventArgs e)
 {
 DialogResult result = folderBrowserDialogSourceDir.ShowDialog();
 if (result == DialogResult.OK)
 {
 textBox1.Text = this.folderBrowserDialogSourceDir.SelectedPath;
 }

}

private void btnDestination_Click(object sender, EventArgs e)
 {
 DialogResult result = folderBrowserDialogDestinationDir.ShowDialog();
 if (result == DialogResult.OK)
 {
 textBox2.Text = this.folderBrowserDialogDestinationDir.SelectedPath;
 }
 }

Then when you click one of “Source” or “Destination” buttons, a browser window will popup and you can select any folder.

3 select directories

Image 4 : Folder browser dialague

3. User can check the “Delete after transferring”  check box if he want to delete files from source folder after copy them to destination.

4.Next Add functions to “Transfer files” button  to transfer files when Click it. So I use “Button click” event.

Here is the code in this event.


private void btnTransfer_Click(object sender, EventArgs e)
 {
 try
 {
 string pathDestinationFolder = string.Format(@"{0}", textBox2.Text);

string pathSource = string.Format(@"{0}", textBox1.Text);

if (!string.IsNullOrWhiteSpace(pathSource) && !string.IsNullOrWhiteSpace(pathDestinationFolder))
 {
 DateTime selectedDate = Convert.ToDateTime(dpEffiectiveDate.Text);
 DirectoryCopy(pathSource, pathDestinationFolder, true, selectedDate);

if (chkDelete.Checked)
 {
 DeleteDirectories(pathSource, selectedDate);
 }

lblDirectoriesFound.Text = foundDirectories.ToString();
 lblTransferedFilesCount.Text = createdDirectories.ToString();
 lblDeleted.Text = deletedDirectories.ToString();
 lblNotTransfered.Text = (foundDirectories - createdDirectories).ToString();
 }
 else { MessageBox.Show("Source and destination is required", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); }
 }
 catch (Exception ex)
 {
 MessageBox.Show(MethodBase.GetCurrentMethod() + " -> " + ex.Message);
 }
 }

I have extracted the function to copy directories and files to destination to a method “DirectoryCopy”.


private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, DateTime selectedDate)
 {
 try
 {
 #region check exists and create is not exists
 // Get the sub directories for the specified directory.
 DirectoryInfo dir = new DirectoryInfo(sourceDirName);
 DirectoryInfo[] dirs = dir.GetDirectories();

if (!dir.Exists)
 {
 throw new DirectoryNotFoundException(
 "Source directory does not exist or could not be found: "
 + sourceDirName);
 }

// If the destination directory doesn't exist, create it.
 if (!Directory.Exists(destDirName))
 {
 Directory.CreateDirectory(destDirName);
 createdDirectories = createdDirectories + 1;
 dirList.Add(destDirName);
 listViewDirectories.Items.Add("Created Directory -> " + destDirName);
 }

// Get the files in the directory and copy them to the new location.
 FileInfo[] files = dir.GetFiles();
 foreach (FileInfo file in files)
 {
 string temppath = Path.Combine(destDirName, file.Name);
 if (File.Exists(temppath))
 { }
 else
 {
 file.CopyTo(temppath, false);
 listViewDirectories.Items.Add("Coppied file -> " + temppath);
 }
 }
 #endregion
 // If copying subdirectories, copy them and their contents to new location.
 if (copySubDirs)
 {
 foreach (DirectoryInfo subdir in dirs)
 {
 if (subdir.CreationTime.Date == selectedDate.Date)
 {
 foundDirectories = foundDirectories + 1;
 string temppath = Path.Combine(destDirName, subdir.Name);
 DirectoryCopy(subdir.FullName, temppath, copySubDirs, selectedDate);
 }
 }
 }
 }
 catch (Exception ex)
 {
 MessageBox.Show(MethodBase.GetCurrentMethod()+" -> "+ ex.Message);
 }

}

“DirectoryCopy” Method is a recursive function.

Recursive function is a method which calls itself.

for more information go to =>Recursive function

7 use recursive function

Image 5 : Recursive function

The reason is some directories has one or more sub directories. So we have to go through all of them. So we have to loop through all directories in a same war. For that we have to use a Recursive function.

In “DirectoryCopy” method we have to use “FileInfo” class and “Directory“. SO we have to import System.IO namespace.


using System.IO;

[/code</blockquote>
In this method first we are checking directories in the source directory and we can watch information of source directory when debugging it.
<pre>

DirectoryInfo dir = new DirectoryInfo(sourceDirName);

4 file info creation date

Image 6 : File info -> Quick watch

According to my requirement  I get folders and files by its creation date. So I have to use "FileInfo" class to get values.

Then we have to get sub directories in the folder. For that I use GetDirectories() method.


DirectoryInfo[] dirs = dir.GetDirectories();

when debugging the code we can check whether it has sub directories or not.

5 sub directories

Image 7 : Directory info

  • According to above "older is exists and if it is not existing, Then I'm reading a folder to copy files.
  • And then read File information of containing files of resource folder and if its date is my selected date, then copy those files to selected destination.
  • Then show copied files and created folders in the list-box.

After copy files, In  Transfer button click event, then I check the "chkDelete" check box and if it is checked, Then program delete folders from source folder.

DeleteDirectories() is a recursive function too.


private void DeleteDirectories(string pathSource, DateTime selectedDate)
 {
 try
 {
 // Get the subdirectories for the specified directory.
 DirectoryInfo dirs = new DirectoryInfo(pathSource);
 DirectoryInfo[] dirList2 = dirs.GetDirectories();
 foreach (DirectoryInfo subdir in dirList2)
 {
 string subDirname = subdir.FullName;
 if (subdir.CreationTime.Date == selectedDate.Date)
 {
 deletedDirectories = deletedDirectories + 1;
 Directory.Delete(subDirname, true);
 listViewDirectories.Items.Add("Deleted Directory ->" + subDirname);
 }
 else
 {
 DeleteDirectories(subDirname, selectedDate);
 }
 }
 }
 catch (Exception ex)
 {
 MessageBox.Show(MethodBase.GetCurrentMethod() + " -> " + ex.Message);
 }
 }

Then we can see copied files , created directories and deleted directories in the list box.

8 final info

Image 8 : Final Result

And another thing is if an error occurred, System will shows the error message with the Method name. To get the method name that I used ..


MethodBase.GetCurrentMethod()

to use the MethodBase class we have to import ...


using System.Reflection;

To download the code go to Download.

Thanks !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s