分享

执行CMD命令并返回结果

 缘木求鱼001 2012-09-27
执行CMD命令并返回结果 
 
private void button1_Click(object sender, EventArgs e) 

    string[] cmd = new string[] { "ping 192.168.3.15 -n 1""ping 192.168.3.16 -n 2" }; 
    MessageBox.Show(Cmd(cmd)); 
    CloseProcess("cmd.exe"); 

 
 
public static string Cmd(string [] cmd) 

    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
    p.Start(); 
    p.StandardInput.AutoFlush = true
    for (int i = 0; i < cmd.Length; i++) 
    { 
        p.StandardInput.WriteLine(cmd[i].ToString()); 
    } 
    p.StandardInput.WriteLine("exit"); 
    string strRst = p.StandardOutput.ReadToEnd(); 
    p.WaitForExit(); 
    p.Close(); 
    return strRst; 

 
 
public static bool CloseProcess(string ProcName) 

    bool result = false
    System.Collections.ArrayList procList = new System.Collections.ArrayList(); 
    string tempName = ""
    int begpos; 
    int endpos; 
    foreach (System.Diagnostics.Process thisProc in System.Diagnostics.Process.GetProcesses()) 
    { 
        tempName = thisProc.ToString(); 
        begpos = tempName.IndexOf("(") + 1
        endpos = tempName.IndexOf(")"); 
        tempName = tempName.Substring(begpos, endpos - begpos); 
        procList.Add(tempName); 
        if (tempName == ProcName) 
        { 
            if (!thisProc.CloseMainWindow()) 
                thisProc.Kill(); // 当发送关闭窗口命令无效时强行结束进程 
            result = true
        } 
    } 
    return result; 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约