Passing a stream object to a function where the stream can be the console or a file
I want to write a function that accepts a stream argument. Ideally I would like that argument to be the console (if I want the output to go to the screen), or a file (if I want to save the out开发者_运维知识库put).
Something like this:
void myFunc(<some stream object> strm)
{
strm.Write("something");
}
How do I declare and call the function to get the behavior I am looking for?
Instead of Stream
, consider using TextWriter
. That way, you can use a StreamWriter
for writing to files, and Console.Out
for writing to the console:
static void DoStuff(TextWriter output)
{
output.WriteLine("doing stuff");
}
static void Main()
{
DoStuff(Console.Out);
using( var sw = new StreamWriter("file.txt") )
{
DoStuff(sw);
}
}
I entirely agree with Mark's answer: a TextWriter
is almost certainly the way to go.
However, if you absolutely have to cope with an arbitrary stream, you can use Console.OpenStandardOutput()
to get a stream to the console. I would strongly advise you not to use this unless you really have to though.
精彩评论