.NET 执行命令行乱码

Process可以运行命令行内容儿不用担心会弹出命令行窗口

需要读取命令行结果时,如果不注意内容编码,就会出现读取的结果出现乱码

读取StandardOutput结果时需要指定StandardOutputEncoding

        Process p = new Process();

            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.StandardOutputEncoding = Encoding.UTF8;// 指定编码
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口


            p.Start();//启动程序
            p.StandardInput.WriteLine("**** & exit");
            p.StandardInput.AutoFlush = true;

            StreamReader sr = p.StandardOutput;
            string output = sr.ReadToEnd();

            p.WaitForExit();
            p.Close();

            Console.WriteLine(output);

这是个小问题,标记一下用法。

原文地址:https://www.cnblogs.com/stealth7/p/8081403.html