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

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)
}

Related

Command Line Parser library giving 'System.Type' error in C#

I'm writing a Console App (.NET Framework) in C#. I want to use arguments from the command line, and I'm trying to use the Command Line Parser library to help me do this.
This is the package on Nuget - https://www.nuget.org/packages/CommandLineParser/
I found out about it from this StackOverflow question - Best way to parse command line arguments in C#?
MWE
using System;
using CommandLine;
namespace CLPtest
{
class Program
{
class SomeOptions
{
[Option('n', "name")]
public string Name { get; set; }
}
static void Main(string[] args)
{
var options = new SomeOptions();
CommandLine.Parser.Default.ParseArguments(args, options);
}
}
}
When I try create a minimal working example, I get an error for options on this line:
CommandLine.Parser.Default.ParseArguments(args, options);
The error is Argument 2: cannot convert from 'CLPtest.Program.SomeOptions' to 'System.Type'
I'm really confused as I have seen this same example code on at least 3 tutorials for how to use this library. (see for example - Parsing Command Line Arguments with Command Line Parser Library)
(This answer is being written at the time of v2.7 of this library)
From looking at their repository's README, it appears as if this is part of the API change that is mentioned earlier in the README. It looks as though the arguments are now handled differently since the example code you reference. So, now you should do something like this inside of Main:
...
static void Main(string[] args)
{
CommandLine.Parser.Default.ParseArguments<SomeOptions>(args);
}
...
To actually do something with those options you can use WithParsed which takes in the options that are defined in your SomeOptions class.
...
static void Main(string[] args)
{
CommandLine.Parser.Default.ParseArguments<SomeOptions>(args).WithParsed(option =>
{
// Do something with your parsed arguments in here...
Console.WriteLine(option.Name); // This is the property from your SomeOptions class.
});
}
...
The C# Example further down the README shows that you can pass in a method into WithParsed to handle your options instead of doing everything within Main.

How to add to a class a string with two integers and show the sum

Greeting fellow programmers!
I am currently studying software development (I started not a month ago) and I have a problem that needs a solution. Underneath you can find the code and as you can see, the method WriteNumber needs help. I need to write the code in a way that when I run the program, on the console screen the following two lines will be shown:
Hello World!
81
The Main method code cannot be changed and also I cannot add more methods to the class Calculator so the code needs to be done only within the WriteNumbers method. I have tried a lot of things but I am still grasping how everything works so any help is welcome! Thank you in advance for your time.
Namespace CalculatorTest
{
class Calculator
{
public static string WriteText (string input)
{
return "" + input;
}
public static string WriteNumber()
{
}
}
class Program
{
static void Main(string[] args)
{
string s = Calculator.WriteText("Hello World!");
Console.WriteLine(s);
string n = Calculator.WriteNumber(53 + 28);
Console.WriteLine(n);
Console.Read();
}
}
Not to do your homework for you to just be copied/pasted, hopefully I can give you some hints...
Notice how the method is being invoked:
Calculator.WriteNumber(53 + 28)
The 53 + 28 part happens first, then the result of that operation is passed to the method. That result, naturally, is 81. What's important about that is its type, which is an integer.
So, reasonably, the method signature needs to accept an int as a parameter. This would be done very similarly to how the other method accepts a string as a parameter:
public static string WriteText(string input)
What, then, does that method need to do with that input? Well, it's only a single value, so there aren't any calculations to be performed on it. It would appear that the method simply needs to return the value as a string. (It's your homework so you tell me, is that correct?)
This can be done with exactly two things:
Calling .ToString() on the value
Using the return keyword to return the result of that operation
(Note: The .ToString() operation does something very intuitive on value types, such as int or double or bool. As you progress into using reference types, you're going to find that it does something very different. Any time you have a custom class on which you want to call .ToString(), you'll need to override the .ToString() method on that class first.)
Please read David's answer, it's important that you make the effort to understand why this works the way it does. That being said:
public static string WriteNumber(int number)
{
return number.ToString();
}
Thank you all for your valuable input but special thanks to David because he showed where I made my error. I forgot that the two numbers in the main function will be summed up FIRST and THEN forwarded to the method in the class Calculator. After that got cleared up, it was easy to understand what to do (basically adjust the type of the input parameter to int).
namespace CalculatorTest
{
class Calculator
{
public static string WriteText (string input)
{
return "" + input;
}
public static string WriteNumber(int sumOfNumbers)
{
return "" + sumOfNumbers;
}
}
class Program
{
static void Main(string[] args)
{
string s = Calculator.WriteText("Hello World!");
Console.WriteLine(s);
string n = Calculator.WriteNumber(53 + 28);
Console.WriteLine(n);
Console.Read();
}
}
}

C# Application with Numerous Errors

I am having fun with a couple of errors I am getting in a C# application I am writing.
The error I keep getting is:
encrypt and decrypt calls must have a return type
Console.WriteLine being used as a method
static void encrypt(string[] args) expected class, delegate, interface or struct
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string pw ="", hash =""; //Declare an intialise variables
if (args.Length < 4) // Test to see if correct number of arguments have been passed
{
Console.WriteLine("Please use command line arguments in this format: encrypt -e (or -d) password-to-encrypt-with input-file output-file");
Environment.Exit(0);
}
if (args[1].Length < 10 || args[1].Length > 40) // Test to see if the password is between 10 and 40 characters
{
Console.WriteLine("Please use a password between 10 and 40 characters");
Environment.Exit(0);
}
switch (args[0]) //Uses first argument value to drive switch statement (-e or -d)
{
case "-e":
encrypt(string[] args);
break;
case "-d":
decrypt(string[] args);
break;
default:
Console.WriteLine("When using the program please use -e to encrypt and -d to decrypt");
break;
}
} //End of MAIN
static void encrypt(string[] args) //Function to encrypt
{
string inputtext =""; //Initialise Varible (Ensure it is empty)
inputtext=System.IO.File.ReadAllText(args[2]); //Read file in an assign to input text
return;
}
static void decrypt(string[] args) //Function to decrypt
{
string inputtext =""; //Initialise Varible (Ensure it is empty)
inputtext=System.IO.File.ReadAllText(args[2]); //Read file in an assign to input text
return;
}
}
}
Any help would be much appreciated!
Alistair
When calling a method, you must not specify the types of the arguments. So:
case "-e":
encrypt(args);
break;
Along with what Hans has said, you mentioned an error about return types in your methods.
Your encrypt and decrypt methods have return statements, but they are void methods meaning they don't have any return types.
Either give it a type you want to return (presumably the string you are manipulating) or just remove the return statement altogether. You do not need to explicitly put return at the end of a method to get it to exit out of the method. It will do that anyway.
Two small pro-tips, I would declare your fields on different lines, not all bunched together (with the way you have declared pw and hash) and also add a using directive for System.IO, so you don't have to call System.IO.File.ReadAllText, you can just call File.ReadAllText.

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.

How to receive an argument in console program?

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

Categories