Skip to content

Note

不挑戰記憶力的技術筆記

Menu
Menu

[C#] 使用 Process Class 執行其他命令列或程式

Posted on 2016 年 9 月 5 日 by febr
using System.Diagnostics;

Process p = new Process();

p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true; //設定輸出結果導向
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true; //不顯示視窗

string cmdInput = "dir";
string cmdOutput = null;
string cmdErr = null;

p.Start();  //開始執行
p.StandardInput.WriteLine(cmdInput);
p.StandardInput.WriteLine("exit");
cmdOutput = p.StandardOutput.ReadToEnd();  //將整個執行過程轉為字串
cmdErr = p.StandardError.ReadToEnd();  //將執行錯誤的訊息轉為字串
p.WaitForExit();
p.Close();

 

若執行大量資料時,要注意 WaitForExit() 一定要寫在 StandardOutput 之後,

// To avoid deadlocks, always read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit(); 

參考文件:https://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx

發佈留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

近期文章

  • [AWS] S3 Object Initiate restore (復原回 Standard)
  • [Windows] 使用者快速登出的方法 Logout/ Logoff/Sign Out from Windows User Account
  • [Windows] Windows 11 安裝Server管理工具Install RSAT(Remote Server Administrator Tools)
  • Chrome出現:你的連線不是私人連線 Your connection is not private
  • [C#] 取得 Request URL 的方法

近期留言

    彙整

    分類

    • Ajax
    • Android
    • ASP
    • ASP.NET MVC
    • Azure
    • C#
    • Cisco
    • CSS
    • Delphi
    • Developer Tools
    • Framework
    • FreeBSD
    • Git
    • HTML5
    • javascript
    • jQuery
    • Juniper
    • Linux
    • Mac
    • PHP
    • Python
    • Server&OS
    • Software
    • SQL server
    • Sublime Text
    • Ubuntu
    • Visual Studio
    • Vmware
    • Web Design
    • Web Development
    • Windows
    • WordPress
    • 未分類
    • 未分類

    彙整

    分類

    • Ajax
    • Android
    • ASP
    • ASP.NET MVC
    • Azure
    • C#
    • Cisco
    • CSS
    • Delphi
    • Developer Tools
    • Framework
    • FreeBSD
    • Git
    • HTML5
    • javascript
    • jQuery
    • Juniper
    • Linux
    • Mac
    • PHP
    • Python
    • Server&OS
    • Software
    • SQL server
    • Sublime Text
    • Ubuntu
    • Visual Studio
    • Vmware
    • Web Design
    • Web Development
    • Windows
    • WordPress
    • 未分類
    • 未分類

    其他操作

    • 登入
    • 訂閱網站內容的資訊提供
    • 訂閱留言的資訊提供
    • WordPress.org 台灣繁體中文
    © 2025 Note | Powered by Superbs Personal Blog theme