问题描述
我想执行一个批处理命令并将输出保存在一个字符串中,但是我只能执行该文件并且无法将内容保存在一个字符串中.
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.
批处理文件:
@echo 关闭
"C:lmxendutil.exe" -licstatxml -host serv005 -port6200>C:TempHW_Lic_XML.xml 记事本 C:TempHW_Lic_XML.xml
"C:lmxendutil.exe" -licstatxml -host serv005 -port 6200>C:TempHW_Lic_XML.xml notepad C:TempHW_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;
}
我想要一个字符串的输出,并直接在 C# 中执行此操作而无需批处理文件,这可能吗?
I want the output in a string and do this directly in C# without a batch file, is this possible?
推荐答案
不需要使用CMD.exe"来执行命令行应用程序或检索输出,您可以直接使用lmxendutil.exe".
Don't need to use "CMD.exe" for execute a commandline application or retreive the output, you can use "lmxendutil.exe" directly.
试试这个:
processInfo = new ProcessStartInfo();
processInfo.FileName = "C:\lmxendutil.exe";
processInfo.Arguments = "-licstatxml -host serv005 -port 6200";
//etc...
进行修改以在此处使用命令".
Do your modifications to use "command" there.
我希望这会有所帮助.
这篇关于如何直接在 C# 中执行批处理命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!