2009-05-28 55 views
3

運行命令行命令我需要做2件事:運行一個批處理文件(工作正常),並運行一個命令(不起作用)。 該命令的方法會引發異常'未找到文件'。如果我打開一個cmd窗口,並輸入命令,它完美的工作。如何從代碼

private static void Rescan() 
    { 
     //System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("DEVCON ReScan"); 
     //psi.RedirectStandardOutput = true; 
     //psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
     //psi.UseShellExecute = false; 
     //System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); 
     System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
     proc.StartInfo.FileName = "DEVCON ReScan"; 
     proc.StartInfo.RedirectStandardError = true; 
     proc.StartInfo.RedirectStandardOutput = true; 
     proc.StartInfo.UseShellExecute = false; 
     proc.Start(); 
     proc.WaitForExit(); 
     System.IO.StreamReader myOutput = proc.StandardOutput; 
     proc.WaitForExit(4000); 
     if (proc.HasExited) 
     { 
      string output = myOutput.ReadToEnd(); 
      FileIO.WriteLog(_writePath, output); 
     } 

    } 

註釋的代碼也會引發相同的異常。

回答

9

DEVCON ReScan是否真的是可執行文件的名稱?我猜可執行文件是DEVCON,而ReScan是一個參數。這意味着您必須將StartInfo.FileName設置爲「DEVCON」,將StartInfo.Arguments設置爲「ReScan」。

+0

我只有1 upvote給。謝謝! – callisto 2009-05-28 08:42:38

+0

由於一些有趣的原因,這是System.Diagnostics.Process和本機ShellExecute(Ex)的常見錯誤,即使它顯然是一個「FileName」參數:) – OregonGhost 2009-05-28 08:45:01

0

DEVCON應用程序是否在工作目錄中? 否則,除非您指定完整路徑,否則它將不起作用。

而且你必須指定擴展,所以我想你會去「Devcon.exe的」, 並指定沒有參數的文件名,但在參數:)

0

試試這個:

 ProcessStartInfo psi = new ProcessStartInfo();    
     psi.FileName = Environment.GetEnvironmentVariable("comspec"); 
     psi.CreateNoWindow = true; 
     psi.RedirectStandardError = true; 
     psi.RedirectStandardInput = true; 
     psi.RedirectStandardOutput = true; 
     psi.UseShellExecute = false; 

     Process p = Process.Start(psi); 

     ConsoleColor fc = Console.ForegroundColor; 

     StreamWriter sw = p.StandardInput; 
     StreamReader sr = p.StandardOutput; 

     char[] buffer = new char[1024]; 
     int l = 0; 

     sw.Write("DEVCON ReScan"); 
     sw.Write(sw.NewLine); 

     Console.Write(">> "); 

     l = sr.Read(buffer, 0, buffer.Length); 

     for (int n = 0; n < l; n++) 
      Console.Write(buffer[n] + " "); 

     p.Close();