How I can execute a Batch Command in C# directly?
Asked Answered
C

2

11

I want to execute a batch command and save the output in a string, but I can only execute the file and am not able to save the content in a string.

Batch file:

@echo off

"C:\lmxendutil.exe" -licstatxml -host serv005 -port 6200>C:\Temp\HW_Lic_XML.xml notepad C:\Temp\HW_Lic_XML.xml

C# code:

private void btnShowLicstate_Click(object sender, EventArgs e)
{
     string command = "'C:\\lmxendutil.exe' -licstatxml -host lwserv005 -port 6200";

     txtOutput.Text = ExecuteCommand(command);
}

static string ExecuteCommand(string command)
{
     int exitCode;
     ProcessStartInfo processInfo;
     Process process;

     processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
     processInfo.CreateNoWindow = true;
     processInfo.UseShellExecute = false;
     // *** Redirect the output ***
     processInfo.RedirectStandardError = true;
     processInfo.RedirectStandardOutput = true;

     process = Process.Start(processInfo);
     process.WaitForExit();

     // *** Read the streams ***
     string output = process.StandardOutput.ReadToEnd();
     string error = process.StandardError.ReadToEnd();

     exitCode = process.ExitCode;

     process.Close();

     return output; 
}

I want the output in a string and do this directly in C# without a batch file, is this possible?

Comeaux answered 21/5, 2013 at 9:55 Comment(2)
#5519828Ladonnalady
look to my update ...Comeaux
P
9

Don't need to use "CMD.exe" for execute a commandline application or retreive the output, you can use "lmxendutil.exe" directly.

Try this:

processInfo = new ProcessStartInfo();
processInfo.FileName  = "C:\\lmxendutil.exe";
processInfo.Arguments = "-licstatxml -host serv005 -port 6200";
//etc...

Do your modifications to use "command" there.

I hope this helps.

Peppers answered 21/5, 2013 at 19:47 Comment(0)
K
2

It doesn't look to me like your batch file will produce any output. If you run it in the command line, do you see an output? You have the redirection > operator in your bat file line, so it seems like you're sending output to the xml file.

If you have saved the output to an xml file, maybe you should just load that using C# once your process exits.

Kiki answered 21/5, 2013 at 10:8 Comment(1)
look to my update...with my command it don't work but with echo test i get testComeaux

© 2022 - 2024 — McMap. All rights reserved.