Archive for April, 2008
Making C# IO Redirect
When i compare Java I/O and .NET steams, i find the streams little hard to work with. It was just little easier than the legendary stdio.h. It’s not because of overly exposure to java, but it’s with the classes being structured in .NET to work on I/O.
Recently i was trying to write a i/o re-director which writes into a file making use of FIleStream class in .NET. What i had to do is
1. Create FileStream
2. Make is a BufferedStream (Personal Choice even though i dont write any kind of huge data)
3. Associate the Stream to the console class out property.
Now the interesting part. Since the StreamWriter is in some way associated with BufferedStream, i had to do a close to ensure a flush. Where do i call the Close () ?
Stream or BufferedStream or Console.Out.Close() ?
OK i guess where ever we do a Close(), it works and i can continue with my standards i/o from console. But unfortunately i was not allowed to proceed further with my i/o. The Console.Out was closed for ever and i need to regain the Out property. So i had to take help from MSDN to look for any clue, which helped me at last.
ObjectDisposedException was unhandled, is the case when when we dont have the TextWrite available any more.
I felt the solution little awkward though (personal opinion).
Stream fs2 = new FileStream(“MyOwnDesktop\\Routine.txt”, FileMode.Append);
BufferedStream bfs2 = new BufferedStream(fs2);
StreamWriter sw2 = new StreamWriter(bfs2);
Console.SetOut(sw2);
Console.Out.WriteLine(“Getting Written to file”);
sw2.Close();
TextWriter regainTextWriter = Console.Out;
Console.SetOut(regainTextWriter);
Console.Out.WriteLine(“Getting printed in console again. Shhhhhhh”);
Additional Snippet of information:
If you are interested how the static TextWriter reference is initialized with StreamWriter, take a look at the source code (Console class constructor) directly here. Look for line numbers 113 to 115. The link shows MONO source code and the best way to lookup the latest code is to get the laterst source tarball.
This article does not try to compare .NET and Java FIle I/O processing by any chance but it could interest people to explore on few basic differences between the two.
2 comments April 28, 2008