我使用此代码清空我经常删除的一些文件,例如Windows中的临时文件。几个朋友可能希望使用相同的应用程序,我正在研究处理文件未找到异常的最佳方法。
如何最好地处理这个以供多个用户使用?
public void Deletefiles()
{
try
{
string[] DirectoryList = Directory.GetDirectories("C:\\Users\\user\\Desktop\\1");
string[] FileList = Directory.GetFiles("C:\\Users\\user\\Desktop\\1");
foreach (string x in DirectoryList)
{
Directory.Delete(x, true);
FoldersCounter++;
}
foreach (string y in FileList)
{
File.Delete(y);
FilesCounter++;
}
MessageBox.Show("Done...\nFiles deleted - " + FileList.Length + "\nDirectories deleted - " + DirectoryList.Length + "\n" + FilesCounter + "\n", "message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception z)
{
if (z.Message.Contains("NotFound"))
{
MessageBox.Show("File Not Found");
}
else
{
throw (z);
}
//throw new FileNotFoundException();
}
}
答案 0 :(得分:0)
尽可能少地修改你的代码,你可以简单地将你的Delete
调用包装在try / catch中:
foreach (string x in DirectoryList)
{
try {
Directory.Delete(x, true);
}
catch (DirectoryNotFoundException e)
{
// do something, or not...
}
FoldersCounter++;
}
foreach (string y in FileList)
{
try
{
File.Delete(y);
}
catch (FileNotFoundException e)
{
// do something, or not...
}
FilesCounter++;
}
删除顶级的try / catch,让foreach
语句循环显示 - try
和catch
任何例外情况。
您不一定需要提醒用户该文件未找到。它会在那里被删除,所以它不存在并不会影响该计划的结果。
这不是最资源友好的方法,但它足够简单,不会引起问题。