2009-05-28 1 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本当に実行可能ファイルの名前ですか? ReScanはパラメータですが、実行可能ファイルはDEVCONだと思います。つまり、StartInfo.FileNameを「DEVCON」に、StartInfo.Argumentsを「ReScan」に設定する必要があります。

+0

私には1アップヴォートがあります。ありがとう! – callisto

+0

面白い理由から、明らかに "FileName"パラメータであっても、それはSystem.Diagnostics.ProcessとネイティブShellExecute(Ex)のよくある間違いです。 – OregonGhost

+0

Filenameにファイル名(devcon.exe)を設定し、 ReScan引数を渡すにはproc.StartInfo.Argumentsを使用します。何が何であるかを明白に保つだけです。 –

0

DEVCONアプリケーションは実際に作業ディレクトリにありますか? それ以外の場合は、フルパスを指定しない限り動作しません。

さらに、あなたは拡張子を指定する必要があり、私はあなたが「Devcon.exe」のために行くだろうと仮定し、 およびファイル名にパラメータを指定していないが、パラメータ:)

+0

DevconはPATH環境ディレクトリにあります。 働いています: proc.StartInfo.FileName = "DEVCON"; proc.StartInfo.Arguments = "ReScan"; – callisto

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(); 
関連する問題