extra2
extra2

Reputation: 43

C# Read text (output?) from console that runs as a Process

I'm trying to check if username and password for git repository is valid. In console I run:

git clone http://username:password@server/test.git

And I get:

fatal: Authentication failed for ...

So now I know username and password are not valid. I'm trying to run this command as a process:

var process = new Process
{
     StartInfo = new ProcessStartInfo
     {
          FileName = "git.exe",
          RedirectStandardInput = true,
          RedirectStandardOutput = true,
          RedirectStandardError = true,
          UseShellExecute = false,
          WorkingDirectory = "some_directory"
          CreateNoWindow = true,
           Arguments = "git clone http://username:password@server/test.git"
      },
};
process.Start();

I'd like to access the result of this command. Both process.StandardError and process.StandardOutput are equals string.Empty. Is there any way to read the result?

Upvotes: 1

Views: 729

Answers (2)

isydmr
isydmr

Reputation: 657

What you really need is your standard output, which can be accessed as below:

string stdout = p.StandardOutput.ReadToEnd(); 

and use p.WaitForExit(); right after because sometimes it takes a while to give error message.

Upvotes: 1

Stefan
Stefan

Reputation: 17648

Normally you should read the exit code of the process.

process.ExitCode

If the process failed, the return value should be non 0. Of course you can only retrieve the exit code after the process completes.

So:

if (process.ExitCode != 0)
    //error

Please note: I haven't tested it but it is standard convention.

To read the output, one normally uses:

string output = process.StandardOutput.ReadToEnd();
string err = process.StandardError.ReadToEnd();
Console.WriteLine(output);
Console.WriteLine(err);

Upvotes: 1

Related Questions