create folder based on file extension in c#

I am copying files from C:\SampleFilesInSourceFolder to D:\SampleFilesInDestinationFolder.

In this folder D:\SampleFilesInDestinationFolder I have list of files.


.jpeg,.pdf,.xlsx,.docs etc

I want to move all the files into respective folder based on file extension. could any one help on this

1 answer

  • answered 2018-11-08 07:06 Nakul

    First get all the files from your source folder.

    DirectoryInfo d = new DirectoryInfo(@"D:\Test");//Assuming Test is your source Folder

    Then get files by extension

    FileInfo[] Files = d.GetFiles("*.txt"); //Getting files by extension

    Create folder in your destination with the extension name


    Like this you can achieve your requirements.

    Or you can directly apply each loop on files you got and same logic you can do it. string str = "";

    FileInfo[] Files = d.GetFiles();
    foreach(FileInfo file in Files )
     str = str + ", " + file.Name;// Apply your logic here.