zoukankan      html  css  js  c++  java
  • C# 使用cmd输入参数来执行控制台应用程序

    在外部可以使用cmd命令向C#控制台应用程序发送参数,并使之处理。main函数的形参一定要包含string[] args,否则该控制台应用程序不能接收外部参数。在使用cmd调用程序的时候,外部每个参数之间需要用空格隔开。

    以下代码的逻辑是,将外部输入的参数追加的文本文件中,按照每行一个参数值的方式追加:

    class Program {
            static void Main(string[] args) {
                try {
                    if(args != null && args.Length > 0) {
                        FileTo(Path.Combine(Application.StartupPath,"test.txt"),args);
                    }
                }
                catch(Exception ex) {
                    Console.WriteLine(ex.Message);
                }
            }
    
            public static void FileTo(string path,string[] param) {
                FileStream fs = null;
                StreamWriter sw = null;
                try {
                    if(param != null && param.Length > 0) {
                        fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                        sw = new StreamWriter(fs);
                        foreach(string item in param)
                            sw.WriteLine(item);
                    }
                }
                catch(Exception ex) {
                    Console.WriteLine(ex.Message);
                }
                finally {
                    if(sw != null)
                        sw.Close();
                    if(fs != null)
                        fs.Close();
                }
            }
    
        }

    在外部用cmd调用该控制台应用程序,ConsoleAppTest2.exe是编译后的控制台应用程序文件:

    外部调用控制台应用程序后得到的结果:

    文本文档中的结果:

    经过本次实践,说明C#控制台应用程序的main方法可以接收外部参数,它可以成为一个外部调用该程序的一个入口。

  • 相关阅读:
    C#读写txt文件的两种方法介绍
    C#委托的介绍(delegate、Action、Func、predicate)
    C#邮件发送
    ASP.NET 文件上传于下载
    关于Virtual Box虚拟机里的系统不能启动的解决方法
    unity的yield
    unity文件路径
    手机上的unity路径
    readonly
    unity延迟加载图片
  • 原文地址:https://www.cnblogs.com/williamwsj/p/6109644.html
Copyright © 2011-2022 走看看