C# Programming Guide - Main() and Command-Line Arguments 프로그래밍/C#2017. 5. 10. 17:59
- Main() and Command-Line Arguments
- Command-Line Arguments
- How to: Display Command Line Arguments
- How to: Access Command-Line Arguments Using foreach
- Main() Return Values
https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/main-and-command-args/
Main() and Command-Line Arguments
The Main
method is the entry point of a C# console application or windows application. (Libraries and services do not require a Main
method as an entry point.). When the application is started, the Main
method is the first method that is invoked.
There can only be one entry point in a C# program. If you have more than one class that has a Main
method, you must compile your program with the /main compiler option to specify which Main
method to use as the entry point. For more information, see .
class TestClass
{
static void Main(string[] args)
{
// Display the number of command line arguments:
System.Console.WriteLine(args.Length);
}
}
Overview
The
Main
method is the entry point of an .exe program; it is where the program control starts and ends.Main
is declared inside a class or struct.Main
must be and it should not be . (In the earlier example, it receives the default access of .) The enclosing class or struct is not required to be static.Main
can either have avoid
orint
return type.The
Main
method can be declared with or without astring[]
parameter that contains command-line arguments. When using Visual Studio to create Windows Forms applications, you can add the parameter manually or else use the class to obtain the command-line arguments. Parameters are read as zero-indexed command-line arguments. Unlike C and C++, the name of the program is not treated as the first command-line argument.
In This Section
Command-Line Arguments
You can send arguments to the Main
method by defining the method in one of the following ways:
static int Main(string[] args)
static void Main(string[] args)
Note
To enable command-line arguments in the Main
method in a Windows Forms application, you must manually modify the signature of Main
in program.cs. The code generated by the Windows Forms designer creates a Main
without an input parameter. You can also use or to access the command-line arguments from any point in a console or Windows application.
The parameter of the Main
method is a array that represents the command-line arguments. Usually you determine whether arguments exist by testing the Length
property, for example:
if (args.Length == 0)
{
System.Console.WriteLine("Please enter a numeric argument.");
return 1;
}
You can also convert the string arguments to numeric types by using the Parse
method. For example, the following statement converts the string
to a long
number by using the method:
long num = Int64.Parse(args[0]);
It is also possible to use the C# type long
, which aliases Int64
:
long num = long.Parse(args[0]);
You can also use the Convert
class method ToInt64
to do the same thing:
long num = Convert.ToInt64(s);
For more information, see
and .Example
The following example shows how to use command-line arguments in a console application. The application takes one argument at run time, converts the argument to an integer, and calculates the factorial of the number. If no arguments are supplied, the application issues a message that explains the correct usage of the program.
To compile and run the application from a command prompt, follow these steps:
Paste the following code into any text editor, and then save the file as a text file with the name
Factorial.cs
.C#//Add a using directive for System if the directive isn't already present. public class Functions { public static long Factorial(int n) { // Test for invalid input if ((n < 0) || (n > 20)) { return -1; } // Calculate the factorial iteratively rather than recursively: long tempResult = 1; for (int i = 1; i <= n; i++) { tempResult *= i; } return tempResult; } } class MainClass { static int Main(string[] args) { // Test if input arguments were supplied: if (args.Length == 0) { System.Console.WriteLine("Please enter a numeric argument."); System.Console.WriteLine("Usage: Factorial <num>"); return 1; } // Try to convert the input arguments to numbers. This will throw // an exception if the argument is not a number. // num = int.Parse(args[0]); int num; bool test = int.TryParse(args[0], out num); if (test == false) { System.Console.WriteLine("Please enter a numeric argument."); System.Console.WriteLine("Usage: Factorial <num>"); return 1; } // Calculate factorial. long result = Functions.Factorial(num); // Print result. if (result == -1) System.Console.WriteLine("Input must be >= 0 and <= 20."); else System.Console.WriteLine("The Factorial of {0} is {1}.", num, result); return 0; } } // If 3 is entered on command line, the // output reads: The factorial of 3 is 6.
From the Start screen or Start menu, open a Visual Studio Developer Command Prompt window, and then navigate to the folder that contains the file that you just created.
Enter the following command to compile the application.
csc Factorial.cs
If your application has no compilation errors, an executable file that's named
Factorial.exe
is created.Enter the following command to calculate the factorial of 3:
Factorial 3
The command produces this output:
The factorial of 3 is 6.
Note
When running an application in Visual Studio, you can specify command-line arguments in the
.For more examples about how to use command-line arguments, see
.How to: Display Command Line Arguments
Arguments provided to an executable on the command-line are accessible through an optional parameter to Main
. The arguments are provided in the form of an array of strings. Each element of the array contains one argument. White-space between arguments is removed. For example, consider these command-line invocations of a fictitious executable:
Input on Command-line | Array of strings passed to Main |
---|---|
executable.exe a b c | "a" "b" "c" |
executable.exe one two | "one" "two" |
executable.exe "one two" three | "one two" "three" |
Note
When you are running an application in Visual Studio, you can specify command-line arguments in the
.Example
This example displays the command line arguments passed to a command-line application. The output shown is for the first entry in the table above.
class CommandLine
{
static void Main(string[] args)
{
// The Length property provides the number of array elements
System.Console.WriteLine("parameter count = {0}", args.Length);
for (int i = 0; i < args.Length; i++)
{
System.Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
}
}
}
/* Output (assumes 3 cmd line args):
parameter count = 3
Arg[0] = [a]
Arg[1] = [b]
Arg[2] = [c]
*/
How to: Access Command-Line Arguments Using foreach
Another approach to iterating over the array is to use the statement as shown in this example. The foreach
statement can be used to iterate over an array, a .NET Framework collection class, or any class or struct that implements the interface.
Note
When running an application in Visual Studio, you can specify command-line arguments in the
.Example
This example demonstrates how to print out the command line arguments using foreach
.
// arguments: John Paul Mary
class CommandLine2
{
static void Main(string[] args)
{
System.Console.WriteLine("Number of command line parameters = {0}", args.Length);
foreach (string s in args)
{
System.Console.WriteLine(s);
}
}
}
/* Output:
Number of command line parameters = 3
John
Paul
Mary
*/
Main() Return Values
The Main
method can return void
:
static void Main()
{
//...
}
It can also return an int
:
static int Main()
{
//...
return 0;
}
If the return value from Main
is not used, returning void
allows for slightly simpler code. However, returning an integer enables the program to communicate status information to other programs or scripts that invoke the executable file. The following example shows how the return value from Main
can be accessed.
Example
In this example, a batch file is used to run a program and test the return value of the Main
function. When a program is executed in Windows, any value returned from the Main
function is stored in an environment variable called ERRORLEVEL
. A batch file can determine the outcome of execution by inspecting the ERRORLEVEL
variable. Traditionally, a return value of zero indicates successful execution. The following example is a simple program that returns zero from the Main
function. The zero indicates that the program ran successfully. Save the program as MainReturnValTest.cs.
// Save this program as MainReturnValTest.cs.
class MainReturnValTest
{
static int Main()
{
//...
return 0;
}
}
Example
Because this example uses a batch file, it is best to compile the code from a command prompt. Follow the instructions in Start menu under Visual Studio Tools. From the command prompt, navigate to the folder in which you saved the program. The following command compiles MainReturnValTest.cs and produces the executable file MainReturnValTest.exe.
to enable command-line builds, or use the Visual Studio Command Prompt, available from thecsc MainReturnValTest.cs
Next, create a batch file to run MainReturnValTest.exe and to display the result. Paste the following code into a text file and save it as test.bat
in the folder that contains MainReturnValTest.cs and MainReturnValTest.exe. Run the batch file by typing test
at the command prompt.
Because the code returns zero, the batch file will report success. However, if you change MainReturnValTest.cs to return a non-zero value and then re-compile the program, subsequent execution of the batch file will report failure.
rem test.bat
@echo off
MainReturnValTest
@if "%ERRORLEVEL%" == "0" goto good
:fail
echo Execution Failed
echo return value = %ERRORLEVEL%
goto end
:good
echo Execution succeeded
echo Return value = %ERRORLEVEL%
goto end
:end
Sample Output
Execution succeeded
Return value = 0
'프로그래밍 > C#' 카테고리의 다른 글
C# Programming Guide - Delegates (0) | 2017.06.18 |
---|---|
C# Programming Guide - Classes and Structs (0) | 2017.05.16 |
C# Programming Guide - Strings (0) | 2017.05.10 |
C# Programming Guide - Types (0) | 2017.05.10 |
C# Programming Guide - Inside a C# Program (0) | 2017.05.10 |