C# 4.0 System.Diagnostics.ProcessStartInfo和net.exe没有输出
我在我的应用程序中执行以下操作:C# 4.0 System.Diagnostics.ProcessStartInfo和net.exe没有输出,c#-4.0,C# 4.0,我在我的应用程序中执行以下操作: if (!new DriveInfo(elt.driveletter).IsReady) { var messages = new List<string>(); var p = new System.Diagnostics.Process() { StartInfo = new System.Diagnostics.ProcessStartInfo("net.exe", String.Format(
if (!new DriveInfo(elt.driveletter).IsReady)
{
var messages = new List<string>();
var p = new System.Diagnostics.Process()
{
StartInfo = new System.Diagnostics.ProcessStartInfo("net.exe", String.Format(
"use {0}: {1}"
, elt.driveletter
, elt.parameters
))
{
RedirectStandardOutput = true
, RedirectStandardError = true
, UseShellExecute = false
}
};
p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler((o, arg) =>
{
messages.Add(arg.Data);
});
p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler((o, arg) =>
{
messages.Add(arg.Data);
});
p.Start();
p.WaitForExit();
if (!new DriveInfo(elt.driveletter).IsReady)
{
throw new Exception(String.Format(
"Cannot map drive {0} - {1}"
, elt.driveletter
, String.Join("-", messages.ToArray())
));
}
}
if(!new DriveInfo(elt.driveletter).IsReady)
{
var messages=新列表();
var p=新系统.Diagnostics.Process()
{
StartInfo=new System.Diagnostics.ProcessStartInfo(“net.exe”,String.Format(
“使用{0}:{1}”
,elt.drivelett
,elt.parameters
))
{
重定向标准输出=真
,RedirectStandardError=true
,UseShellExecute=false
}
};
p、 OutputDataReceived+=new System.Diagnostics.DataReceivedEventHandler((o,arg)=>
{
messages.Add(参数数据);
});
p、 ErrorDataReceived+=new System.Diagnostics.DataReceivedEventHandler((o,arg)=>
{
messages.Add(参数数据);
});
p、 Start();
p、 WaitForExit();
如果(!new DriveInfo(elt.driveletter).IsReady)
{
抛出新异常(String.Format)(
“无法映射驱动器{0}-{1}”
,elt.drivelett
,String.Join(“-”,messages.ToArray())
));
}
}
抛出异常,但在“无法映射驱动器{0}-”之后文本始终为空,为什么
消息
不包含任何内容?不确定这是否是输入错误,但您的第一个if
语句应该检查IsReady
,并在未准备就绪时抛出异常/错误
if (new DriveInfo(elt.driveletter).IsReady)
//work the process
else
//throw exception
由于进程本身未启动的原因,消息
变量为空,因此未获取任何数据。要进行检查,请尝试打印所调用进程的StandardOutput
,如
p.Start();
Console.WriteLine(p.StandardOutput.ReadToEnd());
p.WaitForExit();
您只是忘记调用所需的BeginOutput/ErrorReadLine()方法。因此,永远不会调用事件处理程序。也不要跳过检查Process.ExitCode,以便验证严重错误。修正:
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
int err = p.ExitCode;
if (err != 0) throw new Exception("NET.EXE failed with exit code {0}", err);
相反,最好以这种方式减少事故。如果手动运行该命令会发生什么情况?系统错误85已发生。本地设备名已在使用中。文档说明,当UseShellExecute为false时,需要完整路径名。您尝试过net.exe的完整路径吗?您只是忘记调用所需的BeginOutput/ErrorReadLine()方法。因此,永远不会调用事件处理程序。也不要跳过检查Process.ExitCode,以便验证严重错误。最好是这样。不,我只需要在驱动器不可用的情况下创建映射。这意味着进程本身可能不会启动。如果进程在p.Start()之后和调用p.BeginOutputReadLine()之前结束,该怎么办?输出不会去任何地方,耐心地坐在管道缓冲区中,直到您读取它。