繁体   English   中英

如何使用带有多个参数的C#运行cmd.exe?

[英]How to run cmd.exe using c# with multiple arguments?

我正在使用以下代码打开.exe,然后将另一个参数传递给它:

ProcessStartInfo StartInfo = new ProcessStartInfo();
StartInfo.FileName = "cmd.exe";
StartInfo.Arguments = @"/k set inetroot=c:\depot&set corextbranch=surfacert_v2_blue_kit&c:\depot\tools\path1st\myenv.cmd";
Process.Start(StartInfo);`

随即打开如下窗口。 在此处输入图片说明

现在,我还需要传递“ sd sync dirs”,这会给我一些结果,并希望将结果捕获到变量中。 在此处输入图片说明

为此,我需要在ProcessStartInfo.Arguments中传递两个小数。 如何在上面的代码中添加第二个参数来处理C#代码中的所有内容。

由于它只是一个字符串,请尝试以下操作:

string[] MyArguments = { "firstarg", "secondarg"};
Process.Start("cmd.exe", String.Join(" ", MyArguments));

其中firstarg和secondarg是您的参数。

编辑:糟糕,忘了告诉您,如果您的参数包含空格,请执行此操作(本示例包含1个参数,其中空格为firstarg-,1为空格-secondarg):

string[] MyArguments = { "\"first arg\"", "secondarg" };

这是传递多个参数的示例:

http://msdn.microsoft.com/en-us/library/bfbyhds5.aspx

http://msdn.microsoft.com/en-us/library/53ezey2s.aspx

如果要传递字符串,则需要考虑在主题行或正文中包含引号的可能性。 我通过StackOverflow 问题寻求了一些帮助。

我最终得到了这样的东西:

// DOS command line
C:\>ConsoleApplication1 "Subject Line Text" "Some body text"

// Web form code-behind
// Pass subject and message strings as params to console app    
ProcessStartInfo info = new ProcessStartInfo();

string arguments = String.Format(@"""{0}"" ""{1}""",
     subjectText.Text.Replace(@"""", @""""""),
     messageText.Text.Replace(@"""", @""""""));
     info.FileName = MAILER_FILEPATH;

Process process = Process.Start(info.FileName, arguments);
Process.Start(info);

// Console application
static void Main(string[] args)
{
    if (args.Length >= 2)
    {
        // Do stuff 
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM