简体   繁体   中英

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

I am using the following code to open the .exe and then I would like to pass another argument to it:

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);`

Which opens up the window as below. 在此处输入图片说明

Now I also need to pass "sd sync dirs" which gives me some result and would like to capture the result to a variable. 在此处输入图片说明

To accomplish this I need to pass two agruments in the ProcessStartInfo.Arguments. How can I add this second argument in the above code to take care of everything in C# code.

Since its just a string try this:

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

Where firstarg and secondarg are your arguments.

EDIT: Oops forgot to tell you ,if your argument contains spaces do this(the example contains 1 argument with spaces-first arg- and 1 without spaces-secondarg):

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

Here's an example of passing multiple arguments:

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

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

If you're passing strings you need to take account of the possibility of quotes being included in the subject line or body text. I enlisted some help on this issue with a StackOverflow question .

I ended up with something like this:

// 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 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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