C#用Process類調(diào)用cmd執(zhí)行及命令行首字母亂碼問題

直接上代碼

//=====================================================
// - FileName:      ProcessTask 
// - Description:
// - Author:        wangguoqing
// - Email:         wangguoqing@hehemj.com
// - Created:       2017/12/13 17:12:17
// - CLR version:   4.0.30319.42000
// - UserName:      Wang
// -  (C) Copyright 2008 - 2015, hehehuyu,Inc.
// -  All Rights Reserved.
//======================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using UnityEngine;
using Debug = UnityEngine.Debug;
 
    class ProcessTask
    {




        public static bool RunProcess(string filePath,string args="")
        {
            bool isSuncc = true;
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = filePath;
            //start.Arguments = args+"&exit";
            start.UseShellExecute = false;//是否使用操作系統(tǒng)shell啟動(dòng)
            start.RedirectStandardOutput = true;//由調(diào)用程序獲取輸出信息
            start.RedirectStandardError = true;//重定向標(biāo)準(zhǔn)錯(cuò)誤輸出
            start.RedirectStandardInput = true;//接受來自調(diào)用程序的輸入信息
            //start.CreateNoWindow = true;/不顯示程序窗口
            //start.WorkingDirectory = "";
            using (Process process = Process.Start(start))
            {
                process.StandardInput.WriteLine(args);
                process.StandardInput.WriteLine("exit");
                process.EnableRaisingEvents = true;
                process.BeginOutputReadLine();

                process.OutputDataReceived += (s, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data)) Console.WriteLine(e.Data);
                };
                using (StreamReader reader = process.StandardError)
                {
                    string result = reader.ReadToEnd();
                    if (!string.IsNullOrEmpty(result))
                    {
                        Debug.LogError(result);
                        isSuncc = false;
                    }

                }
                //using (StreamReader reader = process.StandardOutput)
                //{
                //    string result = reader.ReadToEnd();
                //    if (!string.IsNullOrEmpty(result))
                //    {
                //        UnityEngine.Debug.Log("" + result);
                //    }

                //}
                process.WaitForExit();
            }
            return isSuncc;
        }



        public static string[] RunProcess(string filePath, string args, string workDir)
        {
            bool isSuncc = true;
            List<string> ls = new List<string>();
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = filePath;
            start.Arguments = args;
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            start.RedirectStandardError = true;
            start.RedirectStandardInput = true;
            //start.CreateNoWindow = true;
            //start.WorkingDirectory = workDir;
            string CurDir = Environment.CurrentDirectory;
            Environment.CurrentDirectory = workDir;
            using (Process process = Process.Start(start))
            {
                process.EnableRaisingEvents = true;
                //process.BeginOutputReadLine();

                process.OutputDataReceived += (s, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data)) Console.WriteLine(e.Data);
                };
                using (StreamReader reader = process.StandardError)
                {
                    string result = reader.ReadToEnd();
                    if (!string.IsNullOrEmpty(result))
                    {
                        Debug.LogError(result);
                        isSuncc = false;
                    }

                }
                using (StreamReader reader = process.StandardOutput)
                {
                    string line = string.Empty;
                    while((line=reader.ReadLine())!=null)
                    {
                        ls.Add(line);
                    }

                }
                process.WaitForExit();
            }
            Environment.CurrentDirectory = CurDir;
            if(isSuncc)
            {
                return ls.ToArray();
            }

            return null;
        }


        public static void RunCmdAsync(string arg)
        {
            System.Console.InputEncoding = System.Text.Encoding.UTF8;
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            //process.StartInfo.Arguments = arg;
            process.StartInfo.UseShellExecute = false;//是否使用操作系統(tǒng)shell啟動(dòng)
            process.StartInfo.RedirectStandardOutput = true;//由調(diào)用程序獲取輸出信息
            process.StartInfo.RedirectStandardError = true;//重定向標(biāo)準(zhǔn)錯(cuò)誤輸出
            process.StartInfo.RedirectStandardInput = true;//接受來自調(diào)用程序的輸入信息
            //process.StartInfo.CreateNoWindow = true;//不顯示程序窗口
            //process.StartInfo.WorkingDirectory = "./";
            process.OutputDataReceived += new DataReceivedEventHandler(OutputReceived);
            process.ErrorDataReceived += new DataReceivedEventHandler(ErrorReceived);            
            process.EnableRaisingEvents = true;                      // 啟用Exited事件  
            process.Exited += new EventHandler(ExitReceived);   // 注冊進(jìn)程結(jié)束事件  

            process.Start();
            process.StandardInput.WriteLine(arg);
            process.StandardInput.WriteLine("exit");
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            // 如果打開注釋档押,則以同步方式執(zhí)行命令伪很,此例子中用Exited事件異步執(zhí)行则北。  
            // CmdProcess.WaitForExit();    
        }

        private static void OutputReceived(object sender,DataReceivedEventArgs e)
        {
            Debug.Log(e.Data);
        }
        private static void ErrorReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data!=null&&e.Data!=string.Empty)
            {
                Debug.LogError("Error::" + e.Data);
            }
            
        }
        private static void ExitReceived(object sender, EventArgs e)
        {
            //Debug.Log("Exit::"+e.ToString());
        }        
    }


