亲宝软件园·资讯

展开

c#执行外部命令 c#执行外部命令示例分享

人气:0
想了解c#执行外部命令示例讲解的相关内容吗,在本文为您仔细讲解c#执行外部命令的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:执行外部命令,下面大家一起来学习吧。

复制代码 代码如下:

String Command = @"python test.py";
String Output = Execute.run(Command);
Console.WriteLine(Output);

复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

//using before change the namespace
namespace test.utility
{
    class Execute
    {
        public static String run(String Command)
        {
            String Output = null;

            if (Command != null && !Command.Equals(""))
            {
                Process process = new Process();
                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.FileName = "cmd.exe";
                //no create the cmd windows
                processStartInfo.CreateNoWindow = true;
                processStartInfo.RedirectStandardInput = true;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.RedirectStandardError = true;
                processStartInfo.UseShellExecute = false;

                process.StartInfo = processStartInfo;

                try
                {
                    process.Start();
                    process.StandardInput.WriteLine(Command);
                    process.StandardInput.WriteLine("exit");
                    process.WaitForExit(30 * 1000);
                    Output = process.StandardOutput.ReadToEnd();
                }
                catch (Exception e)
                {
                    process.Close();
                    return e.ToString();
                }
                finally
                {
                    process.Close();
                }
            }

            return ContextFilter(Output);
        }

        public static String ContextFilter(String Output)
        {
            Regex regex_end = new Regex("^[^^]*#end");
            Match match = regex_end.Match(Output);
            Regex regex_begin = new Regex("^[^^]*?#begin\r\n");
            String result = regex_begin.Replace(match.Value, "");
            Regex regex_tar = new Regex("\r\n#end$");
            result = regex_tar.Replace(result,"");
            return result;
        }
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论