嗨,我遇到了这个错误,我试图以管理员身份运行程序,但还是没有运气得到此错误,我不明白为什么它不能清除最近文档文件夹中的快捷方式,这是我的代码:

//this will delete the the files in the Recent Documents directory
private void DeleteRecentDocuments(string RecentDocumentsDirectory)
{
    //this is the directory and parameter which we will pass when we call the method
    DirectoryInfo cleanRecentDocuments = new DirectoryInfo(RecentDocumentsDirectory);

    //try this code
    try
    {
        //loop through the directory we use the getFiles method to collect all files which is stored in recentDocumentsFolder variable
        foreach(FileInfo recentDocumentsFolder in cleanRecentDocuments.GetFiles())
        {
            //we delete all files in that directory
            recentDocumentsFolder.Delete();
        }
    }
    //catch any possible error and display a message
    catch(Exception)
    {
        MessageBox.Show("Error could not clean Recent documents directory, please try again");
    }
}


我在上面调用了此方法,但是dw认为调用该方法和参数的原因太多了。如果您愿意,我可以将其发布到。

最佳答案

根据MSDN,FileInfo.Delete()将在以下情况时抛出UnauthorizedAccessException

c# - C#未经授权的异常-LMLPHP

Source

为了删除目录中的所有文件可以做

foreach (string filePath in Directory.GetFiles(recentDocumentsFolder))
{
    File.Delete(filePath);
}


如果要删除整个目录以及其中的所有文件和子文件夹,可以调用

Directory.Delete(recentDocumentsFolder, true);

关于c# - C#未经授权的异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36805793/

10-11 18:29