I am trying to parse a folder and delete all the files in it.
DirectoryInfo dir = new DirectoryInfo("C\\Temp");
if (dir.GetDirectories().Any(p => p.Name == "\\NewTemp"))
{
foreach (string file in Directory.GetFiles(dir + "\\NewTemp"))
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
}
This code works fine and deletes all the files in my \NewTemp Folder. But if any of the files is opened those files will not be deleted. I want to forecfully close the files that are opened and delete them. I even tried
foreach (string file in Directory.GetFiles(dir + "\\NewTemp"))
{
TextReader tr = new StreamReader(dir+"\\NewTemp\\"+file);
tr.Close();
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
But no use. Please let me know where I am missing.