c# 未授权异常

标签 c#

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

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

enter image description here

Source

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

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

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

Directory.Delete(recentDocumentsFolder, true);

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

相关文章:

c# - 为什么我的 Ajax 不工作?

c# - 在 SQL Server 上筛选 Entity Framework 结果

c# - 路由,如果包含单词则匹配特定的url

c# - 如何在.net winforms中执行在运行时生成的代码事件?

c# - 如何在JavaScript中设置asp.net隐藏字段并在后面的C#代码中访问该值

c# - SpreadsheetGear CopyFromDataTable 单元格格式

c# - 在 SSH.NET 中执行长时间命令并在 TextBox 中连续显示结果

c# - 将 Datagridview 值更新到数据库中

c# - 在不同类型的数组上调用 item 方法

C# AxWindowsMediaPlayer 循环