Saturday, January 10, 2015

Delete Files & Folders

Sample code to delete the Files and the Directories.

Namespace :


using System.IO;


Code:


Delete Directory:
         
            Directory.Delete("C:\test\")

            If Directory have the sub directories then,


            Directory.Delete("C:\test\", True)


Delete Files:


           File.Delete("C:\test\text.txt")


           To delete multiple files from Directory,


           string[] Files= Directory.GetFiles(@"c:\test\");


           foreach (string filePath in Files)
                  File.Delete(filePath);

Get Files from Directory using C#

Sample code to get the list of files from the source Directory. You can also add filter to search the specific file type only.

Namespace :
using System.IO;


Code:

Directory.GetFiles returns string array with files names.

string[] files = Directory.GetFiles(@"c:\Test\");


You can also search the files with specific pattern.

string[] files = Directory.GetFiles(@"c:\Test\", "*.txt");


To get the list of files from directory including the sub directories,

string[] filePaths = Directory.GetFiles(@"c:\Test\", "*.txt",SearchOption.AllDirectories);