桌面应用程序功能使用控制台分离

1
2
3
4
5
6
7
8
9
10
11
12
13
class Program
   {
       static void Main(string[] args)
       {
           if (args.Length > 0)
           {
               using (var fs = new FileStream(@"C:\Users\Administrator\Desktop\" + args[0] + ".txt", FileMode.Create, FileAccess.Write))
               {
                   Console.WriteLine("hahahahahah");
               }
           }
       }
   }

很多时候,我们使用控制台测试程序的时候,很少会使用到args的,那么,args是怎么用的?

 

当我们调用cmd的时候,就可以在空格后,写一个参数,执行这个控制台代码了。


 

那么,如果我们要做一个功能,需要传入参数---执行----输出结果,那么:

使用Net的库函数,调用cmd.exe,让cmd来启动ConsoleText.exe,并且传递参数:

复制代码
 /// <summary>
        /// Program file
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string str;
            RunCMD(@"F:\FMOS_MVC\WupiInvest_Wcf\WupiInvest_Wcf\ConsoleText\bin\Debug\ConsoleText.exe " + "\"HellowWord\"", out str);
            Console.WriteLine(str);
            Console.ReadKey();
        }
        public static void RunCMD(string CMD, out string msg)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(CMD);

            p.StandardInput.AutoFlush = true;
            p.StandardInput.WriteLine("exit");
            //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
            //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令



            //获取cmd窗口的输出信息
            msg = p.StandardOutput.ReadToEnd();
            //StreamReader reader = p.StandardOutput;
            //string line=reader.ReadLine();
            //while (!reader.EndOfStream)
            //{
            //    str += line + "  ";
            //    line = reader.ReadLine();
            //}

            p.WaitForExit();//等待程序执行完退出进程
            p.Close();

        }
复制代码

 

posted on   耀礼士多德  阅读(422)  评论(0编辑  收藏  举报

(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示