如何在命令行参数中读取文件否则标准?(模拟Python的文件输入)

Col*_*nic 7 .net c#

我希望我的应用程序从命令行参数或标准输入指定的文件中读取,因此用户可以使用它myprogram.exe data.txtotherprogram.exe | myprogram.exe.我怎么能在C#中做到这一点?


在Python中,我会写

import fileinput
for line in fileinput.input():
    process(line)
Run Code Online (Sandbox Code Playgroud)

这将迭代sys.argv [1:]中列出的所有文件的行,如果列表为空,则默认为sys.stdin.如果文件名是' - ',它也会被sys.stdin替换.

Perl <>和Ruby's ARGF同样有用.

Jef*_*ado 8

stdin作为一个TextReader通过暴露给你Console.In.只需TextReader为您的输入声明一个变量,或者使用Console.In您选择的文件,并将其用于所有输入操作.

static TextReader input = Console.In;
static void Main(string[] args)
{
    if (args.Any())
    {
        var path = args[0];
        if (File.Exists(path))
        {
            input = File.OpenText(path);
        }
    }

    // use `input` for all input operations
    for (string line; (line = input.ReadLine()) != null; )
    {
        Console.WriteLine(line);
    }
}
Run Code Online (Sandbox Code Playgroud)

否则,如果重构使用这个新变量太昂贵,您可以随时使用重定向Console.In到您的文件Console.SetIn().

static void Main(string[] args)
{
    if (args.Any())
    {
        var path = args[0];
        if (File.Exists(path))
        {
            Console.SetIn(File.OpenText(path));
        }
    }

    // Just use the console like normal
    for (string line; (line = Console.ReadLine()) != null; )
    {
        Console.WriteLine(line);
    }
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

12831 次

最近记录:

9 年 前