清除浏览器Cookie时出错c#

时间:2013-07-06 13:16:19

标签: c# watin

我想用以下代码清除IE中的所有Cookie:

public void ClearCookie()
    {
        string[] Cookies =
            System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache));
        foreach (string currentFile in Cookies)
        {
            try
            {
                System.IO.File.Delete(currentFile);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

但是当我运行时,messageBox会显示内容:进程无法访问该文件:C:\ User ... \ Microsoft \ Windows \ Temporary InterNet Files \ counter.dat'因为它正被使用另一个过程 我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以专注于指定确切的错误类型,而不是捕获常规异常,例如:

        try
        {
            File.Delete(currentFile);
        }
        catch (IOException ex)
        {
            // file is locked, in use or has an open handle in another application
            // so skip it
        }
        catch (UnauthorizedAccessException ex)
        {
            // you don't have permissions to delete the file
        }

这可以让您更好地指出如何处理可能发生的文件IO异常的多样性。另外,请查看MSDN's File.Delete documentations以获取此方法可能引发的不同类型错误的更多信息。