Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata