Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 441
Tarasov Avatar asked May 21 '13 09:05

Tarasov


People also ask

How do I run a batch file in a loop?

To run or execute the file, double click on it or type the file name on cmd. Example 1: Let's start by looping a simple command, such as 'echo'. 'echo' commands is analogous to 'print' command like in any other programming languages.

How do you write a batch command?

To create a Windows batch file, follow these steps: Open a text file, such as a Notepad or WordPad document. Add your commands, starting with @echo [off], followed by, each in a new line, title [title of your batch script], echo [first line], and pause. Save your file with the file extension BAT, for example, test.


1 Answers

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.

like image 130
ElektroStudios Avatar answered Sep 18 '22 20:09

ElektroStudios