다음을 통해 공유


자습서: 시작 System.CommandLine

중요

System.CommandLine 는 현재 미리 보기로 제공되며 이 설명서는 버전 2.0 베타 4용입니다. 일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.

이 자습서에서는 라이브러리를 사용하는 System.CommandLine.NET 명령줄 앱을 만드는 방법을 보여줍니다. 먼저 하나의 옵션이 있는 간단한 루트 명령을 만듭니다. 그런 다음, 해당 베이스에 를 추가하여 여러 하위 명령과 각 명령에 대한 다양한 옵션을 포함하는 더 복잡한 앱을 만듭니다.

이 자습서에서는 다음 작업 방법을 알아봅니다.

  • 명령, 옵션 및 인수를 만듭니다.
  • 옵션의 기본값을 지정합니다.
  • 명령에 옵션 및 인수를 할당합니다.
  • 명령 아래의 모든 하위 명령에 옵션을 재귀적으로 할당합니다.
  • 여러 수준의 중첩된 하위 명령을 사용합니다.
  • 명령 및 옵션에 대한 별칭을 만듭니다.
  • , , string[], intboolFileInfo 및 열거형 옵션 형식으로 string작업합니다.
  • 명령 처리기 코드에 옵션 값을 바인딩합니다.
  • 옵션 구문 분석 및 유효성 검사에 사용자 지정 코드를 사용합니다.

사전 요구 사항

또는

앱 만들기

"scl"이라는 .NET 6 콘솔 앱 프로젝트를 만듭니다.

  1. 프로젝트에 대한 scl 이라는 폴더를 만든 다음 새 폴더에서 명령 프롬프트를 엽니다.

  2. 다음 명령 실행:

    dotnet new console --framework net6.0
    

System.CommandLine 패키지를 설치합니다.

  • 다음 명령 실행:

    dotnet add package System.CommandLine --prerelease
    

    --prerelease 라이브러리가 베타 버전이므로 옵션이 필요합니다.

  1. Program.cs의 내용을 다음 코드로 바꿉니다.

    using System.CommandLine;
    
    namespace scl;
    
    class Program
    {
        static async Task<int> Main(string[] args)
        {
            var fileOption = new Option<FileInfo?>(
                name: "--file",
                description: "The file to read and display on the console.");
    
            var rootCommand = new RootCommand("Sample app for System.CommandLine");
            rootCommand.AddOption(fileOption);
    
            rootCommand.SetHandler((file) => 
                { 
                    ReadFile(file!); 
                },
                fileOption);
    
            return await rootCommand.InvokeAsync(args);
        }
    
        static void ReadFile(FileInfo file)
        {
            File.ReadLines(file.FullName).ToList()
                .ForEach(line => Console.WriteLine(line));
        }
    }
    

앞의 코드가 하는 역할은 다음과 같습니다.

  • 형식 FileInfo 이라는 옵션을--file 만들고 루트 명령에 할당합니다.

    var fileOption = new Option<FileInfo?>(
        name: "--file",
        description: "The file to read and display on the console.");
    
    var rootCommand = new RootCommand("Sample app for System.CommandLine");
    rootCommand.AddOption(fileOption);
    
  • 루트 명령이 ReadFile 호출될 때 호출될 메서드를 지정합니다.

    rootCommand.SetHandler((file) => 
        { 
            ReadFile(file!); 
        },
        fileOption);
    
  • 루트 명령이 호출될 때 지정된 파일의 내용을 표시합니다.

    static void ReadFile(FileInfo file)
    {
        File.ReadLines(file.FullName).ToList()
            .ForEach(line => Console.WriteLine(line));
    }
    

앱 테스트

명령줄 앱을 개발하는 동안 다음 방법 중 원하는 방법으로 테스트할 수 있습니다.

  • 명령을 실행한 dotnet build 다음 scl/bin/Debug/net6.0 폴더에서 명령 프롬프트를 열어 실행 파일을 실행합니다.

    dotnet build
    cd bin/Debug/net6.0
    scl --file scl.runtimeconfig.json
    
  • 다음 예제와 같이 옵션 값을 사용 dotnet run 후 에 포함하여 --명령 대신 run 앱에 전달합니다.

    dotnet run -- --file scl.runtimeconfig.json
    

    .NET 7.0.100 SDK 미리 보기에서 명령을 dotnet run --launch-profile <profilename>실행하여 launchSettings.json 파일의 를 사용할 commandLineArgs 수 있습니다.

  • 프로젝트를 폴더에 게시하고, 해당 폴더에 명령 프롬프트를 열고, 실행 파일을 실행합니다.

    dotnet publish -o publish
    cd ./publish
    scl --file scl.runtimeconfig.json
    
  • Visual Studio 2022의 메뉴에서 >버그 디버그 속성을 선택하고 명령줄 인수 상자에 옵션 및 인수를 입력합니다. 다음은 그 예입니다.

    Visual Studio 2022의 명령줄 인수

    그런 다음, 예를 들어 Ctrl+F5를 눌러 앱을 실행합니다.

