Skip to Content
.NET & XML
book

.NET & XML

by Niel M. Bornstein
November 2003
Intermediate to advanced
476 pages
14h 38m
English
O'Reilly Media, Inc.
Content preview from .NET & XML

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Applied XML Programming for Microsoft® .NET

Applied XML Programming for Microsoft® .NET

Dino Esposito
XML Hacks

XML Hacks

Michael Fitzgerald

Publisher Resources

ISBN: 0596003978Supplemental ContentErrata