C#访问路径被拒绝

时间:2016-02-05 02:23:40

标签: c#

嘿伙计们,所以我正在编写一个程序,删除某些目录文件,主要是临时文件,除非我收到错误,即使知道我添加了一个catch块。 System.UnauthorizedAccessException。在catch ioexception上我得到了错误:

private void DeleteInternetFiles(string internetDirectory)
{
    DirectoryInfo internetTempStorage = new DirectoryInfo(internetDirectory);
    try
    {
        //this will delete files
        foreach (FileInfo getNetFileInfo in internetTempStorage.GetFiles())
        {
            getNetFileInfo.Delete();
        }

        //this will loop through and delete folders
        foreach (DirectoryInfo tempDirectoryInformation in internetTempStorage.GetDirectories())
        {         
            tempDirectoryInformation.Delete();
        }
    }

    //catch io exception and try delete file again
    catch (IOException)
    {
        //delete file in this directory
        File.Delete(internetDirectory);

        //delete folders in this directory
        Directory.Delete(internetDirectory);
    }

    //catch access exception and delete file again
    catch (UnauthorizedAccessException)
    {
        //delete file in this directory
        File.Delete(internetDirectory);

        //delete folders in this directory
        Directory.Delete(internetDirectory);

    }
}

以下是我称之为方法的方法:

if (checkBox1.Checked)
{
    DeleteInternetFiles(@"C:\Users\" + Environment.UserName + @" \AppData\Local\Microsoft\Windows\Temporary Internet Files");
}

3 个答案:

答案 0 :(得分:2)

你在catch区内第二次调用File.Delete(internetDirectory);似乎可能是问题所在。尝试删除文件时,程序已经遇到错误,然后再次尝试。可能会发生两件事:

  1. 执行程序的用户帐户没有权限 删除另一个用户目录中的文件。

  2. 某些文件仍在使用中,因此无法删除(例如 目前在Internet Explorer中打开。

  3. 您可能想要在C# - How to Delete temporary internet files中研究回复。请注意关于可能必须“杀死IE”的评论。

答案 1 :(得分:0)

我在此处看到的问题是,您执行的删除操作需要Administrator个权限。

您可以尝试右键单击>以管理员身份运行应用程序,然后执行操作。

如果要提示用户提升您的应用程序,可以执行此操作。

Force application to Run as Administrator [Winforms only]

答案 2 :(得分:0)

您收到此错误,因为您尝试删除的文件或文件夹没有此访问权限。

在您执行删除操作时,由于某些文件当前正在使用,可能会发生这种情况。

使用文件的可能性更大,因为您从Windows OS用于临时使用的文件夹中删除。

相关问题