이 자습서에서는 이러한 옵션 중 첫 번째 옵션을 사용 중이라고 가정합니다.

앱을 실행하면 옵션에서 지정한 파일의 내용이 --file 표시됩니다.

{
  "runtimeOptions": {
    "tfm": "net6.0",
    "framework": {
      "name": "Microsoft.NETCore.App",
      "version": "6.0.0"
    }
  }
}

도움말 출력

System.CommandLine 는 자동으로 도움말 출력을 제공합니다.

scl --help
Description:
  Sample app for System.CommandLine

Usage:
  scl [options]

Options:
  --file <file>   The file to read and display on the console.
  --version       Show version information
  -?, -h, --help  Show help and usage information

버전 출력

System.CommandLine 는 버전 출력을 자동으로 제공합니다.

scl --version
1.0.0

하위 명령 및 옵션 추가

이 섹션에서는 다음을 수행합니다.

  • 더 많은 옵션을 만듭니다.
  • 하위 명령을 만듭니다.
  • 새 하위 명령에 새 옵션을 할당합니다.

새 옵션을 사용하면 전경 및 배경 텍스트 색과 읽기 속도를 구성할 수 있습니다. 이러한 기능은 Teleprompter 콘솔 앱 자습서에서 제공되는 따옴표 컬렉션을 읽는 데 사용됩니다.

  1. 이 샘플에 대한 GitHub 리포지토리의 sampleQuotes.txt 파일을 프로젝트 디렉터리로 복사합니다. 파일을 다운로드하는 방법에 대한 자세한 내용은 샘플 및 자습서의 지침을 참조하세요.

  2. 프로젝트 파일을 열고 닫 </Project><ItemGroup> 태그 바로 앞에 요소를 추가합니다.

    <ItemGroup>
      <Content Include="sampleQuotes.txt">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </Content>
    </ItemGroup>
    

    이 태그를 추가하면 앱을 빌드할 때 텍스트 파일이 bin/debug/net6.0 폴더에 복사됩니다. 따라서 해당 폴더에서 실행 파일을 실행할 때 폴더 경로를 지정하지 않고 이름으로 파일에 액세스할 수 있습니다.

  3. Program.cs에서 옵션을 만드는 코드 다음에 --file 읽기 속도 및 텍스트 색을 제어하는 옵션을 만듭니다.

    var delayOption = new Option<int>(
        name: "--delay",
        description: "Delay between lines, specified as milliseconds per character in a line.",
        getDefaultValue: () => 42);
    
    var fgcolorOption = new Option<ConsoleColor>(
        name: "--fgcolor",
        description: "Foreground color of text displayed on the console.",
        getDefaultValue: () => ConsoleColor.White);
    
    var lightModeOption = new Option<bool>(
        name: "--light-mode",
        description: "Background color of text displayed on the console: default is black, light mode is white.");
    
  4. 루트 명령을 만드는 줄 다음에 옵션을 추가하는 --file 줄을 삭제합니다. 새 하위 명령에 추가하므로 여기서 제거합니다.

    var rootCommand = new RootCommand("Sample app for System.CommandLine");
    //rootCommand.AddOption(fileOption);
    
  5. 루트 명령을 만드는 줄 다음에 하위 명령을 만듭니 read 다. 이 하위 명령에 옵션을 추가하고 루트 명령에 하위 명령을 추가합니다.

    var readCommand = new Command("read", "Read and display the file.")
        {
            fileOption,
            delayOption,
            fgcolorOption,
            lightModeOption
        };
    rootCommand.AddCommand(readCommand);
    
  6. SetHandler 코드를 새 하위 명령에 대한 다음 SetHandler 코드로 바꿉 있습니다.

    readCommand.SetHandler(async (file, delay, fgcolor, lightMode) =>
        {
            await ReadFile(file!, delay, fgcolor, lightMode);
        },
        fileOption, delayOption, fgcolorOption, lightModeOption);
    

    루트 명령에 더 이상 처리기가 필요하지 않으므로 더 이상 루트 명령에서 를 호출 SetHandler 하지 않습니다. 명령에 하위 명령이 있는 경우 일반적으로 명령줄 앱을 호출할 때 하위 명령 중 하나를 지정해야 합니다.

  7. 처리기 메서드를 ReadFile 다음 코드로 바꿉 있습니다.

    internal static async Task ReadFile(
            FileInfo file, int delay, ConsoleColor fgColor, bool lightMode)
    {
        Console.BackgroundColor = lightMode ? ConsoleColor.White : ConsoleColor.Black;
        Console.ForegroundColor = fgColor;
        List<string> lines = File.ReadLines(file.FullName).ToList();
        foreach (string line in lines)
        {
            Console.WriteLine(line);
            await Task.Delay(delay * line.Length);
        };
    }
    

