如何获取命令行参数并将其放入变量? [英] How to get command line parameters and put them into variables?

查看:70
本文介绍了如何获取命令行参数并将其放入变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提出申请.有人可以帮助我如何获取命令行参数并将其放入变量/字符串中.我需要在C#上执行此操作,它必须是5个参数.

I am trying to make an application. Can someone help me how to get command line parameters and put them into variables/strings. I need to do this on C#, and it must be 5 parameters.

第一个参数需要放入Title变量中. 第二个参数需要放入Line1变量中. 第三个参数需要放入Line2变量中. 第四个参数需要放入Line3变量中. 并且第五个参数需要放入Line4变量中.

The first parameter needs to be put into Title variable. The second parameter needs to be put into Line1 variable. The third parameter needs to be put into Line2 variable. The fourth parameter needs to be put into Line3 variable. And the fifth parameter needs to be put into Line4 variable.

感谢您的帮助!

我需要将其添加到Windows窗体应用程序中.

I need to add this into Windows Forms Application.

推荐答案

您可以通过以下两种方式之一进行操作.

You can do it in one of two ways.

第一种方法是使用string[] args并将其从Main传递到您的Form,就像这样:

The first way is to use string[] args and pass that from Main to your Form, like so:

// Program.cs
namespace MyNamespace
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyForm(args));
        }
    }
}

然后在MyForm.cs中执行以下操作:

And then in MyForm.cs do the following:

// MyForm.cs
namespace MyNamespace
{
    public partial class MyForm : Form
    {
        string Title, Line1, Line2, Line3, Line4;
        public MyForm(string[] args)
        {
            if (args.Length == 5)
            {
                Title = args[0];
                Line1 = args[1];
                Line2 = args[2];
                Line3 = args[3];
                Line4 = args[4];
            }
        }
    }
}

另一种方法是使用Environment.GetCommandLineArgs(),就像这样:

The other way is to use Environment.GetCommandLineArgs(), like so:

// MyForm.cs
namespace MyNamespace
{
    public partial class MyForm : Form
    {
        string Title, Line1, Line2, Line3, Line4;
        public MyForm()
        {
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length == 6)
            {
                // note that args[0] is the path of the executable
                Title = args[1];
                Line1 = args[2];
                Line2 = args[3];
                Line3 = args[4];
                Line4 = args[5];
            }
        }
    }
}

,您只需离开Program.cs原始状态,就不用string[] args.

and you would just leave Program.cs how it was originally, without the string[] args.

这篇关于如何获取命令行参数并将其放入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