I did the bookend post to this a couple weeks back (i.e. how to read from a file) so its time I wrapped this topic up. Where the writing function was StreamWriter, we instead use StreamReader to extract the text from the document. Pretty logical right? In the example below, I’m pulling a block of code out of a text file named code.txt so I can append it to the header of a document I’m getting ready to generate. So once I’ve told the StringReader which file we are working with, we need to loop through that file line by line to suck them into the reader. In this case I’m storing that output in a string variable I’ve called sCode. Finally, once we’ve captured all the file’s contents we close the StreamReader to release our resources. Don’t forget to make your reference to System.IO or Visual Studio is going to yell at you. Now I can take that sCode value and do with it what I will. Just like the StreamWriter class, we can accomplish a big task in a few lines of code, leaving more time to goof off looking for iPhone apps.
↧