Run commandline from c# with parameters?

隐身守侯 提交于 2020-03-21 12:03:26

问题


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?


回答1:


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.




回答2:


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



回答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.



来源:https://stackoverflow.com/questions/5964123/run-commandline-from-c-sharp-with-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!