【问题标题】:Pass text file content to Console.ReadLine() instead of typing将文本文件内容传递给 Console.ReadLine() 而不是键入
【发布时间】:2021-05-09 06:50:38
【问题描述】:
Public static void main(args){
     String input = Console.ReadLine();
     Console.WriteLine(input);
}

代替使用键盘输入“input”变量的值,是否可以使用文件加载输入值?

我不想使用 'args' 来传递值。

例如:对于在线 C# 编辑器,我们将在 中输入输入值,这将自动发送到 Console.ReadLine() 方法。

编辑:这不是我的生产代码,我也无意用于工作。这只是为了了解在线 C# 编辑器如何使用

中提供的 STDIN 数据/值运行程序

【问题讨论】:

标签: c# visual-studio


【解决方案1】:

感谢@Marc Gravell 和@Olivier Rogier。

答案是使用管道。

myconsoleapp main.cs

Public static void main(args){
     String input = Console.ReadLine();
     Console.WriteLine(input);
}

input.txt 文件

Hello world

命令行

 myconsoleapp.exe < input.txt

输出

Hello world

参考: ss64.com/nt/syntax-redirection.html

How-to: Redirection
   command > filename        Redirect command output to a file

   command >> filename       APPEND into a file

   command < filename        Type a text file and pass the text to command

   commandA  |  commandB     Pipe the output from commandA into commandB

   commandA &  commandB      Run commandA and then run commandB
   commandA && commandB      Run commandA, if it succeeds then run commandB
   commandA || commandB      Run commandA, if it fails then run commandB

   commandA && commandB || commandC
                             If commandA succeeds run commandB, if commandA fails run commandC
                             ( Note that if commandB fails, that will also trigger running commandC )

【讨论】:

  • 请注意,这并不能回答所提出的问题,特别是“这只是为了了解在线 C# 编辑器将如何使用提供的 STDIN 数据/值运行程序” - 请将此用作在尝试提出意图非常明确的问题方面的学习经验。 “为现有程序使用文本文件”的目标与“编写能够使用文本区域进行输入的在线编辑器”的目标确实不同。
  • @JonSkeet 很抱歉造成混淆 :) 英语不是我的第一语言,我假设以下行“而不是使用键盘输入 'input' 变量的值,是否可以使用文件加载输入值?”已经足够好了,我只是以“在线C#编译器”为例帮助大家理解。会尽力让每个人都能理解。
  • 你引用的那句话很好 - 但是将在线 C# 编译器带入其中会使整个事情变得更加混乱。如果你坚持一个目标,那就简单多了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 2012-04-23
  • 2021-12-19
  • 1970-01-01
  • 2021-09-24
  • 2018-04-04
相关资源
最近更新 更多