Filesystem I/O
I covered the basics of opening and
reading a file through the File
and
FileInfo
objects in Chapter 2.
In this section, I’ll focus on writing to a file
using the same objects.
To
begin with, File
has a Create(
)
method. This method takes a filename as a parameter and
returns a FileStream
, so the most basic creation
and writing to a file is fairly intuitive. Stream
and its subclasses implement a variety of Write( )
methods, including one that writes an array of bytes to the
Stream
. The following code snippet creates a file
named myfile.txt and writes the text
.NET & XML
to it:
byte [ ] buffer = new byte [ ] {46,78,69,84,32,38,32,88,77,76}; string filename = "myfile.txt"; FileStream stream; stream = File.Create(filename); stream.Write(buffer,0,buffer.Length);
Tip
That byte array is an awkward way to write a string to a
Stream
; ordinarily, you wouldn’t
hardcode an array of bytes like that. I’ll show you
a more typical way of encoding a string as a byte array in a moment.
If the file already exists, the previous code overwrites the files’s current contents. You may not want to do that in practice; you may prefer to append to the file if it already exists. You can handle this very easily in .NET in several different ways. This snippet shows one way, with the changes highlighted:
byte [ ] buffer = new byte [ ] {46,78,69,84,32,38,32,88,77,76}; string filename = "myfile.txt"; FileStream stream; if (File.Exists(filename)) { // it already exists, let's append to it stream ...
Get .NET & XML now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.