Home Full Site
Command Line Argument의 사용

C# 프로그램 (EXE 실행 파일)을 콘솔 윈도우 (cmd.exe) 에서 실행할 때, 실행파일 뒤에 프로그램에서 사용할 옵션들 (Command-Line Argument 라 부름)을 사용할 수 있다. 이렇게 지정된 옵션들은 C# 프로그램의 Main(string[] args) 메서드의 입력 파라미터인 args 에 전달된다.

만약 Command Line Argument가 지정되지 않으면, args 는 비어 있게 된다. 만약 Command Line Argument가 하나 지정되면, args 문자열 배열에는 하나의 문자열이 전달되고 첫번째 배열요소 즉 args[0]에 해당 아규먼트가 전달된다. 만약 Command Line Argument가 2개 지정되면, args 문자열 배열에는 2개의 문자열이 전달되고 순서대로 각각 args[0], args[1] 에 아규먼트가 전달된다.

Command Line Argument들은 공백(Space)로 구분하는 데, 만약 아규먼트 내에 공백이 있으면 (예를 들어 파일경로에 공백이 있는 경우), 그 아규먼트를 이중인용부호(double quote)로 묶어 준다.

아래 예제는 2개의 아규먼트가 전달되었을 때, 각 args 배열 요소들에 어떤 값들이 전달되지 보여 주는 예이다.


예제

static void Main(string[] args)
{
    int argsCount = args.Length;

    if (argsCount < 2)
    {
        Console.WriteLine("Usage: MyApp.exe {inputFilename} {outputFilename}");
        Console.WriteLine("   ex) MyApp.exe data.inp data.out");
        return;
    }

    string inputFile = args[0];
    string outputFile = args[1];

    Console.WriteLine("Input File: {0}", inputFile);
    Console.WriteLine("Output File: {0}", outputFile);
}





Visual Studio에서 Command Line Argument 지정하기

콘솔에서와 같이 Visual Studio에서도 Command Line Argument를 지정할 수 있다. Visual Studio의 [Solution Explorer]에서 프로젝트 노드로부터 오른쪽 버튼을 눌러 [속성창 (Properties)] 메뉴를 선택하여 프로젝트 속성창을 띄운 후, Debug 탭을 선택 중앙의 [Command line arguments] 텍스트박스에 커맨드 라인 아규먼트를 지정한다.

아래 그림은 data.in 과 data.out 이라는 2개의 아규먼트를 지정한 예이다.







Environment.GetCommandLineArgs() 사용

Main() 메서드 밖에서 Command Line Argument들을 엑세스하기 위해서는 Environment.GetCommandLineArgs() 메서드를 사용할 수 있다. Environment.GetCommandLineArgs()은 프로그램 실행파일 경로를 포함하여 모든 Argument들을 문자열 배열로 리턴한다. 즉, Main(string[] args) 메서드의 args 파라미터가 콘솔 옵션들만을 포함하는 것과 달리, Environment.GetCommandLineArgs() 메서드는 첫번째 배열요소에 프로그램 실행파일 경로도 포함한다.

아래 예제에서 보이듯이, 만약 콘솔에서 "MyApp.exe a b c" 를 실행하면, Main 메서드의 args 파라미터는 "a", "b", "c" 등 3개의 문자열을 갖는 반면, Environment.GetCommandLineArgs()는 "MyApp.exe", "a", "b", "c" 등 4개의 문자열을 리턴한다.

또한, 한가지 주의할 점은 만약 콘솔이 아니라 Visual Studio에서 Command Line Argument를 지정하고 Environment.GetCommandLineArgs()를 사용하였다면, 첫번째 배열요소인 실행 프로그램명이 실행모드("Start Debugging" vs "Start without debugging") 에 따라 틀려진다는 점이다. 디버깅 모드가 아닌 경우 (Start without debugging) 실행파일명은 MyApp.exe 처럼 되지만, 디버깅 모드(Start Debugging)에서는 MyApp.exe 가 아니라 MyApp.vshost.exe 가 된다. 이는 디버깅 모드에서 VS가 대신 MyApp.vshost.exe 을 실행하기 때문이다.


예제

using System;

namespace MyApp
{
    class Program
    {
        /// <summary>
        /// "C> MyApp.exe a b c" 가 실행되었을 때
        /// </summary>        
        static void Main(string[] args)
        {
            // args = { "a", "b", "c" }
            foreach (var item in args)
            {
                Console.WriteLine(item);
            }

            Run();
        }

        static void Run()
        {
            string[] args2 = Environment.GetCommandLineArgs();

            // args2 = { "MyApp.exe", "a", "b", "c" }
            foreach (var item in args2)
            {
                Console.WriteLine(item);
            }
        }
    }
}



© csharpstudy.com