在c#中从同一个流中多次读取

时间:2009-05-19 10:42:09

标签: c# process

我想多次读取程序的输出。有些事情,如果我通过X我得到输出,我显示它,然后再次,如果我通过Y我得到输出,我显示它。没有重新启动过程。 尝试它我已经制作了一个c程序

#include<stdio.h>
int main()
{
    int i;
    int j;
while(scanf("%d", &i))
{
    for(j = 0; j<=i;j++)
    printf("%d\n",j);
}
return 0;
}

现在我正在用C#进行插入,当我在文本框中输入文本时,它会通过重定向standardinput(一个流写器)传递给程序并读取输出,我称之为标准输出(streamreader)。 ReadToEnd的()。

但它不适合我。因为它进入等待状态,直到流返回一些指示告诉结束已被读取。

我怎样才能实现这样的目标?

我尝试了异步读取,我调用了beginoutputread方法,但后来我不知道读取何时完成!一种方法是我可以在原始程序中添加一个标记,以指示当前输入的输出结束。我还有其他方法可以实现吗?

3 个答案:

答案 0 :(得分:6)

如果流支持搜索(CanSeek),您可以通过设置

来“回放”它
stream.Position = 0;

因此开始重新阅读。

答案 1 :(得分:2)

如果流不支持搜索,但流中的数据不是那么大,您可以读取和写入该流到MemoryStream,并根据需要多次读取MemoryStream。

答案 2 :(得分:0)

Quck and Dirty:这个可以解决一些小问题。尝试改进它,因为我要离开办公室:)

        ProcessStartInfo psi = new ProcessStartInfo(@"c:\temp\testC.exe");
        psi.CreateNoWindow = true;
        psi.RedirectStandardError = true;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.UseShellExecute = false;

        Process p = Process.Start(psi);
        string input = "";

        ConsoleColor fc = Console.ForegroundColor;

        StreamWriter sw = p.StandardInput;
        StreamReader sr = p.StandardOutput;

        char[] buffer = new char[1024];
        int l = 0;

        do
        {
            Console.Write("Enter input: ");
            input = Console.ReadLine();

            int i = Convert.ToInt32(input);

            sw.Write(i);
            sw.Write(sw.NewLine);

            Console.ForegroundColor = ConsoleColor.Yellow;

            Console.Write(">> ");

            l = sr.Read(buffer, 0, buffer.Length);

            for (int n = 0; n < l; n++)
                Console.Write(buffer[n] + " ");

            Console.WriteLine();

            Console.ForegroundColor = fc;
        } while (input != "10");

        Console.WriteLine("Excution Finished. Press Enter to close.");
        Console.ReadLine();
        p.Close();

PS: - 我在vs2008中创建了控制台exe并将其复制到名为testC.exe的c:\ temp文件夹中。

相关问题