【发布时间】:2017-04-13 15:26:10
【问题描述】:
由于旧的question 扩展了很多,没有有效的答案(但有用),我想对其进行改造。事实是在 cmd 中一切都运行良好,但不是 c#。如果共享资源存在,则 c# 中 net use 的输出是正确的:“命令已完成”(在我的情况下是西班牙语)。 但是当共享资源不存在时, 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");
}
}
【问题讨论】:
-
output包含什么内容? -
我执行的命令的输出,如果 net use 是成功的:'命令完成',如果不是它应该是 false 但从不打印假 :(
-
您在尝试从标准输出读取之前关闭进程。您应该使用
using语句。如果您将异常处理程序更改为打印e.Message,您就会看到这一点。这是一个很好的例子,说明了为什么包罗万象的异常处理会成为一个问题。