Objectives
By the end of this lesson you will be able to:
- Understand basic file I/O management
- Understand the purpose of the IO library
- How to use a command prompt to view file and directory information
- Create a program that reads a stream of characters from a text file using the StreamReader class
- Create a program that writes a stream of characters to a text file using the StreamWriter class
Introduction
If you think about the functionality of a computer program like Microsoft Word, its main purpose is to allow the user to create a printable document. However, it is also important that the user be able to save the document for later editing. They will want to retrieve the document's contents from a saved a file stored on some storage system. As a programmer you will be expected to be able to write and read data to and from a digitally stored file; that is what this lesson is all about.
The Microsoft .Net library offers several helpful classes including the StreamWriter class and the StreamReader class which make it easier for developers to write to and read from text files stored on a storage system. The DirectoryInfo class is also helpful in that it can be used for gathering file and folder information on the user's device.
In order to re-familiarize yourself with how to do file management using a command prompt we'll start with a little refresher. First and foremost you need to understand that the zeros and ones that make up the data file are indexed by the file system and organized into a Directory Tree for easy reference. The directory tree starts at the "root" of the storage device, "C" in the examples used below, and it contains one or more subdirectories and/or files. The subdirectories form the branches of the tree and the files are often referred to as the leaves. Subdirectories contain zero or more subdirectories and/or files and those subdirectories contain more subdirectories and/or files and so on and so forth.
In order for the computer programs we create to successfully read and write the contents of a file, they will first need to be able to locate a file's correct location in a given storage device's directory structure.
Visual Studio Solution for Tutorial 11
Using the Command Prompt For File IO
Open a command prompt and notice what the prompt is telling you. It is telling you the drive (storage device) and directory where you are "located" within the storage device's file system. At the top, you should see the version of the operating system you are running on your device; underneath is what is referred to as the "prompt", most likely c:\Users\YourUserName
, followed by a flashing cursor as shown in figure 1.
Figure 1: The Windows Command Prompt
Type dir
and press enter. You should now see a list of the directories (folders) contained in your user folder.
On this screen we can see the volume name of the drive (Windows) and its serial number along with a list of all the files and folders in the directory. Each entry includes a date and time stamp, an indication if it is a directory or not, if its a file its size is shown, followed by the name of the item. These are all properties of the DirectoryInfo class in the .NET framework (more on this class later).
Type help
at the command prompt and you will see a listing of all the commands you can use with the command prompt.
If you type Help
followed by a command name, you will get detailed help for that specific command; e.g. help cd.
Type cd documents
to change the directory to your Documents subfolder (assuming you are still in your user's directory.
Type "tree" and press enter. You should see a graphical representation of your directory structure scroll by.
You can press Ctrl+C
on your keyboard at any time to stop the scrolling.
You can type "cls
" at the prompt to clear the screen.
You can press the up arrow on your keyboard to retrieve commands from your history cache.
You can also type ../ and press Enter to move up a level in the directory tree.
Type the name of a folder in the directory you are viewing and the command window opens the folder and displays its contents.
Type systeminfo
and you will see your computer's system information.
⇑ Table of Contents
The System.IO Namespace
As you can see by its description, the System.IO namespace contains classes which help with reading and writing files and dealing with file and folder information. This beginning of this tutorial will help you to learn how to implement the StreamWriter and StreamReader classes for constructing file I/O in your programs. The end of this tutorial will briefly cover the DirectoryInfo class for obtaining file and folder info.
StreamWriter
The StreamWriter class implements a TextWriter for writing characters to a stream in a particular encoding.
using System;
using System.IO;
namespace StreamWriterExample
{
class Program
{
static void Main(string[] args)
{
//Prompt User to enter text to be saved
Console.WriteLine("Enter text to save:");
//Assign user text to textInput
var textInput = Console.ReadLine();
using var writer = new StreamWriter(@"e:\MyText.txt");
writer.WriteLine(textInput);
}
}
}
StreamWriter Code Dissected
⇑ Table of Contents
The Using Statement
In the previous code example you saw use of a new control structure, the using
statement. This control structure obtains one or more resources, executes a statement, and then disposes of the resource. In the case of the previous code example, the keyword using
invokes a new instance of a StreamWriter
object using the StreamWriter
constructor which accepts a string value as the name of the new text file and binds it to the name/identifier writer
. The new writer
object uses the WriteLine
method to convert the users input into an ascii encoded text file with a file name of MyText
.
⇑ Table of Contents
StreamReader
The StreamReader class implements a TextReader that reads characters from a byte stream in a particular encoding.
Using StreamReader To View A Text File
using System;
using System.IO;
namespace StreamReaderExample
{
class Program
{
static void Main(string[] args)
{
//Declare a variable to hold the read text
string line;
//Declare 'sr' of type StreamReader to use MyText.txt file for storage
using var sr = new StreamReader("MyText.txt");
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
StreamReader Dissected
Click or tap to view larger image.
⇑ Table of Contents
Using The DirectoryInfo Class to Read & Write Directories
C#
Here is how the code in our Program.cs
file will look. Place the code inside the Main() method and run it. Note: You will need the using System.IO; declaration in order for your code to gain access to the StreamReader and StreamWriter classes.
using System;
using System.IO;
namespace StreamReadWriter
{
class Program
{
static void Main(string[] args)
{
// Get the directories currently on the C drive.
DirectoryInfo[] cDirs = new DirectoryInfo(@"c:\").GetDirectories();
// Write each directory name to a file.
using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
{
foreach (DirectoryInfo dir in cDirs)
{
sw.WriteLine(dir.Name);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("CDriveDirs.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
}
The DirectoryInfo class exposes instance methods for creating, moving, and enumerating through directories and subdirectories.
Note: in the example above the @ character is the C # verbatim operator which causes escape sequences to NOT be processed.
⇑ Table of Contents
Summary
In this lesson you learned what basic file I/O management is, what the purpose of the System.IO namespace is, how to use a command prompt to view file and directory information, how to create a program that reads a stream of characters from a text file using the StreamReader class, how to create a program that writes a stream of characters to a text file using the StreamWriter class.