Code that needs to read or write environment variables using the System.Environment class must be granted the EnvironmentPermission by code access security policy. This permission type can be used to constrain access to specific named environment variables.
To constrain code so that it can only read specific environment variables, you can use the EnvironmentPermissionAttribute together with SecurityAction.PermitOnly . The following attributes ensure that the code can only read from the username , userdomain , and temp variables.
[EnvironmentPermissionAttribute(SecurityAction.PermitOnly, Read="username")] [EnvironmentPermissionAttribute(SecurityAction.PermitOnly, Read="userdomain")] [EnvironmentPermissionAttribute(SecurityAction.PermitOnly, Read="temp")] public static string GetVariable(string name) { return Environment.GetEnvironmentVariable(name); }
To document the permission requirements of your code, and to ensure your assembly cannot load if it is granted insufficient environment variable access from code access security policy, add an assembly level EnvironmentPermissionAttribute with SecurityAction.RequestMinimum as shown in the following code.
[assembly: EnvironmentPermissionAttribute(SecurityAction.RequestMinimum, Read="username"), EnvironmentPermissionAttribute(SecurityAction.RequestMinimum, Read="userdomain"), EnvironmentPermissionAttribute(SecurityAction.RequestMinimum, Read="temp")]