Is it possible to do an unstoppable delete in C# ? (Compact Framework)
Given a folder I want to make sure that ALL the files on that directory are deleted. I know there maybe IOExceptions or Access Denied errors but how do just leave them aside and continue with my deletion of the files that I actually can delete? Is this possible? Please开发者_高级运维 shed some light on me on where I can begin.
If you want to delete all files you can delete, you could create a list of files (recursively for subdirections) and then delete them separately, skipping the ones that throw an exception.
IF you loop through the files in the directory and delete each one within a try/catch you can then continue even after an exception. If you try to delete the entire directory then once it fails it fails.
Edit: Code as requested
private void DeleteFiles(DirectoryInfo Directory)
{
bool AllFilesDeleted = true;
foreach(FileInfo oFile in Directory.GetFiles())
{
try
{
oFile.Delete();
}
catch (Exception ex) { AllFilesDeleted = false; }
}
foreach (DirectoryInfo oDirectory in Directory.GetDirectories())
{
DeleteFiles(oDirectory);
}
if (AllFilesDeleted)
{
try
{
Directory.Delete();
}
catch (Exception ex){}
}
}
IOExceptions or Access Denied errors but how do just leave them aside and continue with my deletion
Huh? If you are having IO issues or you don't have access to the files you can't delete them. They are exceptions. They are telling you "hey, this went wrong, and here's why". They aren't polite warning messages that you can just ignore, they are the reason your delete did not work in the first place.
Answering the recursive search question:
void delete(DirectoryInfo di) {
foreach(DirectoryInfo di2 in di.GetDirectories()) {
delete(di2);
}
foreach(FileInfo fi in di.GetFiles()) {
fi.Delete();
}
}
...as suggested above, try...catch around various parts will cope with the inability to delete certain files.
If you change the order a bit in what @Will A suggested and add a line to delete the directory itself - it should do the trick. Something like
static void delete(DirectoryInfo di)
{
foreach (FileInfo fi in di.GetFiles())
{
try
{
fi.Delete();
}
catch (Exception)
{
}
}
foreach (DirectoryInfo di2 in di.GetDirectories())
{
delete(di2);
}
try
{
di.Delete();
}
catch (Exception)
{
}
}
it should clear the empty folders
精彩评论