【问题标题】:C# deleting a read only fileC#删除只读文件
【发布时间】:2015-01-01 15:04:54
【问题描述】:

您好,我基本上是想在我的应用程序中创建一个按钮,该按钮可以删除我的 %appdata% 文件夹,但是它一直说无法删除只读文件,所以我决定做一些谷歌搜索,但问题仍然存在这是我最近的尝试仍然没有任何线索?

我要删除的是 %appdata%/test,它也有子文件夹。

   private void ClearButton_OnClick(object sender, RoutedEventArgs e)
    {
        string filepath = (Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test"));
        //Get Currently Applied Access Control
        FileSecurity fileS = File.GetAccessControl(filepath);

        //Update it, Grant Current User Full Control
        SecurityIdentifier cu = WindowsIdentity.GetCurrent().User;
        fileS.SetOwner(cu);
        fileS.SetAccessRule(new FileSystemAccessRule(cu, FileSystemRights.FullControl, AccessControlType.Allow));

        //Update the Access Control on the File
        File.SetAccessControl(filepath, fileS);

        //Delete the file
        File.Delete(filepath);
        Process.Start(Application.ResourceAssembly.Location);
        Environment.Exit(0);
    }

【问题讨论】:

标签: c#


【解决方案1】:

尝试使用管理员权限运行应用程序。有时 C 盘需要管理员权限。

【讨论】:

    【解决方案2】:

    您可能需要先取得所有权,如果您没有

    using System.IO;
    using System.IO;
    using System.Security.AccessControl;
    using System.Security.Principal;
    
    //Get Currently Applied Access Control
    FileSecurity fileS = File.GetAccessControl(filepath);
    
    //Update it, Grant Current User Full Control
    SecurityIdentifier cu = WindowsIdentity.GetCurrent().User;
    fileS.SetOwner(cu);
    fileS.SetAccessRule(new FileSystemAccessRule(cu, FileSystemRights.FullControl, AccessControlType.Allow));
    
    //Update the Access Control on the File
    File.SetAccessControl(filepath, fileS);
    
    File.SetAttributes(filePath, FileAttributes.Normal);
    File.Delete(filePath);
    

    此外,您需要以管理权限运行应用程序。

    为此,右键单击您的项目,添加 -> 新建项目 -> 应用程序清单文件

    然后替换这一行

    <requestedExecutionLevel level="asInvoker" uiAccess="false" />
    

    有了这个

    <requestedExecutionLevel level="requireAdministrator" uiAccess="true" />
    

    它将以管理员权限运行您的应用程序。

    【讨论】:

    【解决方案3】:

    在调试模式下运行我的应用程序时遇到了同样的问题。我可以通过简单地设置 File.IsReadOnly = false; 来解决它。然后删除没有问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      • 2011-03-04
      • 2010-10-11
      • 1970-01-01
      相关资源
      最近更新 更多