I am trying to parse a folder and delete all 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 files in the \ NewTemp folder. But if any of the files is open, these files will not be deleted. I want to block the files that open 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 to no avail. Please let me know where I am missing.
source share