How to receive an argument in console program? - c#

So I want other users to be able to run my programm sending arguments. 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

Related

Pass varying arguments to unknown form at runtime

I use the following code to call and open a form at runtime (sourced from this forum). The name of the form depends on user input:
// Method
private void ShowForm(string formToCall)
{
Type type = Type.GetType("MyForms." + formToCall);
var form = Activator.CreateInstance(type) as Form;
}
// Call
ShowForm("StationDef");
Now, some forms take arguments and some not. I can add a parameter with a null default value to the ShowForm() method which will then only change when an argument actually gets passed, but I cannot figure out how to change the ShowForm() code to accept an argument in that case.
Something like this does not work:
private void ShowForm(string formToCall, object arg = null)
{
Type type = Type.GetType("MyForms." + formToCall);
var form = Activator.CreateInstance(type) as Form(arg);
}
Any help will be appreciated.
Maybe try something like:
private void ShowForm(string formToCall, object[] args)
{
Type type = Type.GetType("MyForms." + formToCall);
var form = Activator.CreateInstance(type, args) as Form;
}
You can even make it more "friendly" like this
private void ShowForm(string formToCall, params object[] args)
And use it like this:
ShowForm("MyForm", arg1, arg2);
This won't work because as requires a type name, not a constructor-call.
var form = Activator.CreateInstance(type) as Form(arg);
What you can do instead is passing your arguments to the CreateInstance-method like so:
var form = Activator.CreateInstance(type, arg) as Form;
I'd suggest you parse that arg to object so you do not interfere with other overloaded versions of CreateInstance.
Further Reading

C# service onCustomCommand with parameters?

I am currently trying to implement a service that runs a special command that does something with arguments passed, for example: file paths. I am using the cmd command:
sc control "ServiceName" 128
However, this command doesn't provide any way for me to input arguments. The method is as below:
protected override void OnCustomCommand(int command)
{
switch(command)
{
case 128:
Command.StartProcess(3);
LogWriter.WriteLog("Next output: ");
Command.StartProcess(4);
break;
case 129:
// input extension, output extension, key id , working path
try
{
test t1 = new test();
t1.readLog(#"C:\Users\Joe\Desktop\success.txt");
LogWriter.WriteLog(t1.input);
LogWriter.WriteLog(t1.output);
}
catch(Exception e)
{
LogWriter.WriteLog(e.ToString());
}
finally { LogWriter.WriteLog("abc"); }
//LogWriter.WriteLog(t1.output + "def");
break;
}
}
The only argument i can input is the int command for the method. I would like to input a folder path for t1.readLog();. In the above code, I have to hard code the path which isn't flexible and troublesome. So, is there anyway to work this out?
You are overriding the wrong method for this. Take a look at ServiceBase.OnStart.
It gets array of arguments that can be set in command line like this:
sc start MyService arg1 arg2
Parse args array as you want:
protected override void OnStart(string[] args)
{
var path = args[0];
var someParameter = args[1];
}
Process initialization arguments for the service in the OnStart
method, not in the Main method. The arguments in the args parameter
array can be set manually in the properties window for the service in
the Services console

Passing an array as `params` argument

I have the following method:
void MyMethod(params object[] args)
{
}
which I am trying to call with a parameter of type object[]:
object[] myArgs = GetArgs();
MyMethod(myArgs);
It compiles fine, but inside MyMethod I args == { myArgs}, i.e. an array with one element that is my original arguments. Obviously I wanted to have args = myArgs, what am I doing wrong?
EDIT:
Jon Skeet was actually right, the GetArgs() did wrap the thing in an one element array, sorry for stupid question.
What you've described simply doesn't happen. The compiler does not create a wrapper array unless it needs to. Here's a short but complete program demonstrating this:
using System;
class Test
{
static void MyMethod(params object[] args)
{
Console.WriteLine(args.Length);
}
static void Main()
{
object[] args = { "foo", "bar", "baz" };
MyMethod(args);
}
}
According to your question, this would print 1 - but it doesn't, it prints 3. The value of args is passed directly to MyMethod, with no further expansion.
Either your code isn't as you've posted it, or the "wrapping" occurs within GetArgs.
You can force it to wrap by casting args to object. For example, if I change the last line of Main to:
MyMethod((object) args);
... then it prints 1, because it's effectively calling MyMethod(new object[] { args }).

How to write a program in C# that can take arguments

I've seen alot of command-line programs that take arguments, like ping google.com -t. How can I make a program like ping? I would like my program to take a number as an argument and then further use this number:
For example:
geturi -n 1188
Just write a generic, console application.
The main method looks like the following snippet:
class Program
{
static void Main(string[] args)
{
}
}
Your arguments are included in the args array.
With a normal Console Application, in static void Main(string[] args), simply use the args. If you want to read the first argument as a number, then you simply use:
static void Main(string[] args)
{
if (args.Length > 1)
{
int arg;
if (int.TryParse(args[0], out arg))
// use arg
else // show an error message (the input was not a number)
}
else // show an error message (there was no input)
}

Why does C# handle command line args inconsistently?

In C#, getting command line arguments directly from Main() omits the exe name, contrary to the tradition of C.
Getting those same command line args via Environment.GetCommandLineArgs includes it.
Is there some good logical reason I'm missing for this apparent inconsistency?
class Program
{
static void Main(string[] args)
{
Console.WriteLine(string.Format("args.Length = {0}", args.Length));
foreach(string arg in args)
{
Console.WriteLine(string.Format("args = {0}", arg));
}
Console.WriteLine("");
string[] Eargs = Environment.GetCommandLineArgs();
Console.WriteLine(string.Format("Eargs.Length = {0}", Eargs.Length));
foreach (string arg in Eargs)
{
Console.WriteLine(string.Format("Eargs = {0}", arg));
}
}
}
Output:
C:\\ConsoleApplication1\ConsoleApplication1\bin\Debug>consoleapplication1 xx zz aa
args.Length = 3
args = xx
args = zz
args = aa
Eargs.Length = 4
Eargs = consoleapplication1
Eargs = xx
Eargs = zz
Eargs = aa
Because it isn't C and thus isn't tied to it's conventions. Needing the exe name is pretty much an edge case; the small number of times I've needed this (compared to the other args) IMO justifies the decision to omit it.
This is additionally demanded in the spec (ECMA334v4, §10.1); (snipping to relevant parts):
10. Basic concepts
10.1 Application startup
...
This entry point method is always named Main, and shall have one of the
following signatures:
static void Main() {…}
static void Main(string[] args) {…}
static int Main() {…}
static int Main(string[] args) {…}
...
• Let args be the name of the parameter. If the length of the array designated by args is greater than
zero, the array members args[0] through args[args.Length-1], inclusive, shall refer to strings,
called application parameters, which are given implementation-defined values by the host environment
prior to application startup. The intent is to supply to the application information determined prior to
application startup from elsewhere in the hosted environment. If the host environment is not capable of
supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the
strings are received in lowercase. [Note: On systems supporting a command line, application, application parameters
correspond to what are generally known as command-line arguments. end note]
[status-by-design] -- http://msdn.microsoft.com/en-us/library/acy3edy3(v=VS.100).aspx
Unlike C and C++, the name of the program is not treated as the first command-line argument.
To me, the reason the two methods return different results is due to Context.
The Environment class is used to manipulate the current environement and process, and it makes sense that Environment.GetCommandLineArgs(); returns the executable name, since it is part of the process.
As for the args array, to me it makes sense to exclude the executable name. I know that I am calling the executable and in the context of running my application I want to know what arguments were sent to it.
At the end of the day, it is powerful to have a way to get at both alternatives.

Categories