C# コンソールアプリでコマンドライン引数と標準入力を扱う方法

コンピュータ

コンソールアプリで、コマンドライン引数と標準入力で、ファイルパスを渡すプログラムのサンプルコード。

ソースコード

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        var options = ParseOptions(args);

        if (options.ShowHelp)
        {
            PrintHelp();
            return;
        }

        foreach (var path in GetInputPaths(options))
        {
            Console.WriteLine(path);
        }
    }

    // ===== オプション定義 =====
    class Options
    {
        public string Algorithm { get; set; } = "sha256";
        public bool ShowHelp { get; set; }
        public List<string> Files { get; } = new();
    }

    // ===== オプション解析 =====
    static Options ParseOptions(string[] args)
    {
        var opt = new Options();

        for (int i = 0; i < args.Length; i++)
        {
            var arg = args[i];

            switch (arg)
            {
                case "-h":
                case "--help":
                    opt.ShowHelp = true;
                    break;

                case "-a":
                case "--algorithm":
                    if (i + 1 < args.Length)
                    {
                        opt.Algorithm = args[++i];
                    }
                    break;

                default:
                    // オプションでないものはファイルパス
                    opt.Files.Add(arg);
                    break;
            }
        }

        return opt;
    }

    // ===== 入力取得 =====
    static IEnumerable<string> GetInputPaths(Options options)
    {
        // ① ファイル引数がある場合
        if (options.Files.Count > 0)
        {
            foreach (var file in options.Files)
            {
                yield return file;
            }
            yield break;
        }

        // ② 標準入力
        while (true)
        {
            var line = Console.ReadLine();
            if (line == null)
                yield break;

            if (!string.IsNullOrWhiteSpace(line))
                yield return line;
        }
    }

    // ===== ヘルプ =====
    static void PrintHelp()
    {
        Console.WriteLine("""
        Usage:
          HashTool [options] [files...]

        Options:
          -a, --algorithm <name>   Hash algorithm (default: sha256)
          -h, --help               Show help
        """);
    }
}

実行例

ヘルプ表示

.\ArgvStdinSample.exe --help
Usage:
  HashTool [options] [files...]

Options:
  -a, --algorithm <name>   Hash algorithm (default: sha256)
  -h, --help               Show help

コマンドライン引数

.\ArgvStdinSample.exe aaa.bin bbb.bin ccc.bin -a sha256
aaa.bin
bbb.bin
ccc.bin

標準入力

ls | % { $_.FullName } | .\ArgvStdinSample.exe -a sha256
J:\csharp\console\ArgvStdinSample\output\ArgvStdinSample.deps.json
J:\csharp\console\ArgvStdinSample\output\ArgvStdinSample.dll
J:\csharp\console\ArgvStdinSample\output\ArgvStdinSample.exe
J:\csharp\console\ArgvStdinSample\output\ArgvStdinSample.pdb
J:\csharp\console\ArgvStdinSample\output\ArgvStdinSample.runtimeconfig.json

コメント