close

C# - 執行cmd(命令提示字元)

 

====================

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        string str = "c:\\Users\\User\\Desktop\\test.py";
        static void Main(string[] args)
        {
            Process p = new Process();
            String str = null;

            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; //不跳出cmd視窗


            p.Start();
            p.StandardInput.WriteLine("ipconfig");
            p.StandardInput.WriteLine("c:\\Users\\User\\Desktop\\test.py");
            p.StandardInput.WriteLine("exit");

            str = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            p.Close();
           

            Console.WriteLine(str);
            Console.ReadKey();

        }
    }
}

======================

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
    public class ClassRicky
    {
       
        public string cmd (string str)
        {
            //c:\\Users\\User\\Desktop\\test.py

            Process p = new Process();
            // string str = null;
            //string str = null;
            string str1;
            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; //不跳出cmd視窗


            p.Start();
            p.StandardInput.WriteLine("ipconfig");
            p.StandardInput.WriteLine(str);
            p.StandardInput.WriteLine("exit");
            //str = null;
            str1 = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            p.Close();

            //Console.WriteLine(str);
            //Console.ReadKey();
            return str1;

        }
    }
}

 

=====================

https://dotblogs.com.tw/jj_lifenote/2018/04/24/200342

全站熱搜
創作者介紹
創作者 ricky10116r2d2 的頭像
ricky10116r2d2

ricky10116r2d2的部落格

ricky10116r2d2 發表在 痞客邦 留言(0) 人氣()