Delete File or Folder path in C#

Following is a C# code snippet to delete a path (file or directory). First we have to determine whether the path is a file or a folder and then call appropriate Delete methods. In case of directory, you can specifiy whether the contents should be recursively deleted before deleting the directory.

void DeletePath(string path)
{
try
{
FileInfo finfo = new FileInfo(path);
if (finfo.Attributes == FileAttributes.Directory)
{
//recursively delete directory
Directory.Delete(path, true);
}
else if(finfo.Attributes == FileAttributes.Normal)
{
File.Delete(path);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}

42Gears has recently released SureCop, an Anti-theft software for Windows Mobile phones.To learn more about SureCop for Windows Mobile and how it can help you secure your mobile phone, please visit the product website http://www.surecop.com. To learn more about our products, please visit http://www.42gears.com.

Leave a Comment