我知道如何使用参数编程控制台应用程序,例如:myProgram.exe param1 param2.
我的问题是,如何使我的程序与|,例如:echo"word"| myProgram.exe?
Mat*_*ley 44
您需要使用Console.Read()并且Console.ReadLine()好像您正在阅读用户输入.管道透明地替换用户输入.你不能轻易地使用它们(虽然我确信它很可能......).
编辑:
一个简单的cat风格程序:
class Program
{
static void Main(string[] args)
{
string s;
while ((s = Console.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当运行时,如预期的那样,输出:
C:\...\ConsoleApplication1\bin\Debug>echo "Foo bar baz" | ConsoleApplication1.exe "Foo bar baz" C:\...\ConsoleApplication1\bin\Debug>
Cod*_*ler 15
下面将不会暂停输入的应用程序和数据时工作或没有管道.有点黑客; 并且由于错误捕获,当进行了大量的管道调用时性能可能会很差但很容易.
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
}
Run Code Online (Sandbox Code Playgroud)
gor*_*rdy 11
在.NET 4.5中它是
if (Console.IsInputRedirected)
{
using(stream s = Console.OpenStandardInput())
{
...
Run Code Online (Sandbox Code Playgroud)
这是这样做的方法:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这允许两种使用方法.从标准输入读取:
C:\test>myProgram.exe
hello
Data read was hello
Run Code Online (Sandbox Code Playgroud)
或从管道输入读取:
C:\test>echo hello | myProgram.exe
Data read was hello
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31753 次 |
| 最近记录: |