Home  |  FAQ  |  About  |  Contact  |  View Source   
 
SEARCH:
 
BROWSE:
    My Hood
Edit My Info
View Events
Read Tutorials
Training Modules
View Presentations
Download Tools
Scan News
Get Jobs
Message Forums
School Forums
Member Directory
   
CONTRIBUTE:
    Sign me up!
Post an Event
Submit Tutorials
Upload Tools
Link News
Post Jobs
   
   
Home >  Tutorials >  General ASP.NET >  Reading and Writing Files in C# Part 1
Add to MyHood
Reading and Writing Files in C# Part 1   [ printer friendly ]
Stats
  Rating: 4 out of 5 by 16 users
  Submitted: 04/11/02
David Citron ()

 
With any programming language there is always a need to read and write to files. In C#, this is done quite easily compared to many other programming languages.

Like other languages, C# utilizes a Stream class, which gives basic functionality when working with streams (any situation where you need to read and write data to some endpoint). The class FileStream, which is actually derived from the Stream class, adds to Stream the functionaly needed to read and write to files.

Now, let's get started!

The first thing you need to do is add the correct library at the top:


using System.IO;

This provides us with the functionality we will need for this tutorial.

Now, create an instance of FileStream:


FileStream file = new FileStream("path.txt", FileMode, FileAccess);

There are several overloads for this constructor, but this is the easiest to use for this tutorial.

FileMode specifies what the FileStream should do with the file to begin with. The options are: Append, Create, CreateNew, Open, OpenOrCreate, or Truncate, and can be accessed by FileMode.option.

FileAccess specifies the file priveledges. The options are: Read, ReadWrite, or Write, and can be accesed by FileAccess.option.


Writing to a file:

To write to a file we will need to use class StreamWriter, which is derived from the TextWriter class.


StreamWriter sw = new StreamWriter(file);

The constructor for StreamWriter also has several overloads. The one showed here takes an instance of FileStream, instantiated above (file).

With StreamWriter, you have two options for writing to a file: Write, or WriteLine. The Write method has 21 overloads, and the WriteLine method has 18, so you should have no problem finding the correct functionality to suit your programming needs.

Here is a simple example:


sw.Write("Hello file system world!");

Now don't forget to close the stream when you are done!


sw.Close();


Reading from a file:

To read from a file we will need to use class StreamReader. Similar to StreamWriter, StreamReader is derived from the TextReader class.


StreamReader sr = new StreamReader(file);

Just like StreamWriter there are several posibilities for constructor overloads. This one takes an instance of FileStream.

With StreamReader, there are four options for reading from a file: Read, ReadBlock, ReadLine, or ReadToEnd. Each one of these functions has several overloads. For the purposes of this example, I will use ReadToEnd, which just like the title implies, reads the entire file.


string s = sr.ReadToEnd();

Again, don't forget to close the stream!


sr.Close();

And when you are all done with the file, make sure to close that too.


file.Close();


Thats it! Thats all there is to it! Pretty simple if you ask me.

For those of you who learn better by visually looking at code samples, here is the entire thing one more time:


// *** Write to file ***

// Specify file, instructions, and privelegdes
FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);
            
// Create a new stream to write to the file
StreamWriter sw = new StreamWriter(file);

// Write a string to the file
sw.Write("Hello file system world!");

// Close StreamWriter
sw.Close();

// Close file
file.Close();


// *** Read from file ***

// Specify file, instructions, and privelegdes
file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Read);

// Create a new stream to read from a file
StreamReader sr = new StreamReader(file);

// Read contents of file into a string
string s = sr.ReadToEnd();

// Close StreamReader
sr.Close();

// Close file
file.Close();

This is by no means the only way to read and write to files. FileStream, StreamWriter, and StreamReader each provide many more advanced features.

In my next tutorial I will discuss more advanced file features, as well as show you how to use file dialogs in C#!

Good Luck!

Return to Browsing Tutorials

Email this Tutorial to a Friend

Rate this Content:  
low quality  1 2 3 4 5  high quality

Reader's Comments Post a Comment
 
not a bad tutorial. short and simple, and pretty easy to read, and to figure out what is going on and how to use the file read/write functions using C#. you may have wanted to create a simple app, say a simple parser, that will take a file, open it, read the contents of the file, either line by line, or the whole thing, and then printed what was in the file to the screen. but over a good tutorial.
-- J J, April 13, 2002
 
Pretty good, but ya, as Justin said, you should've included a sample actual code snipplet of sorts using those functions, otherwise very nice!
-- Larry Mak, April 13, 2002
 
Actually, thats what the very last snipet of code is: it puts everything together in one short example.
-- David Citron, April 13, 2002
 
This is useful as I/O is always one of those things you have to learn when you move ot a new platform; this saves me the trouble.
-- Simon Parsons, April 13, 2002
 
well no david...you are just basically throwing all the functions you used into one block of code instead of breaking it up like you had throughout the tutorial...a simple app like i described of a simple parser that reads in a file and prints out what is in the file, and maybe even creates a file would be helpful.
-- J J, April 13, 2002
 
good job
-- john jenty, April 13, 2002
 
Justin - I see what you are saying. I will include something like that in part 2 of this tutorial.
-- David Citron, April 13, 2002
 
Good, simple tutorial, though I would agree with some of the previous comments that code examples might be useful. Since this is pretty basic file I/O stuff, anyone who'd benefit from reading this would probably also like to see some examples.
-- Bassam Islam, April 14, 2002
 
David, as with your other tutorial, I wish you would have gone a bit further. This tutorial would be good for someone with almost no knowledge, but that's not the bulk of your audience. Not bad for what it is though.
-- parker thompson, April 16, 2002
 
Good Tutorial
-- Kirk Boone, April 29, 2002
 
nice basic tutorial ... good read for beginners!
-- Edward Kim, May 29, 2002
 
To the point. Congrats!
-- Radu Grama, July 10, 2002
 
nice tutorial
-- Kyoungjin Park, November 05, 2002
 
nicely done. Thanks.
-- to raptor, May 03, 2003
 
nice and simple. thanks
-- robert sorita, June 07, 2003
 
What changes would be required to read multiple files from a directory and append each to the other in a single file?
-- growlin stan, August 19, 2003
 
Very neat and simple to understand tutorial. Since I know C very well, I was looking for a quick tutorial to learn basic file io in C#. This tutorial gave me exectly what I was looking for! Well Done!
-Narendra Bhagwat.
-- Narendra Bhagwat, September 03, 2003
 
Copyright © 2001 DevHood® All Rights Reserved