【问题标题】:Demand doesn't throw exception while the try to write to a file throws UnauthorizedAccessException尝试写入文件引发 UnauthorizedAccessException 时,需求不会引发异常
【发布时间】:2013-06-27 10:32:25
【问题描述】:

当 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.");
    }

【问题讨论】:

  • 你尝试过使用 permission.Assert() 吗?
  • 试过了。同样的结果:UnauthorizedAccessException

标签: c# .net security code-access-security


【解决方案1】:

FileIOPermission 检查 .NET 代码访问安全模型下的代码权限,而不是 Windows 文件系统中的用户权限。由于您的代码在管理员帐户下运行,因此该代码可能具有足够的 FileIOPermission,因此在不同的用户帐户下运行时需求通过也就不足为奇了。

由于对 FileIOPermission 的需求确实通过了,代码尝试保存文件,即在非管理员场景下遇到用户权限不足的情况。 UnauthorizedAccessException 是操作系统拒绝访问目标资源时的预期异常类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    相关资源
    最近更新 更多