Zum Inhalt springen

Delete File or Folder path in C#

Okt 31, 2010 | 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.

Subscribe for our free newsletter

Thank you! you are successfully subscribed.
newsletter

Exclusive News and Updates on Enterprise Mobility!

* I consent to receive newsletters via email from 42Gears and its Affiliates.
Please agree
* I have reviewed and agreed to 42Gears Privacy Policy and Terms of Use prior to subscribing and understand that I may change my preference or unsubscribe at any time.
Please agree
Please verify captcha
Please enter a valid official email