Reputation: 3127
My application App
is using other my application SubApp
.
When App
needs SubApp
it is creating process with SubApp
, putting data to SubApp
stdin
and reading from SubApp
stdout
.
The problem is that SubApp
is using some library which sometimes writes to stdout
.
Fragment of SubApp
code:
OutsideLibrary.DoSomeInitialization(); // <-- this sometimes writes to stdout
Stream input = Console.OpenStandardInput();
Stream output = Console.OpenStandardOutput();
data = (dataFormat)formatter.Deserialize(input);
//do some job
formatter.Serialize(output, result);
Is there any way to prevent code I don't have from writing to stdout?
Upvotes: 1
Views: 3985
Reputation: 1437
Assuming you want to disable third party component output and you have control over the rest of SubApp code you can do following trick: Redirect standard output to null at application bootstrap. When you need to write something to stdout temporary set standard output back to normal, write and set to null again.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace stdio
{
class Program
{
static void Main(string[] args)
{
Console.SetOut(System.IO.TextWriter.Null);
Console.WriteLine("This will go to > null");
WriteOutput("This is written to standard output");
Console.WriteLine("This will also go to > null");
Console.ReadKey();
}
static void WriteOutput(String someString)
{
Console.SetOut(Console.Out);
Stream output = Console.OpenStandardOutput();
StreamWriter sw = new StreamWriter(output);
sw.Write(someString);
sw.Flush();
sw.Close();
output.Close();
Console.SetOut(System.IO.TextWriter.Null);
}
}
}
Upvotes: 2
Reputation: 11324
I've tried this:
StreamWriter sw = new StreamWriter(@"c:\nul");
Console.SetOut(sw);
Console.WriteLine("hello!");
But it throws an exception in new StreamWriter().
The following might work (call it before your external module becomes active):
StreamWriter sw = new StreamWriter(Stream.Null);
Console.SetOut(sw);
A workaround would be to open a real text file and delete it.
Upvotes: 1