Run command line from C # with options?

You can run the command line in C # using something like this:

process = new Process(); process.StartInfo.FileName = command; process.Start(); 

The problem is that the command line contains options, for example:

 C:\My Dir\MyFile.exe MyParam1 MyParam2 

This will not work, and I don’t see how to extract the parameters from this line and set it in the process.Arguments property? The path and file name may be something else, the file should not end in exe .

How can i solve this?

+6
source share
3 answers

If I understand correctly, I would use:

 string command = @"C:\My Dir\MyFile.exe"; string args = "MyParam1 MyParam2"; Process process = new Process(); process.StartInfo.FileName = command; process.StartInfo.Arguments = args; process.Start(); 

If you have a complete line to parse, I would use other methods suggested by others. If you want to add parameters to the process, use the above.

+5
source

This may be the worst solution, but it may be safer:

 string cmd = "C:\\My Dir\\MyFile.exe MyParam1 MyParam2"; System.IO.FileInfo fi = null; StringBuilder file = new StringBuilder(); // look up until you find an existing file foreach ( char c in cmd ) { file.Append( c ); fi = new System.IO.FileInfo( file.ToString() ); if ( fi.Exists ) break; } cmd = cmd.Remove( 0, file.Length ); System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo( fi.Name, cmd ); System.Diagnostics.Process.Start( psi ); 
+3
source

Statement: if the file name contains a space, it must be enclosed in double quotes.

This certainly takes place on Windows. Otherwise, the rules become much more contextual.

Take a look at regex-matching-spaces-but-not-in-strings , I suspect you can use a regex,

 " +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)" 

using Regex.Split() to convert the command line to an array. The first part should be your name.

+2
source

Source: https://habr.com/ru/post/887824/


All Articles