C#中命令行工具的包装器

Viv*_*obo 5 c# command-line wrapper visual-studio-2010 argument-passing

使用MSDN我得到了类为我的命令行工具编写包装器.

我现在面临一个问题,如果我通过带有参数的命令行执行exe,它可以完美运行而不会出现任何错误.

但是当我尝试从Wrapper传递参数时,它会崩溃程序.

我想知道我是否正确地通过了论证,如果我错了,请有人指出.这是来自MSDN的LaunchEXE类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace SPDB
{
    /// <summary>
    /// Class to run any external command line tool with arguments
    /// </summary>
    public class LaunchEXE
    {
        internal static string Run(string exeName, string argsLine, int timeoutSeconds)
        {
            StreamReader outputStream = StreamReader.Null;
            string output = "";
            bool success = false;

            try
            {
                Process newProcess = new Process();
                newProcess.StartInfo.FileName = exeName;
                newProcess.StartInfo.Arguments = argsLine;
                newProcess.StartInfo.UseShellExecute = false;
                newProcess.StartInfo.CreateNoWindow = true; //The command line is supressed to keep the process in the background
                newProcess.StartInfo.RedirectStandardOutput = true;
                newProcess.Start();
                if (0 == timeoutSeconds)
                {
                    outputStream = newProcess.StandardOutput;
                    output = outputStream.ReadToEnd();
                    newProcess.WaitForExit();
                }
                else
                {
                    success = newProcess.WaitForExit(timeoutSeconds * 1000);

                    if (success)
                    {
                        outputStream = newProcess.StandardOutput;
                        output = outputStream.ReadToEnd();
                    }
                    else
                    {
                        output = "Timed out at " + timeoutSeconds + " seconds waiting for " + exeName + " to exit.";
                    }
                }
            }
            catch (Exception e)
            {
                throw (new Exception("An error occurred running " + exeName + ".", e));
            }
            finally
            {
                outputStream.Close();
            }

            return "\t" + output;           

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我从主程序传递参数的方式(Form1.cs)

private void button1_Click(object sender, EventArgs e)
        {
            string output;
            output = LaunchEXE.Run(@"C:\Program Files (x86)\MyFolder\MyConsole.exe", "/BACKUP C:\\MyBackupProfile.txt", 100);
            System.Windows.Forms.MessageBox.Show(output);
        }
Run Code Online (Sandbox Code Playgroud)

命令行工具接受以下命令并完美地工作:

C:\ Program Files(x86)\ MyFolder> MyConsole.exe/BACKUP C:\ MyBackupProfile.txt

Mat*_*ans 0

我有一种感觉,它不喜欢你路径中的空格。请参阅这篇文章:C# 如何在 process.arguements 中使用目录空白?