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;
}
}
}
=====================