进程类未打印回显输出C# [英] Process class not printing echo output c#

查看:92
本文介绍了进程类未打印回显输出C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于旧的问题扩展了很多,没有有效的答案(但很有用),我想对其进行改造.事实是,在cmd中一切正常,但在C#中却不是.如果存在共享资源,则c#中的net use输出正确:命令已完成"(在我的情况下为西班牙语). 但是,当共享资源不存在时,echo'false'在cmd中起作用,但在c#中不起作用,因此我无法区分所发生的方法(找不到用户特权或资源).在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)
{

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

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

这篇关于进程类未打印回显输出C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