简体   繁体   中英

Maintaining variables when executing cmd from C# application

I want to call some cmd prompt commands from a .net C# application. However before the command is run I need to set up a varaibles within a batch file. Is there a way to maintain the variables to subsequent calls to the command prompt?

I provide an example below of the problem.

Say I have a simple batch file C:\\setEnv.bat containing

set notepad=C:\windows\system32\notepad.exe

Then if I have C# code like thus:

var proc1 = new ProcessStartInfo();
string cmd1 = @"CALL C:\setEnv.bat";
string cmd2 = @"ECHO notepad=%notepad%>C:\test.txt";
proc1.UseShellExecute = true;

var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C " +cmd1;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
startInfo.Arguments = "/C " + cmd2;
process.Start();
process.WaitForExit();

Now I'm guessing that the /C is terminating the command prompt thus losing my variables but if I don't have it then the cmd prompt doesn't return after finishing the command.

I thought I could double the cmd1 & cmd2 to a single call but then I would need to do that for every call to the cmd prompt and feels a little redundant calling C:\\setenv.bat again and again.

You may use way in this question

For example, use command "set" in cmd1:

string cmd1 = "\" CALL C:\\setEnv.bat && set \"";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
//...
process.Start();
string variables = process.StandardOutput.ReadToEnd();
// next parse variables string

And before start second process set parsed variables in "startInfo.EnvironmentVariables"

A few issues/ideas:

1) How many values to you need to track from one execution to the next? Primarily, can you just use the errorlevel return value or do you need more details?

2) Can you pipe the results of the first directly into the second as one call?

3) Can you output the values from the first call to a file and in the 2nd call, pipe that as input into the 2nd cmd?

4) I assume that you have some processing that is done after the first cmd is run, but before the 2nd cmd is called. Could you create an .exe that can be called by the 1st batch file (after the other code) that does that processing. That way, you have 3 cmds all of which can be run in the same environment and your variables stick around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM