C# 是否可以进行不可停止的删除? (紧凑框架)
给定一个文件夹,我想确保删除该目录上的所有文件。 我知道可能存在 IOExceptions 或 Access Denied 错误,但如何将它们放在一边并继续删除我实际上可以删除的文件?这可能吗? 请告诉我可以从哪里开始。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您想删除所有可以删除的文件,您可以创建一个文件列表(对于子目录递归),然后单独删除它们,跳过那些引发异常的文件。
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.
如果您循环遍历目录中的文件并在 try/catch 中删除每个文件,那么即使在发生异常后也可以继续。如果您尝试删除整个目录,那么一旦失败,它就会失败。
编辑:按要求编写代码
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
?如果您遇到 IO 问题或者您无权访问这些文件,则您无法删除它们。他们是例外。他们告诉你“嘿,出了问题,这就是原因”。它们不是您可以忽略的礼貌警告消息,它们是您的删除不起作用的原因。
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:
...as suggested above, try...catch around various parts will cope with the inability to delete certain files.
如果你按照 @Will A 的建议稍微改变一下顺序,并添加一行来删除目录本身 - 它应该可以解决问题。类似的东西
应该清除空文件夹
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
it should clear the empty folders