Question

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.");
    }
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top