iT邦幫忙

1

C# 用cmd來執行指令

    public string Exec(List<string> commandText)
    {
        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 strOutput = null;
        try
        {
            p.Start();
            for (int i = 0; i < commandText.Count; i++)
            {
                string cmd = commandText[i];
                p.StandardInput.WriteLine(cmd);
            }
            p.StandardInput.WriteLine("exit");
            strOutput = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            p.Close();
        }
        catch (Exception e)
        {
            strOutput = e.Message;
        }
        return strOutput;
    }

尚未有邦友留言

立即登入留言