0

Is it possible to preserve OS variables being used as command line arguments.

For example: Test.exe %Temp%

has the expanded temp variable, not the variable itself.

So:

  Console.WriteLine("Args:\n");
  foreach (string cl in args)
  {
    Console.WriteLine(cl);
  }

Outputs something like:

Args:

C:\Temp

What I need is for the variable to remain unexpanded:

Args:

%Temp%
Martin.
  • 10,494
  • 3
  • 42
  • 68
Daro
  • 1,990
  • 2
  • 16
  • 22
  • I should mention that I'm referencing some code I posted some time ago at [link]http://stackoverflow.com/a/8029567/1027551. %Temp% works fine there, but not as an argument... – Daro Jan 10 '12 at 17:40
  • 1
    This is actually completely unrelated to C# and is just the way the console terminal (or rather, Windows’ mechanism for invoking applications) works. – Konrad Rudolph Jan 10 '12 at 17:41
  • i wonder if you could just parse that and when you find the special characters '%' for example.. replace it with it's ASCII value or char value but the question would be why do you want to keep the %Temp% knowing that the system by default will see that as c:\Temp for example – MethodMan Jan 10 '12 at 17:44
  • Konrad: Yes, but I was hoping that some method could get the actual commandline. - DJ: That's my problem the %s are removed. – Daro Jan 10 '12 at 19:52

2 Answers2

3

You need to escape the percentages like this: Test.exe ^%Temp^%. With this you should get the desired output.

Smi
  • 13,850
  • 9
  • 56
  • 64
0

Did you try:

Test.exe "%Temp%"

That may be enough to prevent the OS from expanding the environment variable.

Either that, or consider if you really need to pass the OS-specific form of the environment variable name. Without knowing any specifics of Test.exe perhaps you could just use:

Test.exe Temp

Then inside Test.exe you can simply retrieve the environment variable by name. I think this would be more in line with convention anyway.

Also (again, without more detail, it's hard to tell) it seems odd to pass in the name of an environment variable at runtime. Is the name of the variable dynamic? Could you put the name of the environment variable into one that's static, so that Test.exe can just retrieve the name from a consistently-named variable like "Test_exe_init"?

set Text_exe_init=Some_Dynamic_Variable_Name
Test.exe

And inside Text.exe it uses

string foo=GetEnvironmentVariable("Test_exe_init");

How do I get and set Environment variables in C#?

Just a thought...

Community
  • 1
  • 1
JMD
  • 7,331
  • 3
  • 29
  • 39
  • Yes. "%Temp%" displays "C:\Temp", %%Temp%% shows %C:\Temp%, etc. Path is just one example. I need to create user and system variables based on system Variables. Doing a set before hand would work, but I can't always use a bat or cmd file... – Daro Jan 10 '12 at 19:57