Process class not printing echo output c#

孤者浪人 提交于 2019-12-12 01:57:15

问题


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

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



来源:https://stackoverflow.com/questions/40869169/process-class-not-printing-echo-output-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!