百度空间 | 百度首页 
 
查看文章
 
在.net中悄悄执行dos命令,并获取执行的结果
2007年02月04日 01:23

本文阐述了如何在.net中悄悄的执行dos命令,并通过重定向输出来返回结果的方式。

一、怎样使dos命令悄悄执行,而不弹出控制台窗口?

1.需要执行带“/C”参数的“cmd.exe”命令,它表示执行完命令后立即退出控制台。
2.设置startInfo.UseShellExecute = false;     //不使用系统外壳程序启动进程
3.设置startInfo.CreateNoWindow = true;     //不创建窗口

二、怎样得到dos命令的执行结果?

1.设置startInfo.RedirectStandardOutput = true;   //重定向输出,而不是默认的显示在dos控制台
2.使用process.StandardOutput来读取结果。

三、源程序

我将这一系列操作都封装到了类DosCommandOutput的方法Execute中,请看下面:

using System;
using System.Text;
using System.Diagnostics;

namespace Wuya.GetDosCommandOutput
{
/// <summary>
/// DOS命令输出类
/// </summary>
class DosCommandOutput
{
  /// <summary>
  /// 执行DOS命令,返回DOS命令的输出
  /// </summary>
  /// <param name="dosCommand">dos命令</param>
  /// <returns>返回输出,如果发生异常,返回空字符串</returns>
  public static string Execute(string dosCommand)
  {
   return Execute(dosCommand, 60 * 1000);
  }
  /// <summary>
  /// 执行DOS命令,返回DOS命令的输出
  /// </summary>
  /// <param name="dosCommand">dos命令</param>
  /// <param name="milliseconds">等待命令执行的时间(单位:毫秒),如果设定为0,则无限等待</param>
  /// <returns>返回输出,如果发生异常,返回空字符串</returns>
  public static string Execute(string dosCommand, int milliseconds)
  {
   string output = "";     //输出字符串
   if (dosCommand != null && dosCommand != "")
   {
    Process process = new Process();     //创建进程对象
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.FileName = "cmd.exe";      //设定需要执行的命令
    startInfo.Arguments = "/C " + dosCommand;   //设定参数,其中的“/C”表示执行完命令后马上退出
    startInfo.UseShellExecute = false;     //不使用系统外壳程序启动
    startInfo.RedirectStandardInput = false;   //不重定向输入
    startInfo.RedirectStandardOutput = true;   //重定向输出
    startInfo.CreateNoWindow = true;     //不创建窗口
    process.StartInfo = startInfo;
    try
    {
     if (process.Start())       //开始进程
     {
      if (milliseconds == 0)
       process.WaitForExit();     //这里无限等待进程结束
      else
       process.WaitForExit(milliseconds);  //这里等待进程结束,等待时间为指定的毫秒
      output = process.StandardOutput.ReadToEnd();//读取进程的输出
     }
    }
    catch
    {
    }
    finally
    {
     if (process != null)
      process.Close();
    }
   }
   return output;
  }
}
}

四、使用示例

txtResult.Text=DosCommandOutput.Execute(txtCommand.Text);


类别:c#/.net | 添加到搜藏 | 浏览() | 评论 (5)
 
最近读者:
 
网友评论:
1
2007年02月09日 15:40 | 回复
我现在急需这个...要在asp.net里面用
 
2
2007年02月09日 15:43 | 回复
ml = "ffmpeg.exe -i "&UPath&"UpVideo\"&FileName&".flv -ss 1 -vframes 1 -r 1 -ac 1 -ab 2 -s 120*90 -f image2 "&UPath&"Videoimages\"&FileName&"_1.jpg" cmd = "C:\WINDOWS\System32\cmd.exe /c "&ml&"" 这是asp里面的代码.我要在asp.net里面实现这个功能 请问你有什么办法可以帮帮我吗? 如果你有办法请发我邮箱吧:haitianlei@163.com
 
3
2007年02月11日 04:17 | 回复
你可以加我QQ. 7966778 我不喜欢发邮件
 
4
2008年03月17日 08:54 | 回复
startInfo.RedirectStandardError = True; //重定向错误... --------- throw new Exception(process.StandardError.ReadToEnd()); //抛出错误...
 
5
2008年06月24日 17:36 | 回复
为啥我用VB.NET写的同样的代码,语句硬是没执行,还返回个奇怪的 "M 太奇怪了太奇怪了
 
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu