我如何直接在C#中执行批处理命令?

嗨,我对c#和批处理文件有疑问。 我想执行批处理命令并将输出保存在c#中的字符串中。 但我只能执行该文件但不能将此内容保存在字符串中并在文本框中显示。

我的批处理文件:

@echo关闭

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

这是我的c#代码:

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; } 

我想输出ia stirng,如果我能做到这一点,我希望我没有批处理文件。 我想直接在c#中执行这个batvchcommand …我可以这样做吗?

不需要使用“CMD.exe”执行命令行应用程序或检索输出,可以直接使用“lmxendutil.exe”。

试试这个:

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

做你的修改以在那里使用“命令”。

我希望这有帮助。

它不像我的批处理文件将产生任何输出。 如果在命令行中运行它,是否看到输出? 您的bat文件行中有重定向>运算符,因此您似乎正在将输出发送到xml文件。

如果您已将输出保存到xml文件,则可能只需在进程退出后使用C#加载即可。