1

I am currently trying to develop a program which takes the output of an existing program (written in C) and uses it as input (in C#). The problem I am having is that the existing program prints data in redundant format but it dynamically changes. An example could be a random name generator and I need to make a program that logs all of the random names as they appear.

Could I just pipe this and the output will be grabbed as it comes? The C program is run from a CLI.

akf
  • 38,619
  • 8
  • 86
  • 96

2 Answers2

3

You could redirect the output streams from the Process object to get direct access to it. You make a call and it will invoke an event of your choice when output is received. One of my questions may provide some explanation on how to do this - C# Shell - IO redirection:

processObject.StartInfo.RedirectStandardOutput = true;
processObject.OutputDataReceived += new DataReceivedEventHandler(processObject_OutputDataReceived);
/* ... */
processObject.Start();
processObject.BeginOutputReadLine();

And then later:

public void processObject_OutputDataReceived(object sender, DataReceivedEventArgs e) {
    ProcessNewData(e.Data);
}

Note that this includes the trailing newline.

Or you can just pipe it and use Console.ReadLine to read it in. On the command line, you would execute:

cprogram | csharp_program

Unfortunately, you can't do this directly with the Process object - just use the method above. If you do choose to go this route, you can use:

string input = "";
int currentChar = 0;

while ( (currentChar = Console.Read()) > -1 ) {
    input += Convert.ToChar(currentChar);
}

Which will read from the input until EOF.

Community
  • 1
  • 1
Lucas Jones
  • 19,767
  • 8
  • 75
  • 88
  • Hmm I may have been slightly misleading in my description. The original program is written in C but is executed via CLI in Linux. Some of the existing libraries only exist on the Linux side of this machine as well so I may be trying in vain to get this to work in C# (but C# is so nice for GUI's!) –  Jul 02 '09 at 00:24
  • Oh, CLI! I read it as CLR. Oops. :-) You could get your program to work in Mono - most do without modification. – Lucas Jones Jul 02 '09 at 10:45
  • I was trying to find a version of Mono for RHELv5 but all I saw was "other lisnux" hahah guess its better than nothing. –  Jul 02 '09 at 17:47
  • Try the version for Fedora or standard Red Hat. These *might* be compatible. – Lucas Jones Jul 02 '09 at 18:25
0

If the C# program is also command-line based, running this command from the command-line will chain them together:

my_c_program.exe | my_csharp_program.exe

The C# program will receive the output of the C program, via its standard input stream (Console.Read, etc.)

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284