7

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


在 Python 中,我会写

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

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

Perl<>和 Ruby ARGF也同样有用。

4

4 回答 4

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

否则,如果重构以使用这个新变量过于昂贵,您始终可以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);
    }
}
于 2012-10-07T18:37:22.697 回答
3

实际上,这非常容易。

在 C# 代码编辑器中,您可以执行以下操作:

public static void Main(string[] args) {
    //And then you open up a file. 
    using(Streamreader sr = new Streamreader(args[0])) {
            String line = sr.ReadToEnd();
            Console.WriteLine(line);
    }
}

另一个好主意是遍历 ac# 集合中的项目 args,以便您可以将多个文件作为输入。例:main.exe file1.txt file2.txt file3.txt等等。

您可以通过使用特殊的 for 循环修改上述代码来做到这一点,如下所示:

foreach(string s in args) {
    using( Streamreader sr = new Streamreader(s) ) {
        String line = sr.ReadToEnd();
        Console.WriteLine(line);
    }
}

祝你好运!

于 2012-10-07T18:06:06.720 回答
0

采用

 static void Main(string[] args)

然后在 for 循环中使用 args.length 遍历每个输入。

使用示例:http: //www.dotnetperls.com/main

于 2012-10-07T18:07:34.800 回答
-1

试试这个:

public void Main(string[] args)
        {
            if (args.Count() > 0)
            {

                byte[] byteArray = Encoding.UTF8.GetBytes(args[0]);
                MemoryStream stream = new MemoryStream(byteArray);

                StreamReader sr = new StreamReader(stream);
                String line = sr.ReadToEnd();
                Console.WriteLine(line);
            }
            Console.ReadLine();
        }

args[0] 是一个字符串,在传递给 StreamReader 构造函数之前必须将其转换为流。

于 2017-01-25T04:17:12.650 回答