执行cmd然后卡住了,怎么办呀?谢谢了,大家帮忙看下.

「已注销」 2012-01-05 07:15:23
如果执行cmd或者command这些命令然后就会在p.StandardOutput.ReadToEnd();这里卡住...
现在我解决的方法就是


public static string executeCmd(string command)
{
string strRst = "0";
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.AutoFlush = true;
p.StandardInput.WriteLine("@echo off");
p.StandardInput.WriteLine(command);
p.StandardInput.WriteLine("exit");

System.Timers.Timer timer = new System.Timers.Timer(3000);
timer.Start();
timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
{

p.CloseMainWindow();
timer.Enabled = false;
timer.Close();
};

strRst = p.StandardOutput.ReadToEnd();
timer.Enabled = false;
timer.Close();
strRst = strRst.Substring(strRst.IndexOf(command) + command.Length);
strRst = strRst.Substring(0,strRst.Length - 8);
if (p.StandardError.ReadToEnd() != "")
{
strRst = p.StandardError.ReadToEnd();
}

p.WaitForExit();
p.Close();
return strRst;
}


这样加个时间,一旦3秒后强行结束,但是p.StartInfo.CreateNoWindow = true;就不管用了,
p.StartInfo.CreateNoWindow = false;就可以..
...全文
1003 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
「已注销」 2012-01-05
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 fangxinggood 的回复:]

1.用异步IO流读取(注意不是将ReadToEnd移到线程里,而是用 BeginRead() 和 RecievedData 事件)

2.用 Process.WaitForExit(3000) 等待3秒,如果返回 false , Process.Kill
[/Quote]


..................

谢谢了.
机器人 2012-01-05
  • 打赏
  • 举报
回复
1.用异步IO流读取(注意不是将ReadToEnd移到线程里,而是用 BeginRead() 和 RecievedData 事件)

2.用 Process.WaitForExit(3000) 等待3秒,如果返回 false , Process.Kill
「已注销」 2012-01-05
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 fangxinggood 的回复:]

正常啊,这属于同步的IO处理。ReadToEnd() 结束才会执行下一步。你可以用异步读取Cmd上的流的。
[/Quote]

但是,就算分到其他线程去了,他一直在那里阻塞着,这个线程也不会结束呀...

有什么办法强制结束 p.StandardOutput.ReadToEnd();这里呀?
机器人 2012-01-05
  • 打赏
  • 举报
回复
正常啊,这属于同步的IO处理。ReadToEnd() 结束才会执行下一步。你可以用异步读取Cmd上的流的。
「已注销」 2012-01-05
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 startstartsvip 的回复:]
这个有问题吧? 你读了两遍

if (p.StandardError.ReadToEnd() != "")
{
strRst = p.StandardError.ReadToEnd();
}
[/Quote]

不是呀...这里是.

第一次,读取output的字符...
然后,会判断一下,是否有error的,如果有就读取error的,没有的话还是output的...


嗯,现在主要问题是执行cmd或者command这些cmd命令的话会卡住....
startstartsvip 2012-01-05
  • 打赏
  • 举报
回复

这个有问题吧? 你读了两遍

if (p.StandardError.ReadToEnd() != "")
{
strRst = p.StandardError.ReadToEnd();
}

110,537

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