이제 앱은 다음과 같습니다.

using System.CommandLine;

namespace scl;

class Program
{
    static async Task<int> Main(string[] args)
    {
        var fileOption = new Option<FileInfo?>(
            name: "--file",
            description: "The file to read and display on the console.");

        var delayOption = new Option<int>(
            name: "--delay",
            description: "Delay between lines, specified as milliseconds per character in a line.",
            getDefaultValue: () => 42);

        var fgcolorOption = new Option<ConsoleColor>(
            name: "--fgcolor",
            description: "Foreground color of text displayed on the console.",
            getDefaultValue: () => ConsoleColor.White);

        var lightModeOption = new Option<bool>(
            name: "--light-mode",
            description: "Background color of text displayed on the console: default is black, light mode is white.");

        var rootCommand = new RootCommand("Sample app for System.CommandLine");
        //rootCommand.AddOption(fileOption);

        var readCommand = new Command("read", "Read and display the file.")
            {
                fileOption,
                delayOption,
                fgcolorOption,
                lightModeOption
            };
        rootCommand.AddCommand(readCommand);

        readCommand.SetHandler(async (file, delay, fgcolor, lightMode) =>
            {
                await ReadFile(file!, delay, fgcolor, lightMode);
            },
            fileOption, delayOption, fgcolorOption, lightModeOption);

        return rootCommand.InvokeAsync(args).Result;
    }

    internal static async Task ReadFile(
            FileInfo file, int delay, ConsoleColor fgColor, bool lightMode)
    {
        Console.BackgroundColor = lightMode ? ConsoleColor.White : ConsoleColor.Black;
        Console.ForegroundColor = fgColor;
        List<string> lines = File.ReadLines(file.FullName).ToList();
        foreach (string line in lines)
        {
            Console.WriteLine(line);
            await Task.Delay(delay * line.Length);
        };
    }
}

새 하위 명령 테스트

이제 하위 명령을 지정하지 않고 앱을 실행하려고 하면 오류 메시지와 사용 가능한 하위 명령을 지정하는 도움말 메시지가 표시됩니다.

scl --file sampleQuotes.txt
'--file' was not matched. Did you mean one of the following?
--help
Required command was not provided.
Unrecognized command or argument '--file'.
Unrecognized command or argument 'sampleQuotes.txt'.

Description:
  Sample app for System.CommandLine

Usage:
  scl [command] [options]

Options:
  --version       Show version information
  -?, -h, --help  Show help and usage information

Commands:
  read  Read and display the file.

하위 명령에 read 대한 도움말 텍스트는 네 가지 옵션을 사용할 수 있음을 보여줍니다. 열거형에 유효한 값을 표시합니다.

scl read -h
Description:
  Read and display the file.

Usage:
  scl read [options]

Options:
  --file <file>                                               The file to read and display on the console.
  --delay <delay>                                             Delay between lines, specified as milliseconds per
                                                              character in a line. [default: 42]
  --fgcolor                                                   Foreground color of text displayed on the console.
  <Black|Blue|Cyan|DarkBlue|DarkCyan|DarkGray|DarkGreen|Dark  [default: White]
  Magenta|DarkRed|DarkYellow|Gray|Green|Magenta|Red|White|Ye
  llow>
  --light-mode                                                Background color of text displayed on the console:
                                                              default is black, light mode is white.
  -?, -h, --help                                              Show help and usage information

옵션만 --file 지정하여 하위 명령을 read 실행하고 다른 세 가지 옵션에 대한 기본값을 가져옵니다.

scl read --file sampleQuotes.txt

