tomyforever tomyforever - 1 year ago 71
C# Question

Process class not printing echo output c#

Due to the old question extended a lot, without working answers (but usefull), I would like to remodel it. The fact is in cmd all is working well, but not it c#. If the shared resource exist, the output of net use in c# is correct: 'Command completed' (in my case, in Spanish).
But when the shared resource doesn't exist the echo 'false' works in cmd, but don't in c#, so I can't difference in the method what happened (user privilege or resource not found). In c# I tried:

String cmd = "....else (echo "+false+")";
String cmd = "....else (echo false)";
String cmd = "....else (echo 'false')";

No one works.
The method (modified from the old question):

void mapDrive(String driveChar, string server, string user, string password)


String output;

String cmd = "if exist " + server + " (net use " + driveChar + ": " + server + " /user:" + user + " " + password + " ) else (echo false)";
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", "/c" + cmd);
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.UseShellExecute = false;
processStartInfo.CreateNoWindow = true;

Process proc = new Process();
proc.StartInfo = processStartInfo;

StreamReader streamReader = proc.StandardOutput;
output = streamReader.ReadToEnd();
Debug.WriteLine("CMD OUTPUT: " + output);

if (output.Equals("false"))
MessageBox.Show("Error: couldn't found requested resource");

catch (Exception e)
MessageBox.Show("Error: you have no privileges");

Answer Source

You've got two problems in your code. First of all, you are closing the process before reading the output, so you should move your proc.Close() to the end of the method. The other problem is the output would contain a Newline, so change if (output.Equals("false")) to if (output.Contains("false"))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download