tags:

views:

68

answers:

4

In my application, I have defined the following:

public static readonly string NOTEPAD = "%windir%\\notepad.exe";

I can type in the text value of NOTEPAD into the Run command on my Win7 machine, and Notepad will open.

However, from within my Visual Studio C# project, the Write Line routine will fire every time:

  if (!File.Exists(NOTEPAD)) {
    Console.WriteLine("File Not Found: " + NOTEPAD);
  }

Does Visual Studio not understand %windir%?

+1  A: 

Just have a closer Look at the Class Environment. The Environment Variable is SystemRoot, so you can use Environment.GetEnvironmentVariable("windir") (or something like that)

http://msdn.microsoft.com/en-us/library/system.environment.getenvironmentvariable.aspx

The console "Resolves" the %windir% environment variable to the correct path. You need to use the above function to do the same within your application.

Caladain
+1  A: 

When looking on my windows XP box, the location of notepad is:

%SystemRoot%\system32\notepad.exe

Not:

%windir%\notepad.exe

You also need to make sure that these environment variables are resolved correctly - use Environment.GetEnvironmentVariable and Path.Combine to build up the correct path:

string root = Environment.GetEnvironmentVariable("SystemRoot");
string path = Path.Combine(root, "system32", "notepad.exe");
Oded
On mine it's in C:\WINDOWS as well as C:\WINDOWS\system32. I checked another box and it's in both places as well.
dcp
@dcp - Fair enough. I think MS decided on placing it in two locations for some versions. But for server 2008 it is only in system32 - see this blog post from Raymond Chen: http://blogs.msdn.com/b/oldnewthing/archive/2010/01/28/9954432.aspx
Oded
I'm curious if "system32" changes on 64-bit systems or if it is case sensitive. I had hard coding strings.
jp2code
@jp2code - Just checked my Windows Server 2008 R2 64bit virtual machine, and "system32" is there, live and kicking with "notepad.exe" in place...
Oded
+1  A: 

Use Environment.GetEnvironmentVariable("windir");

So you could declare it like this:

public static readonly string NOTEPAD = Environment.GetEnvironmentVariable("windir") + "\\notepad.exe";
dcp
+3  A: 

Instead of expanding the variable manually as suggested by the other answers so far, you can have the Environment class do this for you just like the Run command does:

if (!File.Exists(Environment.ExpandEnvironmentVariables(NOTEPAD))) {
  Console.WriteLine("File Not Found: " + NOTEPAD);
}

See http://msdn.microsoft.com/en-us/library/system.environment.expandenvironmentvariables.aspx

Lucero
+1 For keeping it closely relevant to the OP's example code, and providing a fix therein.
maxwellb
I actually liked this answer better, so I changed my mark. All answers seem to work, though.
jp2code
@jp2code, thanks! :-)
Lucero