开发者

How to receive an argument in console program?

So I want other users to be able to run my programm sending arguments. 开发者_Python百科how to do such thing?


If you have a Main method (which you'll have with a command-line app) you can access them directly as the args string-array parameter.

public static void Main(string[] args) {
   var arg1 = args[0];
   var arg2 = args[1];
}

If you're some other place in your code you can access the static Environment.GetCommandLineArgs method

//somewhere in your code
var args = Environment.GetCommandLineArgs();
var arg1 = args[0];
var arg2 = args[1];


You mean args when launching? such as myapp.exe blah blah2 blah3

Make your main method look like this:

public static void Main(string[] args)
{

}

now args is an array of the arguments passed into the program. So in the example case, args[0] == "blah", args[1] == "blah2", etc


The program is run from a method with this signature

public static void Main(string[] args)

The parameter args will contain the command line arguments, split on space.


While string[] args works just fine, it's worth mentioning Environment.GetCommandLineArgs.


You can read command line arguments from Main's optional string[] parameter:

static void Main(string[] args)
{
    if (args.Length >= 1)
    {
        string x = args[0];
        // etc...
    }
}

Note that the following declaration for the Main method is also valid, but then you don't have access to the command line arguments:

static void Main()
{
    // ...
}

See the documentation for more details.


This is supported by default, and the arguments will appear in the args array passed to your program.

public static void Main(string[] args)

If you say

App.exe Hello World What's Up

On a command line, you will receive an args array like this:

[0] = "Hello"
[1] = "World"
[2] = "What's"
[3] = "Up"

It's just up to you to determine what arguments you want, how they will be formatted, etc.


try these:

http://sourceforge.net/projects/csharpoptparse/

http://www.codeproject.com/KB/recipes/command_line.aspx

they basically allow you to define args and parse them in an OO way rather than having to lots of string comparisons and stuff like that. i used a similar one for java and it was great

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