by kirupa |
29 March 2007Files are more than the documents you
create in a word processor, images you design, source files
you write, etc. They are not restricted to things you create
or read, for almost everything you do on your computer
directly or indirectly involves manipulating files. To view
this HTML page, your browser received a file filled with
HTML text. Your operating system uses a huge file to cache
often-used pieces of data. When you compile your
applications, the end result is a series of files that you
as a human cannot read with a standard text editor.
More often than not, it is programs that are the intended
readers for many files, and many programs write their own
files in the background for various reasons. In this tutorial, you will
learn how to write programs that read text from files and write text back to
files using the StreamReader and StreamWriter Classes.
In most operating systems, a file is associated with a
particular application designated to read it. When reading a
file, an application takes the collection of data and loads
it into memory for further processing. When an application
is said to read a file, the file's contents may loaded
sequentially in fixed chunks, or the entire file may be
loaded into memory and read in bulk. These details aren't
too important for us, because the .NET classes we use take
care of a lot of these details for us, but it is good to
have a brief idea of what is possible beyond what this
tutorial will cover.
To read a file, you need to know only the path of a
file. Once you have the path to a file, you load the file
into memory until there is nothing more to load. To
facilitate this, you have the System.IO namespace's
StreamReader class that provides a lot of the functionality
needed to read a file for you.
First, find a text file. If you cannot find a text file,
copy and paste the following
Dave Barry quote into Notepad
and save it into an easily accessible location:
For this example, I saved the above quote on my Desktop
and called it quote.txt. With your text file set, the
following code sample shows you how to read a file from your
drive:
- StreamReader
reader
= new
StreamReader("C:\\Users\\Kirupa\\Desktop\\quote.txt");
-
- string
readerLine
=
reader.ReadLine();
-
- while
(readerLine
!=
null)
- {
- Console.WriteLine(readerLine);
- readerLine
=
reader.ReadLine();
- }
When I run through the above code, I see each line from
my quote.txt file displayed in the console:
[ the Console output ]
In the
next page, I will go through the code line-by-line and
provide any interesting details and alternative approaches.
Onwards to the
next page!
|