O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.8. Create, Write to, and Read from a File

Problem

You need to create a file—possibly for logging information to or storing temporary information—and then write information to it. You also need to be able to read the information that you wrote to this file.

Solution

To create, write to, and read from a log file, we will use the FileStream and its reader and writer classes. For example, we will create methods to allow construction, reading to, and writing from a log file. To create a log file, you can use the following code:

public FileStream CreateLogFile(string logFileName)
{
    FileStream fileStream = new FileStream(logFileName, 
                                   FileMode.Create, 
                                   FileAccess.ReadWrite, 
                                   FileShare.None);
    return (fileStream);
}

To write text to this file, you can create a StreamWriter object wrapper around the previously created FileStream object (fileStream). You can then use the WriteLine method of the StreamWriter object. The following code writes three lines to the file: a string, followed by an integer, followed by a second string:

public void WriteToLog(FileStream fileStream, string data)
{
    // make sure we can write to this stream
    if(!fileStream.CanWrite)
    {
        // close it and reopen for append
        string fileName = fileStream.Name;
        fileStream.Close( );
        fileStream = new FileStream(fileName,FileMode.Append);
    }
    StreamWriter streamWriter = new StreamWriter(fileStream);
    streamWriter.WriteLine(data);
    streamWriter.Close( ); 
}

Now that the file has been created and data has been written to it, you can read ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required