Demand doesn't throw exception while the try to write to a file throws UnauthorizedAccessException

StackOverflow https://stackoverflow.com/questions/17340805

The code below works fine when Visual Studio is running under Admin account. But when VS is running under non-priveleged account, Save() method throws UnauthorizedAccessException, but in this case I quite don't understand why Demand() doesn't throw 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 checks code permissions under the .NET Code Access Security model, not user permissions in the Windows file system. Since your code runs under an admin account, the code presumably has adequate FileIOPermission, so it is unsurprising that the demand passes when running under a different user account.

Since the demand for FileIOPermission does pass, the code attempts to save the file, which is when it runs into insufficient user permissions in the non-admin scenario. UnauthorizedAccessException is the expected exception type when the operating system denies access to the target resource.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top