Microsoft Knowledge Base Email Alertz

(829145) - The System.Environment class has methods to read the environment variables. However, this class has no method to set the environment variables for the current process.

Search KbAlertz

Advanced Search

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]











Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks

Article ID: 829145 - Last Review: December 3, 2007 - Revision: 3.5

System.Environment class does not have a method to set the environment variable for the current process

SYMPTOMS

The System.Environment class has methods to read the environment variables. However, this class has no method to set the environment variables for the current process.

WORKAROUND

To work around this problem, use the interop services to set the environment variables. You can set an environment variable by using the Microsoft Platform Software Development Kit (SDK) SetEnvironmentVariable function.

To set an environment variable by calling the Platform SDK SetEnvironmentVariable function, follow these steps:
  1. Start Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click New Project.
  3. In the New Project dialog box, click Visual C# Projects.

    Note In Visual Studio 2005, Visual C# Projects is be changed to Visual C#.
  4. Under Templates, click Console Application, and then click OK. By default, the Class1.cs file is created.
  5. In the code view of the Class1.cs file, specify the using statement to declare the namespaces so that you do not have to qualify the declarations later in the code. Paste the following code in the Class1.cs file:
    using System;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Security.Permissions;
    
  6. Declare the static method and the extern method. Use the DllImport attribute to import the Kernel32.dll file. This declaration indicates that the definition of the function is outside the code. To do this, paste the following code in the Class1.cs file:
    // Import the Kernel32 dll file.
    [DllImport("kernel32.dll",CharSet=CharSet.Auto, SetLastError=true)]
    
    [return:MarshalAs(UnmanagedType.Bool)]
    
    // The declaration is similar to the SDK function
    public static extern bool SetEnvironmentVariable(string lpName, string lpValue);
    
  7. Paste the following code in the Class1.cs file to add a static method in the class that calls the SetEnvironmentVariable method and that sets the environment variable:
    public static bool SetEnvironmentVariableEx(string environmentVariable, string variableValue)
    {
    	try
    	{
    		// Get the write permission to set the environment variable.
    		EnvironmentPermission environmentPermission = new EnvironmentPermission(EnvironmentPermissionAccess.Write,environmentVariable);
    
    		environmentPermission.Demand(); 
    
    		return SetEnvironmentVariable(environmentVariable, variableValue);
    	}
    	catch( SecurityException e)
    	{
    		Console.WriteLine("Exception:" + e.Message);
    	}
    	return false;
    }
  8. Paste the following code in the Main method to set an environment variable:
    // Create a sample environment variable and set its value (for the current process).
    SampleSetEnvironmentVariable.SetEnvironmentVariableEx("TESTENV", "TestValue");
    
  9. Paste the following code to display the environment variable value:
    // Verify that environment variable is set correctly.
    Console.WriteLine("The value of TESTENV is: " + Environment.GetEnvironmentVariable("TESTENV"));

Complete Code Sample

using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;

namespace SetEnv
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	public class SampleSetEnvironmentVariable
	{
// Import the kernel32 dll.
[DllImport("kernel32.dll",CharSet=CharSet.Auto, SetLastError=true)]

[return:MarshalAs(UnmanagedType.Bool)]

// The declaration is similar to the SDK function
public static extern bool SetEnvironmentVariable(string lpName, string lpValue);

		public SampleSetEnvironmentVariable()
		{
		}

		public static bool SetEnvironmentVariableEx(string environmentVariable, string variableValue)
		{
			try
			{
				// Get the write permission to set the environment variable.
				EnvironmentPermission environmentPermission = new EnvironmentPermission(EnvironmentPermissionAccess.Write,environmentVariable);

				environmentPermission.Demand(); 

				return SetEnvironmentVariable(environmentVariable, variableValue);
			}
			catch( SecurityException e)
			{
				Console.WriteLine("Exception:" + e.Message);
			}
			return false;
		}
	}


	class MyClass
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			// Create a sample environment variable and set its value (for the current process).
			SampleSetEnvironmentVariable.SetEnvironmentVariableEx("TESTENV", "TestValue");

			// Verify that environment variable is set correctly.
			Console.WriteLine("The value of TESTENV is: " + Environment.GetEnvironmentVariable("TESTENV"));
		}
	}
}

STATUS

Microsoft has confirmed that this is a problem in the Microsoft products that are listed at the beginning of this article.

REFERENCES

For more information, visit the following Microsoft Developer Network (MSDN) Web sites:
http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute(vs.71).aspx)

http://msdn2.microsoft.com/en-us/library/ms686206.aspx (http://msdn2.microsoft.com/en-us/library/ms686206.aspx)

APPLIES TO
  • Microsoft .NET Framework 2.0
  • Microsoft .NET Framework 1.1
  • Microsoft .NET Framework 1.0
  • Microsoft Visual C# 2005 Express Edition
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual Basic .NET 2002 Standard Edition
Keywords: 
kbvs2005applies kbvs2005swept kbprb kbenv kbcominterop KB829145
       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate

Rowan Report As Irrelevant  
Written: 4/21/2004 8:32 PM
Just what I was looking for, and I'm up and running - thanks