I have C#/WPF application that calls into a third-party native dll (created by the Matlab compiler) to perform an intensive calculation, all within a single process. This dll dumps a bunch of debug info to the console, presumably by writing to stdout and/or stderr. This info is meaningless to users, but would assist greatly in debugging when things go wrong. If I set my application type to Console Application, I get a console window alongside the real application window and can see the debug output, but then the user sees it too. Is there any way for me to redirect or echo my own process's stdout/stderr to a logfile without needing to put a console window on the screen?
Things that don't work:
- Using
Console.SetOut()
/SetError()
. This only seems to affect writes that go through theConsole
object itself, which is obviously not what happens in native code. - Hooking the
Process.GetCurrentProcess().OutputDataReceived
event. This only works if the process was started with a flag indicating that it should redirect stdout, which is not something I can set for my own process after the fact (as far as I know). - Reading from
Process.GetCurrentProcess().StandardOutput
. Again, this requires the process to have been started with redirection enabled. - P/Invoking
SetStdHandle
. This allows me to redirect stdout/stderr from my own C# code to a file, but the native dll is unaffected.
Redirecting from the command line (MyApp.exe > logfile.txt 2>&1
) does work, so I'm sure the dll is writing to stdout and stderr, but all attempts to redirect the native half of things after launching the process have failed.