문자당 42밀리초의 기본 지연으로 인해 읽기 속도가 느려집니다. 를 더 낮은 숫자로 설정 --delay 하여 속도를 높일 수 있습니다.

scl read --file sampleQuotes.txt --delay 0

및 를 --light-mode 사용하여 --fgcolor 텍스트 색을 설정할 수 있습니다.

scl read --file sampleQuotes.txt --fgcolor red --light-mode

에 잘못된 값을 --delay 입력하면 오류 메시지가 표시됩니다.

scl read --file sampleQuotes.txt --delay forty-two
Cannot parse argument 'forty-two' for option '--int' as expected type 'System.Int32'.

에 잘못된 값을 --file 입력하면 예외가 발생합니다.

scl read --file nofile
Unhandled exception: System.IO.FileNotFoundException:
Could not find file 'C:\bin\Debug\net6.0\nofile'.

하위 명령 및 사용자 지정 유효성 검사 추가

이 섹션에서는 앱의 최종 버전을 만듭니다. 완료되면 앱에는 다음과 같은 명령과 옵션이 있습니다.

  • 이라는 전역* 옵션이 있는 루트 명령 --file
    • quotes 명령
      • read, --fgcolor및 라는 --delay옵션이 있는 명령--light-mode
      • add 및 라는 인수가 있는 quote 명령 byline
      • delete 이름이 옵션인 명령 --search-terms

* 전역 옵션은 할당된 명령에 사용할 수 있으며 모든 하위 명령에 재귀적으로 사용할 수 있습니다.

다음은 옵션 및 인수를 사용하여 사용 가능한 각 명령을 호출하는 샘플 명령줄 입력입니다.

