如何将 FINDSTR 的输出从 C# 保存到文本文件?

How to save output of FINDSTR from C# to a text file?

我正在尝试 运行 来自 C# 的 findstr 命令(Windows 表单)。

我已经在命令提示符下正常尝试了,效果很好。

string CD = @"P:\FIles";
Process p = new Process();
p.StartInfo = new ProcessStartInfo("findstr.exe");
p.StartInfo.Arguments = "-M -S" + " " + quote + txtSearch.Text + quote + " " + quote+"dummy.txt"+quote + " > " + "C:\Temp\results.txt" ;
p.StartInfo.WorkingDirectory = CD;
p.StartInfo.ErrorDialog = true;
p.StartInfo.UseShellExecute = false;

p.Start();

p.WaitForExit();

我想将输出保存到另一个具有特定位置的文本文件。

如果我能以某种方式 return 将结果直接返回到它自身的形式并且可能将每一行复制到列表框中,那就更好了。

您可以通过读取 "StandardOutput" 流来读取控制台应用程序的输出。但是你必须先把StartInfo.RedirectStandardOutput 属性设置成"true"。

你的情况:

    string CD = @"P:\FIles";
    Process p = new Process();
    p.StartInfo = new ProcessStartInfo("findstr.exe");
    p.StartInfo.Arguments = "-M -S" + " " + quote + txtSearch.Text + quote + " " + quote+"dummy.txt"+quote + " > " + "C:\Temp\results.txt" ;
    p.StartInfo.WorkingDirectory = CD;
    p.StartInfo.ErrorDialog = true;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;

    p.Start();

    p.WaitForExit();

    string sTest = p.StandardOutput.ReadToEnd();