C#开发一个可被带参数调用并返回数据的控制台应用程序

发布时间 2023-11-10 16:44:19作者: Stephen_Young

1 标准输出流控制台程序:

namespace ReturnConsoleWrite
{
    class Program
    {
        static void Main(string[] args)
        {
            //程序功能:将所以应用程序输入参数连成一个字符串
            string _output=null;
            for (int i = 0; i < args.Length; i++)
            {
                _output += args[i];
            }
            Console.Write(_output);
        }
    }
}

打包成EXE,如下:

先在cmd窗口测试下看看:

(1)在文件所在目录输入: cmd 然后回车

(2)在cmd窗口输入exe的名称+参数(参数用空格隔开即可)

测试正常!

下面我们用C#再写一个Winform窗体程序来调用上面那个控制台程序试试。

Winform窗体程序


代码如下:

namespace Call
{
    public partial class Form1 : Form
    {
        string _bathpath= System.IO.Directory.GetCurrentDirectory();
        string _call_exe_path;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            /////第一种:返回值类型的exe
            //Process myProcess = new Process();
            //string para = textBox1.Text;
            //ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(_call_exe_path, para);
            //myProcess.StartInfo = myProcessStartInfo;
            //myProcess.Start();
            //while (!myProcess.HasExited)
            //{
            //    myProcess.WaitForExit();
            //}
            //int returnValue = myProcess.ExitCode;
            //textBox2.Text = returnValue.ToString();

            ///第二种:

            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = _call_exe_path;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.Arguments = textBox1.Text;//参数以空格分隔,如果某个参数为空,可以传入””
            p.Start();
            p.WaitForExit();
            string output = p.StandardOutput.ReadToEnd();
            textBox2.Text = output;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text ="BathPath:"+ _bathpath;
            //_call_exe_path = _bathpath + "\\ReturN.exe";
            _call_exe_path = _bathpath + "\\ReturnConsoleWrite.exe";
        }
    }
}

声明:本文参考资料——https://developer.aliyun.com/article/614108