C#调用DOS命令

平时都是在CMD中直接执行"dir",使用C#时竟不确定应该调用哪个exe了,其实"dir"可看作"cmd.exe /C dir"的简写方式,这样就该知道怎样在C#中调用了,写下来,备忘吧。

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = CommandLine("cmd.exe", "", "/C dir");//调用dir命令
        }

        #region 调用命令行工具

        /// <summary>
        /// 调用命令行工具
        /// </summary>
        /// <param name="name">命令行工具名称</param>
        /// <param name="workingDirectory">设置工作目录</param>
        /// <param name="args">可选命令行参数</param>
        /// <remarks>注意:所有命令行工具都必须保存于system32文件夹中</remarks>
        /// <returns></returns>
        private string CommandLine(string name, string workingDirectory, params string[] args)
        {
            string returnValue = "";

            using (Process commandline = new Process())
            {
                try
                {
                    commandline.StartInfo.UseShellExecute = false;
                    commandline.StartInfo.CreateNoWindow = true;
                    commandline.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    commandline.StartInfo.RedirectStandardOutput = true;
                    commandline.StartInfo.FileName = name;
                    commandline.StartInfo.WorkingDirectory = workingDirectory;
                    //添加命令行参数
                    if (args.Length > 0) commandline.StartInfo.Arguments = string.Join(" ", args);
                    commandline.Start();
                    commandline.WaitForExit();
                    returnValue = commandline.StandardOutput.ReadToEnd();
                    commandline.Close();
                }
                catch
                {
                    commandline.Dispose();
                    throw;
                }
            }

            return returnValue;
        }

        #endregion
    }
}


评论: 0 | 引用: 0 | 查看次数: 5858
发表评论
登录后再发表评论!