使用

ProcessTask.RunCmdAsync("ipconfig");
ProcessTask.RunCmdAsync("path");

這里出現(xiàn)錯(cuò)誤首字母亂碼
C#用Process類調(diào)用cmd時(shí)台囱,命令行那里首字母亂碼

'锘縤pconfig' 不是內(nèi)部或外部命令,也不是可運(yùn)行的程序或批處理文件。

System.Console.InputEncoding = System.Text.Encoding.UTF8;這句代碼加上就好了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市莺戒,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌急波,老刑警劉巖从铲,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異澄暮,居然都是意外死亡名段,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進(jìn)店門泣懊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來伸辟,“玉大人,你說我怎么就攤上這事馍刮⌒欧颍” “怎么了?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵卡啰,是天一觀的道長静稻。 經(jīng)常有香客問我,道長匈辱,這世上最難降的妖魔是什么振湾? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮梅誓,結(jié)果婚禮上恰梢,老公的妹妹穿的比我還像新娘。我一直安慰自己梗掰,他們只是感情好嵌言,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著及穗,像睡著了一般摧茴。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上埂陆,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天苛白,我揣著相機(jī)與錄音,去河邊找鬼焚虱。 笑死购裙,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的鹃栽。 我是一名探鬼主播躏率,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了薇芝?” 一聲冷哼從身側(cè)響起蓬抄,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎夯到,沒想到半個(gè)月后嚷缭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡耍贾,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年阅爽,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片荐开。...
    茶點(diǎn)故事閱讀 40,001評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡优床,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出誓焦,到底是詐尸還是另有隱情胆敞,我是刑警寧澤,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布杂伟,位于F島的核電站移层,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏赫粥。R本人自食惡果不足惜观话,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望越平。 院中可真熱鬧频蛔,春花似錦、人聲如沸秦叛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽挣跋。三九已至三圆,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間避咆,已是汗流浹背舟肉。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留查库,地道東北人路媚。 一個(gè)月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像樊销,于是被迫代替她去往敵國和親整慎。 傳聞我的和親對象是個(gè)殘疾皇子适荣,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)院领,斷路器,智...
    卡卡羅2017閱讀 134,657評論 18 139
  • https://nodejs.org/api/documentation.html 工具模塊 Assert 測試 ...
    KeKeMars閱讀 6,336評論 0 6
  • 字符集和編碼簡介 在編程中常彻环裕可以見到各種字符集和編碼比然,包括ASCII,MBCS,Unicode等字符集。確切的說...
    蘭山小亭閱讀 8,494評論 0 13
  • 幾個(gè)基本概念 bit二進(jìn)制位周循, 是計(jì)算機(jī)內(nèi)部數(shù)據(jù)儲(chǔ)存的最小單位强法,11010100是一個(gè)8位二進(jìn)制數(shù)。一個(gè)二進(jìn)制位只...
    西電大俠閱讀 3,571評論 1 8
  • 作為一名從小愛觀劇的80后孩子湾笛,現(xiàn)在也只能時(shí)不時(shí)跟同齡人一樣感慨:現(xiàn)在的電視劇越來越不好看了饮怯。是我們看了太多電視,...
    笑忘書風(fēng)鈴草閱讀 528評論 0 0