My console application program is creating some runtime files while it is working so what I want to do is delete all of these files on the application startup. I have tried this:
public static void Empty(string targetDir)
{
var directory = new DirectoryInfo(targetDir);
if (!directory.Exists) return;
foreach (var file in directory.GetFiles()) file.Delete();
foreach (var subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}
...just to look for all the files/folders in the given path (which is in a subdirectory in the program execution path) then delete them. However, I get the following exception:
Access to the path 'file' is denied.
I tried to run the program as administrator with no luck; However, I want a solution that works without using administrator privileges.
Notes :
I got this error and found that it was because my test files were readonly. Changed this and I can now use fileinfo to delete them no worries.
You say that the files are not open in another application, but it must be open within your application:
//Create some directories to delete
Directory.CreateDirectory("C:/Temp/DeleteMe");
Directory.CreateDirectory("C:/Temp/DeleteMe/DeleteMe");
File.Create("C:/Temp/DeleteMe/DeleteMeFile");//FileStream still open!!
//Delete the files
var directory = new DirectoryInfo("C:/Temp/DeleteMe");
if (!directory.Exists) return;
foreach (FileInfo file in directory.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in directory.GetDirectories())
{
dir.Delete(true);
}
Make sure you dispose the file stream when you create the file
//Create some directories to delete
Directory.CreateDirectory("C:/Temp/DeleteMe");
Directory.CreateDirectory("C:/Temp/DeleteMe/DeleteMe");
using (File.Create("C:/Temp/DeleteMe/DeleteMeFile")) { }
//Delete the files
var directory = new DirectoryInfo("C:/Temp/DeleteMe");
if (!directory.Exists) return;
foreach (FileInfo file in directory.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in directory.GetDirectories())
{
dir.Delete(true);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With