最后循环
我有一个 foreach 循环,其中有 try catch 和finally。它会遍历文件夹中的文件,最后将它们全部删除......但现在如果我有两个文件,因为它正在删除所有文件(由于应用程序功能,我需要删除所有文件),它不会通过第二个文件。是否可以让 foreach 循环完成,然后删除 foreach 方法中的所有文件,这是一个示例:
foreach (DirectoryInfo directory in directories)
{
foreach (FileInfo file in directory.GetFiles("*.csv"))
{
try
{
//do something with file
}
catch (Exception e)
{
//catch exception
}
finally
{
if (!IsFileLocked(file))
{
string[] files = Directory.GetFiles(@"C:\Test");
foreach (string filetoDelete in files)
{
File.Delete(filetoDelete);
}
}
}
}
}
希望它足够清楚。
I have a foreach loop that has try catch and finally. it goes through files in a folder and finally deletes them all....but now if i have two files, as it is deleting all( i need to delete all because of app functionality) it will not go though second file. is it possible to let foreach loop finish then delete all files in foreach method here is an example:
foreach (DirectoryInfo directory in directories)
{
foreach (FileInfo file in directory.GetFiles("*.csv"))
{
try
{
//do something with file
}
catch (Exception e)
{
//catch exception
}
finally
{
if (!IsFileLocked(file))
{
string[] files = Directory.GetFiles(@"C:\Test");
foreach (string filetoDelete in files)
{
File.Delete(filetoDelete);
}
}
}
}
}
hope it is clear enough.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码:
您是否应该删除刚刚处理的文件,或者至少删除当前正在处理的目录中的文件,而不是“C:\Test”中的文件?
Your code:
Shouldn't you be deleting the file you just processed, or at least files from the dir you are currently processing, not files from "C:\Test"?
我不太确定我是否正确理解您的要求,但对我来说,解决方案似乎非常微不足道,如下所示:
换句话说,从第二个(嵌套)
foreach
移动文件删除代码> 进入新代码。如果这不是您所要求的,请澄清。
I'm not very sure if I'm right understood what you're asking for, but to me it seems solution pretty trivial, like this:
In other words, move file deletion from the second (nested)
foreach
into the new one.If this is not what you're asking for, please clarify.