0

我正在尝试通过代码删除“filePath”中存在的文件。但是当我尝试删除文件时出现“未经授权的异常”。我知道这是因为我无权删除文件。然后我编写了“SetAccessRule”方法。但不幸的是,这并没有帮助我。任何帮助将非常感激。

public bool deleteAppExecutable(string filePath)
{
    try
    {
        if (File.Exists(filePath))
        {
            SetAccessRule(filePath);
            File.SetAttributes(filePath, FileAttributes.Normal);
            File.Delete(filePath);                    
        }
        return true;
    }
    catch (Exception ex)
    {               
        return false;
    }
}


public void SetAccessRule(string filePath)
{
    // Create a new DirectoryInfo object.
    DirectoryInfo dInfo = new DirectoryInfo(filePath);

    // Get a DirectorySecurity object that represents the 
    // current security settings.
    DirectorySecurity dSecurity = dInfo.GetAccessControl();

    // Add the FileSystemAccessRule to the security settings. 
    dSecurity.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Delete, AccessControlType.Allow));

    // Set the new access settings.
    dInfo.SetAccessControl(dSecurity);
}
4

0 回答 0