Skip to main content
 首页 » 编程设计

c# 未授权异常

2024年02月05日9sxdcgaq8080

嘿伙计们,我遇到了这个错误我尝试以管理员身份运行程序,运气不好仍然遇到这个错误我不明白为什么它不能清除最近文档文件夹中的快捷方式,这是我的代码:

//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 时

Source

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

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

如果你想删除整个目录以及其中的任何文件和子文件夹,你可以调用

Directory.Delete(recentDocumentsFolder, true);