Search code examples
c#fileprocessstreamreader

How to use C# Stream Reader to save a completion of a process?


I have a program which uses a CMD program to execute various arguements.

The arguements that would work in a normal CMD would be C:\temp\bin\fls.exe -m C: -r C:\temp\image.dd > C:\temp\bin\ntfs.bodyfile .

The C# program that I have written only works till C:\temp\bin\fls.exe -m C: -r C:\temp\image.dd but does not execute the > C:\temp\bin\ntfs.bodyfile which means save the process into the ntfs.bodyfile.

I have read many other websites and they all point to the problem of my program missing a streamreader to save the completion of the process into a file. So can someone please advise on my program to allow the process to be saved into a file? Thanks!

One such similar website that has a same problem would be: StreamReader to file?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Diagnostics;

namespace ConsoleApplication1
{
class Program
{
   static void Main(string[] args)
   {
       Process process = new Process();
       process.StartInfo.FileName = "C:\\temp\\bin\\fls.exe";
       process.StartInfo.Arguments = "-m C: -r C:\\temp\\image.dd > 
       C:\\temp\\bin\\ntfs.bodyfile";
       process.StartInfo.UseShellExecute = false;
       process.StartInfo.RedirectStandardOutput = true;
       process.StartInfo.RedirectStandardInput = true;
       process.StartInfo.RedirectStandardError = true;
       process.Start();

       System.IO.StreamReader reader = process.StandardOutput;
       string sRes = reader.ReadToEnd();
       Console.WriteLine(sRes);
       reader.Close();  
   }   
 }
}

Solution

  • Your answers are all very varied but I finally found the answer to the question.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.Win32;
    using System.Diagnostics;
    using System.IO;
    
    namespace ConsoleApplication1
    {
     class Program
     {
       static void Main(string[] args)
       {
           Process process = new Process();
           process.StartInfo.FileName = "C:\\temp\\bin\\fls.exe";
           process.StartInfo.Arguments = "-m C: -r C:\\temp\\image.dd";
           process.StartInfo.UseShellExecute = false;
           process.StartInfo.RedirectStandardOutput = true;
           process.StartInfo.RedirectStandardInput = true;
           process.StartInfo.RedirectStandardError = true;
           process.Start();
    
           System.IO.StreamReader reader = process.StandardOutput;
           string sRes = reader.ReadToEnd();
           StreamWriter SW;
           SW = File.CreateText("C:\\temp\\ntfs.bodyfile");
           SW.WriteLine(sRes);
           SW.Close();
           Console.WriteLine("File Created SucacessFully");
           reader.Close();  
       }   
      }
    }