进程 class 不打印 echo 输出 c#

Process class not printing echo output c#

由于旧的扩展了很多,没有有效的答案(但有用),我想改造它。事实上,在 cmd 中一切都运行良好,但在 c# 中则不然。如果共享资源存在,则 net use 在 c# 中的输出是正确的:'Command completed'(在我的例子中,是西班牙语)。 但是当共享资源不存在时,echo 'false' 在 cmd 中工作,但在 c# 中不工作,所以我无法区分发生的方法(用户权限或资源未找到)。在 c# 中我试过:

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

没有人工作。 方法(从旧问题修改而来):

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

你的代码有两个问题。首先,您要在读取输出之前关闭进程,因此您应该将 proc.Close() 移到方法的末尾。另一个问题是输出将包含换行符,因此将 if (output.Equals("false")) 更改为 if (output.Contains("false"))