我知道如何编写带参数的控制台应用程序,例如:myProgram.exe param1 param2。
我的问题是,如何使我的程序与 | 一起使用,例如:echo "word" | myProgram.exe?
如果要读取用户的输入,你需要使用Console.Read()
和 Console.ReadLine()
。管道可以透明地替换用户输入。虽然同时使用两者也是可能的,但并不容易。
编辑:
一个简单的类似于cat
的程序:
class Program
{
static void Main(string[] args)
{
string s;
while ((s = Console.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
当运行时,如预期的那样,输出结果为:
C:\...\ConsoleApplication1\bin\Debug>echo "Foo bar baz" | ConsoleApplication1.exe "Foo bar baz"
C:\...\ConsoleApplication1\bin\Debug>
public static void Main(String[] args)
{
String pipedText = "";
bool isKeyAvailable;
try
{
isKeyAvailable = System.Console.KeyAvailable;
}
catch (InvalidOperationException expected)
{
pipedText = System.Console.In.ReadToEnd();
}
//do something with pipedText or the args
}
System.Console.WriteLine(System.Console.IsInputRedirected.ToString());
。 - barlop在 .NET 4.5 中,它是
if (Console.IsInputRedirected)
{
using(stream s = Console.OpenStandardInput())
{
...
这是做法:
static void Main(string[] args)
{
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192))); // This will allow input >256 chars
while (Console.In.Peek() != -1)
{
string input = Console.In.ReadLine();
Console.WriteLine("Data read was " + input);
}
}
这种方法有两种用法。从标准输入读取:
C:\test>myProgram.exe
hello
Data read was hello
或从管道输入读取:
C:\test>echo hello | myProgram.exe
Data read was hello
static int Main(string[] args)
{
// if nothing is being piped in, then exit
if (!IsPipedInput())
return 0;
while (Console.In.Peek() != -1)
{
string input = Console.In.ReadLine();
Console.WriteLine(input);
}
return 0;
}
private static bool IsPipedInput()
{
try
{
bool isKey = Console.KeyAvailable;
return false;
}
catch
{
return true;
}
}
System.Console.WriteLine(System.Console.IsInputRedirected.ToString());
,可以检测控制台输入流是否被重定向。 - barlop这也适用于
c:\MyApp.exe < input.txt
我不得不使用StringBuilder来处理从标准输入中捕获的输入:
public static void Main()
{
List<string> salesLines = new List<string>();
Console.InputEncoding = Encoding.UTF8;
using (StreamReader reader = new StreamReader(Console.OpenStandardInput(), Console.InputEncoding))
{
string stdin;
do
{
StringBuilder stdinBuilder = new StringBuilder();
stdin = reader.ReadLine();
stdinBuilder.Append(stdin);
var lineIn = stdin;
if (stdinBuilder.ToString().Trim() != "")
{
salesLines.Add(stdinBuilder.ToString().Trim());
}
} while (stdin != null);
}
}
Console.In是一个围绕标准输入流包装的TextReader引用。当将大量数据传输到程序中时,使用这种方式可能更容易处理。
提供的示例存在问题。
while ((s = Console.ReadLine()) != null)
如果程序在没有管道数据的情况下启动,将会一直等待输入。因此用户必须手动按任意键退出程序。
Console.ReadLine
的文档说明如果没有更多的行可读,则返回 null:https://msdn.microsoft.com/de-de/library/system.console.readline(v=vs.110).aspx - Robert S.