How to capture binary process output in C # /. NET

I want to run an external application and write its output. It is quite easy to use Diagnostics.Processit OutputStream.

However, the process that I created the binary data that I need to write as Stream, rather than as textStreamWriter

Is there a way to get the underlying raw binary stream?

I am currently hacking it by running a batch file that looks like this:

myapplication | socat stdin tcp-connect:localhost:12345

And in my code, I create and listen on a TCP socket. while this hack works, it is a little ugly, and I prefer to use an external process directly.

(One thing I cannot do is to use local files, since real-time data is inherently in nature)

+3
source share
3 answers
+3
source

You can use a named pipe that is similar, but more in-depth, than the functionality of OutputStream for Process (which is basically a listener for StandardOutput). Named pipes are accessible using Streams, without any assumption that the content is a Unicode character. They also do not bind network ports if you do not want to connect to the pipe remotely (which is also possible).

+1
source

stdout

ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "yourProcess";
info.Arguments = "blah";
info.StandardOutputEncoding = System.Text.Encoding.GetEncoding("latin1");//important part
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
Process p = Process.Start(info);
FileStream fs = new FileStream("outputfile.bin", FileMode.Create);

while((val = p.StandardOutput.Read())!= -1){
    fs.WriteByte((byte)val);
}

p.WaitForExit();
fs.Close();
+1

Source: https://habr.com/ru/post/1780070/


All Articles