批处理文件写入空文件

本文关键字:文件 批处理文件 | 更新日期: 2023-09-27 17:56:19

我写单元测试。代码调用带有参数的 cmd 并将结果写入文件。但结果这是文件是空的。你能帮我解决它吗?

String command = @"tf workspaces /owner:* /computer:* /server:http://servertfs:8080/tfs/Default/  > C:'Test'test1.txt";
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = command;
using (Process exeProcess = Process.Start(startInfo))
{
    exeProcess.WaitForExit();
}

批处理文件写入空文件

您可以将ProcessStartInfo.RedirectStandardOutput设置为true,然后通过Process.StandardOutput获取输出,而不是将> C:'Test'test1.txt附加到命令中。

String command = @"tf workspaces /owner:* /computer:* /server:http://servertfs:8080/tfs/Default/";
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = command;
startInfo.RedirectStandardOutput = true;
using (Process exeProcess = Process.Start(startInfo))
{
    string output = exeProcess.StandardOutput.ReadToEnd();
    exeProcess.WaitForExit();
}

您可以将输出放入所需的文件或直接使用它。