Channels ▼
RSS

.NET

Accessing Environment Variables


Accessing Environment Variables

Windows Q&A
January 7, 2005


Accessing Environment Variables

How do I access the values of custom environment variables from within my application?

Many applications (particularly older ones) utilize environment variables to customize their configuration or alter their execution. They have the advantage of being easy to specify and modify, are simple, and are widely understood by developers (and quite a few users). Early versions of Windows used environment variables extensively, although the practice has fallen out of use somewhat with alternate ways to specify such information, such as file-based designs (.INI, .NET’s .config, custom XML, etc.), programmatic designs (COM Automation, plugins, etc.), and the registry. However, they are still used even by the newest tools such as Visual Studio .NET 2003 (PATH, LIB, INCLUDE, TEMP, etc.).

Creating or modifying environment variables through the Windows UI is simple, although it has changed over the years and various releases of Windows. On this Windows XP machine I’m writing on, I click on the properties menu item for My Computer and see the following:

Figure 1: My Computer Properties

Clicking on the Environment Variables button shows the following dialog:

Figure 2: Environment Variables

The dialog’s buttons make it pretty clear how to add, edit, and remove variables. Typically, but not always, a variable will accommodate multiple values by separating them with semicolons—the PATH variable is the most famous one for doing this. However, there are examples such as the TEMP variable that only accommodate a single value.

Assuming your application needs to access a variable from the environment—whether a custom one you created yourself or a common one such as TEMP—the process is straightforward. The Windows SDK provides a function named ExpandEnvironmentStrings, which takes three parameters—the first is the environment variable you want to expand, the second is a buffer that will be updated with the variable’s current value, and the third is the size of the buffer passed in. If you are unsure of the size of the value that may be set for the variable, it’s best to use a large size like 32K or greater.

Here’s some code to illustrate:

std::string GetEnvVar(std::string sVar)
{
	char buffer[32000];
	ZeroMemory(buffer,sizeof(buffer));
	ExpandEnvironmentStrings( sVar.c_str(),buffer,sizeof(buffer) );
	sVar = buffer;
}
<P>
void main()
{
	std::string sValue= GetEnvVar( "%PATH%);
}

Notice the use of the % symbol to wrap the variable that is needed. This is required by the API. Not doing so will call the function to fail and return nothing but zero, indicating an error. However, we'll see a bit later why the use of the % symbol adds horsepower to this function.

An alternative is to call the function and rely on the return value to indicate the size that is needed—an initial call with a buffer size of 0 will return a DWORD with the number of bytes necessary to contain the value. A subsequent call can then be made with the proper size buffer.

Here’s some final code that shows this:

std::string GetEnvVar(std::string sVar)
{
	std::string sRet;
	char* buffer = NULL;
	DWORD sz = ExpandEnvironmentStrings( sVar.c_str(),buffer,0 );
	if ( sz > 0 )
	{
		buffer = new char[ sz+1 ];
		ZeroMemory(buffer,sz+1);
		ExpandEnvironmentStrings( sVar.c_str(),buffer,sz );
		sRet = buffer;
		delete []buffer;
	}
	return sRet;
}

It takes a bit more code to handle allocating the necessary RAM, but obviously this code is more robust than hardwiring the buffer size to 32K or so.

If the variable doesn’t exist in the environment, ExpandEnvironmentStrings returns 0, indicating an error condition. The function is also case-insensitive when looking up variables, which is handy—most of the time, they are uppercase from tradition, but sometimes you find mixed or lowercase ones.

A final tip about ExpandEnvironmentStrings—the first parameter may contain one or more environment variables embedded in a string. Any variables that are found in the environment are replaced in the passed string with their values. This can be useful if you want to blindly pass in values (such as command-line strings), which may or may not have environment variable references and just have them expanded before you begin processing. Nonenvironment variable text is ignored and unaffected. This is the reason behind why the environment variables passed in the first parameter must be wrapped with the % symbol—it allows the parser inside the function to find the variables since they must follow a specific format.


Mark M. Baker is the Chief of Research & Development at BNA Software located in Washington, D.C.
Do you have a Windows development question? Send it to markbaker-winqa8364@mailblocks.com.



Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video