2017-08-28 448 views
0

我期待在c#應用程序中自動創建nupkg。我打算在我的項目中包含nuget.exe,並使用System.Diagnostics作爲進程啓動cmd.exe,然後傳遞所需的命令,這將是'cd project \ path \ here','nuget spec something.dll '和'nuget pack something.nuspec'。如何從C#控制檯運行多個CMD命令應用程序

我到目前爲止的代碼是:

 Process p = new Process(); 
     ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\System32\cmd.exe", @"mkdir testdir"); 

     p.StartInfo = info; 
     p.Start(); 

     Console.ReadLine(); 

然而,它甚至不創造TESTDIR,和我沒有想法鏈如何將這些命令。在我的Process上有一個名爲WaitForInputIdle的方法,但它引發了事件,我不知道如何處理這些事實。

一個完美的解決方案還可以讓我讀取輸出和輸入。我已經嘗試過使用StreamWriter p.StandardInput,但是接下來會出現檢查命令是否已完成以及結果如何的問題。

任何幫助將不勝感激。

編輯:成功!我已經成功地創建一個目錄:) 這裏是我的代碼現在:

Process p = new Process(); 
    ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\System32\cmd.exe"); 
    info.RedirectStandardInput = true; 
    info.UseShellExecute = false; 

     p.StartInfo = info; 
     p.Start(); 

     using (StreamWriter sw = p.StandardInput) 
     { 
      sw.WriteLine("mkdir lulz"); 
     } 

仍然不知道如何等待輸入和跟進更多的命令,雖然。

+0

'Directory.CreateDirectory'或創建bat-file並運行它。 – Sinatr

+0

Sinatr我不打算創建一個目錄,那只是想讓cmd工作。 – Nech

+0

既然你可以回答你自己的問題,如果你沒有發佈你的解決方案作爲編輯,但作爲答案,它會很好。 –

回答

0

您可以通過三種方式

1最簡單的方法是將兩個命令與「&」符號結合起來做。

var processInfo = new ProcessStartInfo("cmd.exe", @"command1 & command2"); 

2-通過ProcessStartInfo設置進程的工作目錄。

var processInfo = new ProcessStartInfo("cmd.exe", @"your commands here "); 
processInfo.UseShellExecute = false; 
processInfo.WorkingDirectory = path; 

3-重定向過程的輸入和輸出。 (另外通過的ProcessStartInfo完成)當您想更多的輸入發送給該進程。這是必需的,或當你想獲得過程

的輸出也看到this answer

相關問題