Mt. San Jacinto College Computer Information Systems
Minimize header.

CSIS 111B: Fundamentals of Computer Programming: Lessons

Lesson 11

File I/O

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 a 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 at which time they will want to retrieve the document and its code is saved to a file on a storage system. As a programmer you will be expected to be able to write and read data to and from a 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 accessible by the user's device, and the DirectoryInfo class which 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.

Table of Contents
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 and directory where you are located, At the top, you should see the operating system version 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.

Image of a Microsoft Windows Command Prompt.
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.

Image showing the results of running the dir command in the Windows Command Prompt.

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 folder in the directory. Each entry includes a data 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 "cd documents" to change the directory to your Documents subfolder (assuming you are still in your user's directory.

Image shows the result of running the command cd documents.

Type "tree" and press enter. You should see a graphical representation of your directory struture scroll by.

Image shows the results of running the tree command. The directory structure shows branching lines to sub-folders.

You can press Ctrl+Z on your keyboard at any time to stop the scrolling.

Type "help" at the command prompt and you will see a listing of all the commands you can use with the command prompt.

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.

Type "systeminfo" and you will see your computer's system information.

Table of Contents
The System.IO Namespace
The System.IO Namespace contains types that allow reading and writing to files and data streams, and types that provide file and directory support.

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.

Table of Contents

StreamWriter

The StreamWriter class implements a TextWriter for writing characters to a stream in a particular encoding.

    using System;
    using System.IO;

    namespace StreamWriter1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Enter text to save:");
                string textInput = Console.ReadLine();

                using (StreamWriter writer = new StreamWriter("MyText.txt"))
                {

                    writer.WriteLine(textInput);
                }
            }
        }
    }
Table of Contents
StreamWriter Code Dissected
Image highlights the code portions which initialize the writer variable of StreamWriter type by assigning it a new instance of a StreamWriter object with the argument MyText.txt
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 StreamReader1
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (StreamReader sr = new StreamReader("TestFile.txt")) 
                {
                    string line;
                    // Read and display lines from the file until the end of 
                    // the file is reached.
                    while ((line = sr.ReadLine()) != null) 
                    {
                        Console.WriteLine(line);
                    }
                }
            }
        }
    }
Table of Contents
StreamReader Dissected
Image highlights the initialization of the sr variable of StreamReader type with a new instance of a StreamReader object with the argument of TestFile.txt passed to it.
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 # literal string operator which causes escape sequences to NOT be processed.

Table of Contents

The Scribes Oath

In this video Uncle Bob talks about the evolution of computer programmers as a profession and software craftmanship. Software craftmanship refers to why it is important for programmers to have a good set of programming ethics which adhere to proven programming principles.

Table of Contents

Summary

In this lesson you learned what basic file I/O management is, what the purpose of the IO library 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.