0

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)
{

    try
    {

        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;
        proc.Start();
        proc.WaitForExit(2000);
        proc.Close();

        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");
    }
}
Community
  • 1
  • 1
tec
  • 999
  • 3
  • 18
  • 40
  • What does `output` contain? – 001 Nov 29 '16 at 15:12
  • the output of the command I execute, if **net use** is successfull: 'Command completed', if not it should be **false** but never prints **false** :( – tec Nov 29 '16 at 15:14
  • You are closing the process before trying to read from stdout. You should use `using` statements. If you change your exception handler to print `e.Message` you would have seen that. That's a good example of why catch-all exception handling can be a problem. – 001 Nov 29 '16 at 15:18

1 Answers1

1

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"))

Pikoh
  • 7,582
  • 28
  • 53