Click here to Skip to main content
15,886,518 members
Articles / Programming Languages / C#

File Segregation using C#.NET

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
25 Oct 2010CPOL3 min read 29K   617   5   3
Copies files from multiple folders to single destination

Introduction

The main objective of this tool is to explore through the mentioned main folder and its sub directories and segregate the files and copy it to the new destination mentioned by the user.

Background

C#.NET and basic File Operations knowledge is enough.

The Scenario

Think about the scenario in which you have multiple folders within a folder where there are lots of files available with mixed file types like .txt, .pdf, .exe, .config, .dll, etc.

You are in great need to get a specific file type into a separate folder. (For example: You wanted to collect all .pdf files into a separate folder called AllPDFs from the directory which has numerous subdirectories.)

If you have the scenario I mentioned here, then this tool is for you.The tool will trace all the files spread over subdirectories and segregate it into the Destination folder structure.

Tool Description

Screen Shot

Untitled.png

  1. The Source path field will get the source directory path and lists the number of sub-directories available within the selected path in the left-side list box.
  2. The Destination path is the target path where the files to be moved.
  3. The Extension field will get the file extension which is to be explored in the specified path.

For example: If you give *.dll, then the file segregation tool will only look for the .dll files available in the main and sub-directories of the mentioned path and copies those alone to the target directory.

Add ons

The Delete and move operations are available as addons, you can switch ON/OFF the functionality by using the combo box labelled Addons.

Just like copy operation, the move will take only the mentioned extension files from the source and move it to the destination.If the extension is not provided, all the files available in the directory will be moved to the destination.

Delete operation deletes all the files available in the source path and matching the extension. In absence of extension, all files will be deleted from the source.

Using the Code

The getfiles method will get you the array of files to be copied, moved to the destination or deleted from the source.

C#
private string[] GetFiles()
        {
            string fileName = string.Empty;
            string strSourcePath = textBox1.Text;
            strTargetPath = textBox2.Text;
            string strExtension = !string.IsNullOrEmpty(textBox3.Text) ? 
				textBox3.Text : "*.*";
            string[] files = null;            

            if (System.IO.Directory.Exists(strSourcePath))
            {
                files = System.IO.Directory.GetFiles(strSourcePath, strExtension);
                string joined = String.Join(", ", files);
                files = null;


                // Determine if there are any items checked.
                if (checkedListBox1.CheckedItems.Count != 0)
                {
                    // If so, loop through all checked items and print results.
                    string strSubdirectories = "";
                    string strTempfilelist = "";
                    for (int x = 0; x < checkedListBox1.CheckedItems.Count; x++)
                    {
                        strSubdirectories = checkedListBox1.CheckedItems[x].ToString();
                        files = System.IO.Directory.GetFiles
				(strSubdirectories, strExtension);
                        strTempfilelist = String.Join(", ", files);
                        //Concatenating or collecting  the filelist 
                        joined += "," + strTempfilelist + ",";
                        files = null;
                        strTempfilelist = string.Empty;
                    }
                }

                files = joined.Split(',');
            }
            else
            {
                MessageBox.Show("Source path does not exist!");
            }

            return files;
        }

GetFiles() Method Breakups

The following code snippet does the stuff of getting the files of the given path:

C#
files = System.IO.Directory.GetFiles(strSourcePath, strExtension); 

Since we may have directories within directories, this array value may needs to be extended sometimes so we have to convert an array into the comma separated string value, so we can iterate through the number of available directories (obviously the directories selected in the list-box) and add the files to this array.

The Conversion of array into the comma separated string is done by the following snippet:

  • files - Array value
  • String.Join - Keyword to convert the array into a string with the separator value mentioned (here its Comma (", ")
C#
string joined = String.Join(", ", files);  

Since the getfiles needs to send an array, finally the following snippet is needed to do the activity.

C#
files = joined.Split(',');

Now we got the array of values that's needed to be deleted, moved, or copied what next?

We need a consumer code to perform the actual Delete, Copy, Move Operation, isn't it?

So I wrote the functionality in button event for Delete, copy, move separately.

See the below snippet to perform copy operation on array returned by the getfiles() method:

C#
foreach (string s in files)
 {
   if (!string.IsNullOrEmpty(s))
   {
      // Use static Path methods to extract only the file name from the path.
        fileName = System.IO.Path.GetFileName(s);
         destFile = System.IO.Path.Combine(strTargetPath, fileName);
         System.IO.File.Copy(s, destFile, true);
    }      
 }
  • fileName - Extracts the filename from the sourcefile
  • destFile - Combines the destination directory path retrieved from the destination text box to the fileName (To name the destination file as same as the source file)
  • System.IO.File.Copy(s,destFile,true) - Copies the file from source path from destination path
  • s - Full path of the source file like "D:\C#Books\C#.PDF"
  • destFile - Destination directory selected + fileName (Example: If you have mentioned "E:\Allpdf", then the path will be "E:\Allpdf\C#.PDF".)

This will happen for every iteration of the loop and finally you will have the specific file types segregated in the destination folder.

Hope I had explained better about the tool.

History

  • 25th October, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Cognizant Technology Solutions
India India
Expertise in Asp.Net,Worked in variety of domains.
Have fair knowledge in using design patterns.
Presently he is working as Senior developer with cognizant India.His interest is to develop tools using Sqlserver,C#.Net.

Comments and Discussions

 
GeneralMy vote of 5 Pin
ramanujkumar9-Jul-12 2:41
ramanujkumar9-Jul-12 2:41 
GeneralFilenames with , Pin
dalek92-Nov-10 1:25
dalek92-Nov-10 1:25 
GeneralA bit of a definition clarification Pin
Ron Beyer25-Oct-10 10:38
professionalRon Beyer25-Oct-10 10:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.