Process类调用exe,返回值以及参数空格问题

(方法一)返回值为int

fileName为调用的exe路径,入口参数为para,其中多个参数用空格分开,当D:/DD.exe返回值为int类型时。

 
  
Process p = new Process();  
  
string fileName = @"D:/DD.exe";  
  
string para ="aa bb";  
  
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(fileName, para);  
  
p.StartInfo = myProcessStartInfo;  
  
p.Start();  
  
while (!p.HasExited)  
  
{  
  
p.WaitForExit();  
  
}  
  
int returnValue = p.ExitCode;  

(方法二)返回值位string

返回值为string时,首先在生成DD.exe时主函数main返回值为void,但在主函数要用Write输出string,通过StandardOutput.ReadToEnd()获取输出流(即输出的字符串)

    string fileName = @"D:/DD.exe";  
      
    Process p = new Process();  
      
    p.StartInfo.UseShellExecute = false;  
      
    p.StartInfo.RedirectStandardOutput = true;  
      
    p.StartInfo.FileName = fileName;  
      
    p.StartInfo.CreateNoWindow = true;  
      
    p.StartInfo.Arguments = "aa bb cc";//参数以空格分隔
      
    p.Start();  
      
    p.WaitForExit();  
      
    string output = p.StandardOutput.ReadToEnd();  

PS:在输入参数 p.StartInfo.Arguments时,由于是以空格分隔,所以,当参数中含有字符串时,会强行分隔。比如我的入口参数需要以下四个参数:“D:\\Demo\\picWorldCup\\worldCup_cy.png”   “Canon MG3600 series Printer XPS” “330” “471”,如果我直接写成如下形式(即直接用空格连接起来)p.StartInfo.Arguments=“D:\\Demo\\picWorldCup\\worldCup_cy.png Canon MG3600 series Printer XPS 330 471显然是不可以的,此时应该通过转义字符\"把属于一个参数的内容包含起来即可,如

p.StartInfo.Arguments = "\"D:\\Demo\\picWorldCup\\worldCup_cy.png\" \"Canon MG3600 series Printer XPS\" 330 471";

猜你喜欢

转载自www.cnblogs.com/llstart-new0201/p/9101679.html
今日推荐