10

It's possible to run commandline in c# by using something like this :

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

The problem is if the command string contains parameters, 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 string and set it on the process.Arguments property? The path and filename could be something else, the file does not have to end with exe.

How can I solve this?

Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
Banshee
  • 15,376
  • 38
  • 128
  • 219
  • So, the question is, how can I split a command line into a `FileName` and `Arguments`. – Jodrell May 11 '11 at 12:27
  • Sounds like you want a regular expression to find the break point. Strictly speaking, if the filename contains a space, is should be in double quotes. That would help u a lot. Is this the case, in your example is the filename `C:\\My` or `C:\\My Dir\MyFile.exe`? Incidentally, is that `M` escaped? – Jodrell May 11 '11 at 12:31
  • Do the file ends with a dot and any extension? e.g. .com, .exe... – ibram May 11 '11 at 12:46

3 Answers3

7

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 string that you need to parse I would use the other methods put forward by the others here. If you want to add parameters to the process, use the above.

anothershrubery
  • 20,461
  • 14
  • 53
  • 98
5

This could be the worst solution, but it could a safer one:

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 );
ibram
  • 4,414
  • 2
  • 22
  • 34
  • thats quite a good idea, it uses the context of the environmnet to infer the correctness of the string. +1 for lateral thinking. Also works if there really are no quotes. – Jodrell May 11 '11 at 17:05
3

Assertion: If a filename contains a space, it must be wrapped in double quotes.

This is certainly the case in Windows. Otherwise the rules become much more contextual.

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

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

using Regex.Split() to convert you command line into an array. The first part should be your filename.

Community
  • 1
  • 1
Jodrell
  • 34,946
  • 5
  • 87
  • 124