加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何从命令行参数中读取文件,否则标准? (模拟Python的文

发布时间:2020-12-15 04:04:57 所属栏目:百科 来源:网络整理
导读:我希望我的应用程序从命令行参数或标准输入指定的文件中读取,因此用户可以使用它myprogram.exe data.txt或otherprogram.exe | myprogram.exe.我怎么能在C#中做到这一点? 在Python中,我会写 import fileinputfor line in fileinput.input(): process(line) T
我希望我的应用程序从命令行参数或标准输入指定的文件中读取,因此用户可以使用它myprogram.exe data.txt或otherprogram.exe | myprogram.exe.我怎么能在C#中做到这一点?

在Python中,我会写

import fileinput
for line in fileinput.input():
    process(line)

This iterates over the lines of all files listed in sys.argv[1:],defaulting to sys.stdin if the list is empty. If a filename is ‘-‘,it is also replaced by sys.stdin.

Perl的<>和Ruby的ARGF同样有用.

解决方法

stdin通过Console.In作为TextReader暴露给您.只需为您的输入声明一个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);
    }
}

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

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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读