15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

796 ❘ ChaPTer 29 mAnipulAtinG files And the reGistry<br />

Finally, you can read a given number of characters into an array, with an offset:<br />

// to read 100 characters in.<br />

int nChars = 100;<br />

char [] charArray = new char[nChars];<br />

int nCharsRead = sr.Read(charArray, 0, nChars);<br />

nCharsRead will be less than nChars if you have requested to read more characters than are left in the file.<br />

The streamWriter Class<br />

This works in the same way as the StreamReader, except that you can use StreamWriter only to write to a<br />

file (or to another stream). Possibilities for constructing a StreamWriter include this:<br />

StreamWriter sw = new StreamWriter(@"C:\My Documents\ReadMe.txt");<br />

This will use UTF8 encoding, which is regarded by .<strong>NET</strong> as the default encoding method. If you want, you<br />

can specify alternative encoding:<br />

StreamWriter sw = new StreamWriter(@"C:\My Documents\ReadMe.txt", true,<br />

Encoding.ASCII);<br />

In this constructor, the second parameter is a Boolean that indicates whether the file should be opened for<br />

appending. There is, oddly, no constructor that takes only a filename <strong>and</strong> an encoding class.<br />

Of course, you may want to hook up StreamWriter to a file stream to give you more control over the<br />

options for opening the file:<br />

FileStream fs = new FileStream(@"C:\My Documents\ReadMe.txt",<br />

FileMode.CreateNew, FileAccess.Write, FileShare.Read);<br />

StreamWriter sw = new StreamWriter(fs);<br />

FileStream does not implement any methods that return a StreamWriter class.<br />

Alternatively, if you want to create a new file <strong>and</strong> start writing data to it, you will find this sequence useful:<br />

FileInfo myFile = new FileInfo(@"C:\My Documents\NewFile.txt");<br />

StreamWriter sw = myFile.CreateText();<br />

Just as with all other stream classes, it is important to close a StreamWriter class when you are finished<br />

with it:<br />

sw.Close();<br />

Writing to the stream is done using any of 17 overloads of StreamWriter.Write(). The simplest writes out<br />

a string:<br />

string nextLine = "Groovy Line";<br />

sw.Write(nextLine);<br />

It is also possible to write out a single character:<br />

char nextChar = 'a';<br />

sw.Write(nextChar);<br />

And an array of characters:<br />

char [] charArray = new char[100];<br />

// initialize these characters<br />

sw.Write(charArray);<br />

It is even possible to write out a portion of an array of characters:<br />

int nCharsToWrite = 50;<br />

int startAtLocation = 25;<br />

char [] charArray = new char[100];<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!