Search code examples
c#cmdfindstr

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


I am trying to run the findstr command from C# (Windows Forms).

I have tried this normally in Command Prompt it works fine.

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();

I would like to save the output to another text file with a specific location.

It would be even better if I could somehow return the result directly back to the form it self and maybe copy each line to a list box.


Solution

  • You can read the output of a console application with reading the "StandardOutput" stream. But you have to set the StartInfo.RedirectStandardOutput property to "true" before.

    In your case:

        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();