当 Visual Studio 在管理员帐户下运行时,下面的代码工作正常。 但是当VS在非特权帐户下运行时,Save()方法会抛出UnauthorizedAccessException,但在这种情况下我很不明白为什么Demand()不会抛出SecurityException。
public void SetLoggingLevel(string loggerRuleName, LoggingLevel loggingLevel)
{
foreach (XElement loggerRule in GetLoggerElements().Where(loggerRule => CompareWithLoggerRule(loggerRuleName, loggerRule)))
{
loggerRule.SetAttributeValue("minlevel", loggingLevel.ToString());
var permission = new FileIOPermission(FileIOPermissionAccess.Write, Source);
permission.Demand();
_configFile.Save(Source); //Writing to the xml-file
return;
}
throw new RuleNotFoundException("The rule not found.");
}
最佳答案
FileIOPermission 检查 .NET 代码访问安全模型下的代码权限,而不是 Windows 文件系统中的用户权限。由于您的代码在管理员帐户下运行,代码可能具有足够的 FileIOPermission,因此当在不同的用户帐户下运行时需求通过也就不足为奇了。
由于对 FileIOPermission 的需求确实通过了,因此代码会尝试保存文件,这是在非管理员场景中遇到用户权限不足的情况。 UnauthorizedAccessException是操作系统拒绝访问目标资源时的预期异常类型。
关于c# - 当尝试写入文件抛出 UnauthorizedAccessException 时,需求不会抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17340805/