Delete File or Folder path in C#

Featured-Image-42Gears-logo
By 42Gears Team

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);
}
}

To learn more about our products, please visit https://www.42gears.com.

“Written with expertise and passion to help you understand the topic better.”

4
42Gears Team – Content Author
Published on October 31, 2010

Subscribe to our newsletter

Stay updated with the latest news, articles, and resources on enterprise mobility.

Weekly articles
Actionable insights delivered once a week. No noise.
No spam
Your privacy matters. Unsubscribe anytime.