If you want to avoid a DirectoryNotFoundException
you will need to ensure that the directory of the file does indeed exist. File.Exists
accomplishes this. Another way would be to utilize the Path
and Directory
utility classes like so:
string file = @"C:\subfolder\test.txt";
if (Directory.Exists(Path.GetDirectoryName(file)))
{
File.Delete(file);
}