2016-11-29 17 views
0

古いquestionがかなり拡張されているため、実際の回答はありませんが便利ですが、私はそれを改造したいと思います。事実はcmdですべてうまくいきますが、それはC#ではありません。共有リソースが存在する場合、C#でのnet useの出力は正しいです: 'Command completed'(私の場合はスペイン語)。 しかし、共有リソースが存在しない場合、echo 'false'はcmdでは動作しますが、c#では動作しません。したがって、何が起こったのか(ユーザー特権またはリソースが見つかりません) C#で私は試しました:プロセスクラスはエコー出力を出力しません。C#

String cmd = "....else (echo "+false+")"; 
String cmd = "....else (echo false)"; 
String cmd = "....else (echo 'false')"; 

誰も動作しません。 方法は、(古い質問から変更):

void mapDrive(String driveChar, string server, string user, string password) 
{ 

    try 
    { 

     String output; 

     String cmd = "if exist " + server + " (net use " + driveChar + ": " + server + " /user:" + user + " " + password + ") else (echo false)"; 
     ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", "/c" + cmd); 
     processStartInfo.RedirectStandardOutput = true; 
     processStartInfo.RedirectStandardError = true; 
     processStartInfo.UseShellExecute = false; 
     processStartInfo.CreateNoWindow = true; 

     Process proc = new Process(); 
     proc.StartInfo = processStartInfo; 
     proc.Start(); 
     proc.WaitForExit(2000); 
     proc.Close(); 

     StreamReader streamReader = proc.StandardOutput; 
     output = streamReader.ReadToEnd(); 
     Debug.WriteLine("CMD OUTPUT: " + output); 

     if (output.Equals("false")) 
     { 
      MessageBox.Show("Error: couldn't found requested resource"); 
     } 

    } 
    catch (Exception e) 
    { 
     MessageBox.Show("Error: you have no privileges"); 
    } 
} 
+0

「出力」には何が含まれていますか? –

+0

** net use **が成功した場合、コマンドの出力が実行されます。 'Command completed'、そうでなければ** false **ですが、決して印刷されません** false ** :( – tomyforever

+0

あなたはプロセスを終了しています例外ハンドラを 'e.Message'を表示するように変更すると、それが見えます。これはcatch-all例外処理が問題になる理由の良い例です。 –

答えて

1

あなたは、あなたのコード内の二つの問題を持っています。まず、出力を読み込む前にプロセスを閉じているので、proc.Close()をメソッドの最後に移動する必要があります。もう1つの問題は、出力に改行が含まれているため、変更することですif (output.Equals("false"))if (output.Contains("false"))

+0

Omg、最終的にThx。 – tomyforever

+0

De nada @tomyforever :) – Pikoh

関連する問題