Windows窗体中未经授权的异常-C#
我正试图通过代码删除“文件路径”中存在的文件。但是当我试图删除文件时,我得到了“未经授权的异常”。我知道这是因为我没有删除文件的权限。然后我编写了“SetAccessRule”方法。但不幸的是,这并没有帮到我。任何帮助都将不胜感激Windows窗体中未经授权的异常-C#,c#,winforms,exception,C#,Winforms,Exception,我正试图通过代码删除“文件路径”中存在的文件。但是当我试图删除文件时,我得到了“未经授权的异常”。我知道这是因为我没有删除文件的权限。然后我编写了“SetAccessRule”方法。但不幸的是,这并没有帮到我。任何帮助都将不胜感激 public bool deleteAppExecutable(string filePath) { try { if (File.Exists(filePath)) { SetAccessRul
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);
}
你能告诉我们更多关于你要删除的目录文件的信息吗?它是否在另一台联网服务器上?它是否已经通过其他方式使用?也可能是程序集信任问题。您说
filePath
是一个文件,所以您应该使用FileInfo
而不是DirectoryInfo
FileInfo
还有一个SetAccessControl
方法。@EvanAnger:要删除的文件是使用C#开发的.exe文件code@KingKing:将尝试使用FileInfo并回复您。@KingKing:尝试使用FileInfo…仍然显示未经授权的异常。