如果遇到错误,如何跳过我的代码 [英] How do I make my code skip if it hits an error

查看:111
本文介绍了如果遇到错误,如何跳过我的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的代码遇到它现在发生的错误时,如何实现它,它会跳过该文件并从下一个文件开始,让我演示。





How do I make it so when my code hits an error which it does right now, it skips that file and starts with the next one, let me demo.


private void Clear_Click(object sender, EventArgs e)
{



    string tempPath = Path.GetTempPath();
    DirectoryInfo di = new DirectoryInfo(tempPath);


    foreach (DirectoryInfo dir in di.GetDirectories())
    {
        dir.Delete(true);
    }

    foreach (FileInfo file in di.GetFiles())
    {
        try
        {
            file.Delete();
        }
        catch (Exception)
        {
            // Log error.
        }
    }

}





















它现在做的是删除我的临时文件夹中的文件和文件夹,但是当它碰到一个时我想这样做错误,当它不允许删除文件或文件正在使用时我不希望它显示错误我希望它跳过该文件并继续下一个,我将使用什么类型的循环?



我尝试了什么:



我看过什么类型循环可以工作,但我无法找到哪一个最适合我











What it does now is it deleted files and folders in my temp folder but I want to make it so when it hits an error, when its not allowed to delete a file or a file is in use I dont want it to display an error I want it to skip that file and move on to the next one, what type of loop would I use for this ?

What I have tried:

I've looked over what types of loops would work but I couldnt find which one would fit me the best

推荐答案

将文件名放入列表中。

使用for循环或每个循环处理列表。

用try-catch包装尝试删除,当它失败时记下原因和文件,或用该信息更新列表。

循环将自动移动到下一个文件
Put the filenames into a list.
Process the list with a for loop or for each loop.
Wrap the attempt to delete with a try-catch, when it fails make a note of why and which file, or update the list with that info.
The loop will automatically move onto the next file


是的,你碰到了在任何特定时刻文件的状态都可以改变的事实。有些应用程序打开它,发生了一些硬件更改,权限发生了变化等等。



您可以测试该文件,或者那个,然后,当你去采取行动,文件已经改变状态。



这里有一篇关于CP的有趣文章试图解决这个问题:[ ^ ]。



但是,即使您使用这些技术,我认为您仍然需要Try / Catch。根据总体目标的不同,我会考虑生成未删除的文件的摘要,以及相关的错误信息。
Yep, you hit the wall of the hard fact that at any given moment a file's status could be changed. Some app opened it, some hardware change happened, permissions got changed, etc.

You could test the file for this, or that, and then, when you went to take action, the file has changed state.

There's an interesting article here on CP that tried to address this issue: [^].

But, even if you use those techniques, I think you still need a Try/Catch. Depending on what the overall goal is here, I'd think about generating summaries of the files that did not get deleted, with relevant error information.


您可以使用在catch内继续



You can use continue inside the catch:

catch (Exception err)
{
   continue;
}


这篇关于如果遇到错误,如何跳过我的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