scl quotes read --file sampleQuotes.txt --delay 40 --fgcolor red --light-mode
scl quotes add "Hello world!" "Nancy Davolio"
scl quotes delete --search-terms David "You can do" Antoine "Perfection is achieved"
  1. Program.cs에서 옵션을 만드는 코드를 다음 코드로 바꿉니다--file.

    var fileOption = new Option<FileInfo?>(
        name: "--file",
        description: "An option whose argument is parsed as a FileInfo",
        isDefault: true,
        parseArgument: result =>
        {
            if (result.Tokens.Count == 0)
            {
                return new FileInfo("sampleQuotes.txt");
    
            }
            string? filePath = result.Tokens.Single().Value;
            if (!File.Exists(filePath))
            {
                result.ErrorMessage = "File does not exist";
                return null;
            }
            else
            {
                return new FileInfo(filePath);
            }
        });
    

    이 코드는 를 사용하여 ParseArgument<T> 사용자 지정 구문 분석, 유효성 검사 및 오류 처리를 제공합니다.

    이 코드가 없으면 누락된 파일이 예외 및 스택 추적으로 보고됩니다. 이 코드를 사용하면 지정된 오류 메시지만 표시됩니다.

    또한 이 코드는 기본값을 지정하므로 를 로 true설정합니다isDefault. 로 true설정 isDefault 하지 않으면 에 대한 --file입력이 parseArgument 제공되지 않으면 대리자를 호출하지 않습니다.

  2. 를 만드는 lightModeOption코드 다음에 및 delete 명령에 대한 옵션 및 인수를 add 추가합니다.

    var searchTermsOption = new Option<string[]>(
        name: "--search-terms",
        description: "Strings to search for when deleting entries.")
        { IsRequired = true, AllowMultipleArgumentsPerToken = true };
    
    var quoteArgument = new Argument<string>(
        name: "quote",
        description: "Text of quote.");
    
    var bylineArgument = new Argument<string>(
        name: "byline",
        description: "Byline of quote.");
    

    설정을 AllowMultipleArgumentsPerToken 사용하면 첫 번째 요소 다음에 --search-terms 목록에서 요소를 지정할 때 옵션 이름을 생략할 수 있습니다. 명령줄 입력에 해당하는 다음 예제를 만듭니다.

    scl quotes delete --search-terms David "You can do"
    scl quotes delete --search-terms David --search-terms "You can do"
    
  3. 루트 명령과 read 명령을 만드는 코드를 다음 코드로 바꿉다.

    var rootCommand = new RootCommand("Sample app for System.CommandLine");
    rootCommand.AddGlobalOption(fileOption);
    
    var quotesCommand = new Command("quotes", "Work with a file that contains quotes.");
    rootCommand.AddCommand(quotesCommand);
    
    var readCommand = new Command("read", "Read and display the file.")
        {
            delayOption,
            fgcolorOption,
            lightModeOption
        };
    quotesCommand.AddCommand(readCommand);
    
    var deleteCommand = new Command("delete", "Delete lines from the file.");
    deleteCommand.AddOption(searchTermsOption);
    quotesCommand.AddCommand(deleteCommand);
    
    var addCommand = new Command("add", "Add an entry to the file.");
    addCommand.AddArgument(quoteArgument);
    addCommand.AddArgument(bylineArgument);
    addCommand.AddAlias("insert");
    quotesCommand.AddCommand(addCommand);
    

    이 코드로 다음이 변경됩니다.

    • 명령에서 --fileread 옵션을 제거합니다.

    • --file 루트 명령에 전역 옵션으로 옵션을 추가합니다.

    • quotes 명령을 만들고 루트 명령에 추가합니다.

    • read 루트 명령 quotes 대신 명령에 명령을 추가합니다.

    • 및 명령을 만들고 add 명령에 추가합니다quotes.delete

    결과는 다음 명령 계층 구조입니다.

    • 루트 명령
      • quotes
        • read
        • add
        • delete

    이제 앱은 부모 명령()이 영역 또는 그룹을 지정하고 자식 명령(quotesread, add, delete)이 작업인 권장 패턴을 구현합니다.

    전역 옵션은 명령에 적용되고 하위 명령에 재귀적으로 적용됩니다. --file 는 루트 명령에 있으므로 앱의 모든 하위 명령에서 자동으로 사용할 수 있습니다.

  4. 코드 후에 새 SetHandler 하위 명령에 대한 새 SetHandler 코드를 추가합니다.

    deleteCommand.SetHandler((file, searchTerms) =>
        {
            DeleteFromFile(file!, searchTerms);
        },
        fileOption, searchTermsOption);
    
    addCommand.SetHandler((file, quote, byline) =>
        {
            AddToFile(file!, quote, byline);
        },
        fileOption, quoteArgument, bylineArgument);
    

    하위 명령에 quotes 는 리프 명령이 아니므로 처리기가 없습니다. 하위 명령 read, adddelete 는 아래 quotes의 리프 명령이며 SetHandler 각 명령에 대해 호출됩니다.

  5. delete에 대한 add 처리기를 추가합니다.

    internal static void DeleteFromFile(FileInfo file, string[] searchTerms)
    {
        Console.WriteLine("Deleting from file");
        File.WriteAllLines(
            file.FullName, File.ReadLines(file.FullName)
                .Where(line => searchTerms.All(s => !line.Contains(s))).ToList());
    }
    internal static void AddToFile(FileInfo file, string quote, string byline)
    {
        Console.WriteLine("Adding to file");
        using StreamWriter? writer = file.AppendText();
        writer.WriteLine($"{Environment.NewLine}{Environment.NewLine}{quote}");
        writer.WriteLine($"{Environment.NewLine}-{byline}");
        writer.Flush();
    }
    

완성된 앱은 다음과 같습니다.

using System.CommandLine;

namespace scl;

