문제

매개 변수로 콘솔 애플리케이션을 프로그래밍하는 방법을 알고 있습니다. 예 : 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
}

.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

다음은 다른 솔루션과 Peek ()에서 구성된 또 다른 대체 솔루션입니다.

peek ()가 없으면 "type t.txt | prog.exe"를 수행 할 때 앱이 Ctrl-C없이 돌아 오지 않을 것이라는 경험이있었습니다. 그러나 "prog.exe"또는 "echo hi | prog.exe"만 잘 작동했습니다.

이 코드는 파이프 입력 만 처리하기위한 것입니다.

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

Console.in은 표준 입력 스트림을 감싸는 Textreader에 대한 참조입니다. 많은 양의 데이터를 프로그램에 배관하면 그러한 방식으로 작업하는 것이 더 쉬울 수 있습니다.

제공된 예제에는 문제가 있습니다.

  while ((s = Console.ReadLine()) != null)

Piped 데이터없이 프로그램이 시작된 경우 입력을 기다리는 것입니다. 따라서 사용자는 종료 프로그램을 수동으로 눌러야합니다.

이것은 또한 효과가 있습니다

C : myapp.exe <input.txt

stdin에서 캡처 한 입력을 조작하기 위해 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);

    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top