使用c#中的New Process(),如何将命令行文本复制到文本文件中

本文关键字:文本 命令行 复制 文件 New 中的 Process 使用 | 更新日期: 2023-09-27 18:19:22

我想用参数-a、-c和3400@takd运行lmutil.exe,然后将命令行提示符生成的所有内容放入一个文本文件中。我下面的代码不起作用。

如果逐级执行这个过程,就会得到类似"抛出了一个System类型的异常"这样的错误。InvalidOperationException "

        Process p = new Process();
        p.StartInfo.FileName = @"C:'FlexLM'lmutil.exe";
        p.StartInfo.Arguments = "lmstat -a -c 3400@tkad>Report.txt";
        p.Start();
        p.WaitForExit();

我想要的只是将命令行输出写入Report.txt

使用c#中的New Process(),如何将命令行文本复制到文本文件中

要获得Process输出,您可以使用这里记录的StandardOutput属性。

然后你可以把它写入一个文件:

Process p = new Process();
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = @"C:'FlexLM'lmutil.exe";
p.StartInfo.Arguments = "lmstat -a -c 3400@tkad";
p.Start();
System.IO.File.WriteAllText("Report.txt", p.StandardOutput.ReadToEnd());
p.WaitForExit();
p.Close();

您不能使用>通过Process重定向,您必须使用StandardOutput。还要注意,要使其工作,StartInfo.RedirectStandardOutput必须设置为true。