class Program
{
    static async Task<int> Main(string[] args)
    {
        var fileOption = new Option<FileInfo?>(
            name: "--file",
            description: "An option whose argument is parsed as a FileInfo",
            isDefault: true,
            parseArgument: result =>
            {
                if (result.Tokens.Count == 0)
                {
                    return new FileInfo("sampleQuotes.txt");

                }
                string? filePath = result.Tokens.Single().Value;
                if (!File.Exists(filePath))
                {
                    result.ErrorMessage = "File does not exist";
                    return null;
                }
                else
                {
                    return new FileInfo(filePath);
                }
            });

        var delayOption = new Option<int>(
            name: "--delay",
            description: "Delay between lines, specified as milliseconds per character in a line.",
            getDefaultValue: () => 42);

        var fgcolorOption = new Option<ConsoleColor>(
            name: "--fgcolor",
            description: "Foreground color of text displayed on the console.",
            getDefaultValue: () => ConsoleColor.White);

        var lightModeOption = new Option<bool>(
            name: "--light-mode",
            description: "Background color of text displayed on the console: default is black, light mode is white.");

        var searchTermsOption = new Option<string[]>(
            name: "--search-terms",
            description: "Strings to search for when deleting entries.")
            { IsRequired = true, AllowMultipleArgumentsPerToken = true };

        var quoteArgument = new Argument<string>(
            name: "quote",
            description: "Text of quote.");

        var bylineArgument = new Argument<string>(
            name: "byline",
            description: "Byline of quote.");

        var rootCommand = new RootCommand("Sample app for System.CommandLine");
        rootCommand.AddGlobalOption(fileOption);

        var quotesCommand = new Command("quotes", "Work with a file that contains quotes.");
        rootCommand.AddCommand(quotesCommand);

        var readCommand = new Command("read", "Read and display the file.")
            {
                delayOption,
                fgcolorOption,
                lightModeOption
            };
        quotesCommand.AddCommand(readCommand);

        var deleteCommand = new Command("delete", "Delete lines from the file.");
        deleteCommand.AddOption(searchTermsOption);
        quotesCommand.AddCommand(deleteCommand);

        var addCommand = new Command("add", "Add an entry to the file.");
        addCommand.AddArgument(quoteArgument);
        addCommand.AddArgument(bylineArgument);
        addCommand.AddAlias("insert");
        quotesCommand.AddCommand(addCommand);

        readCommand.SetHandler(async (file, delay, fgcolor, lightMode) =>
            {
                await ReadFile(file!, delay, fgcolor, lightMode);
            },
            fileOption, delayOption, fgcolorOption, lightModeOption);

        deleteCommand.SetHandler((file, searchTerms) =>
            {
                DeleteFromFile(file!, searchTerms);
            },
            fileOption, searchTermsOption);

        addCommand.SetHandler((file, quote, byline) =>
            {
                AddToFile(file!, quote, byline);
            },
            fileOption, quoteArgument, bylineArgument);

        return await rootCommand.InvokeAsync(args);
    }

    internal static async Task ReadFile(
                FileInfo file, int delay, ConsoleColor fgColor, bool lightMode)
    {
        Console.BackgroundColor = lightMode ? ConsoleColor.White : ConsoleColor.Black;
        Console.ForegroundColor = fgColor;
        var lines = File.ReadLines(file.FullName).ToList();
        foreach (string line in lines)
        {
            Console.WriteLine(line);
            await Task.Delay(delay * line.Length);
        };

    }
    internal static void DeleteFromFile(FileInfo file, string[] searchTerms)
    {
        Console.WriteLine("Deleting from file");
        File.WriteAllLines(
            file.FullName, File.ReadLines(file.FullName)
                .Where(line => searchTerms.All(s => !line.Contains(s))).ToList());
    }
    internal static void AddToFile(FileInfo file, string quote, string byline)
    {
        Console.WriteLine("Adding to file");
        using StreamWriter? writer = file.AppendText();
        writer.WriteLine($"{Environment.NewLine}{Environment.NewLine}{quote}");
        writer.WriteLine($"{Environment.NewLine}-{byline}");
        writer.Flush();
    }
}

프로젝트를 빌드한 다음, 다음 명령을 시도합니다.

명령을 사용하여 존재하지 않는 파일을 에 --fileread 제출하면 예외 및 스택 추적 대신 오류 메시지가 표시됩니다.

scl quotes read --file nofile
File does not exist

하위 명령을 quotes 실행하려고 하면 , add또는 delete를 사용하도록 read지시하는 메시지가 표시됩니다.

scl quotes
Required command was not provided.

Description:
  Work with a file that contains quotes.

Usage:
  scl quotes [command] [options]

Options:
  --file <file>   An option whose argument is parsed as a FileInfo [default: sampleQuotes.txt]
  -?, -h, --help  Show help and usage information

Commands:
  read                          Read and display the file.
  delete                        Delete lines from the file.
  add, insert <quote> <byline>  Add an entry to the file.

하위 명령을 add실행한 다음 텍스트 파일의 끝을 확인하여 추가된 텍스트를 확인합니다.

scl quotes add "Hello world!" "Nancy Davolio"

파일의 시작 부분에서 검색 문자열을 사용하여 하위 명령을 delete 실행한 다음 텍스트 파일의 시작을 확인하여 텍스트가 제거된 위치를 확인합니다.

scl quotes delete --search-terms David "You can do" Antoine "Perfection is achieved"

참고

bin/debug/net6.0 폴더에서 실행하는 경우 해당 폴더는 및 delete 명령의 변경 내용 add 이 포함된 파일을 찾을 수 있는 위치입니다. 프로젝트 폴더에 있는 파일의 복사본은 변경되지 않은 상태로 유지됩니다.

다음 단계

이 자습서에서는 를 사용하는 System.CommandLine간단한 명령줄 앱을 만들었습니다. 라이브러리에 대한 자세한 내용은 개요를 참조 System.CommandLine 하세요.