Home Search Contact us About us
Title Reading, Writing and Appending to simple text files in C#.
Summary Three short code samples to perform the most basic of text operations. Reading from a file, writing to a new file and appending to an existing file.
Contributor John McTainsh
Published 12-Jun-2001
Last updated 12-Jun-2001
Page rating   60% for 2 votes Useless Brilliant

Description

Reading to and writing from a text file used to be all the rage in the days when databases were big confusing things. Nowadays database grow on trees and parsing the data in a text file is harder by comparison to extracting a row form a database. However, text files are simple to implement and a lot easier to debug than missing drivers and database connection. For this reason we will look at reading, writing and appending to a text file. The example will create a simple log file with date and entry..

Includes

To use file I/O objects we need t include the following namespaces.

    using System.IO;

Writing to a file

The following code creates a file at the given path. If the file already exists then it is cleared (truncated to 0 length). Two lines of text are then written t the file before it is closed. If an error occurs it is handles by the catch statement which displays the error message and file name.

Note the @ symbol in front of the file name string. This means the escape characters are to be treated a normal characters. Without the @ the string would have to be written as "C:\\CS\\TryFileIO\\SomeWrite.txt".

    string sOutFileName = @"C:\CS\TryFileIO\SomeWrite.txt";
    try 
    {
        StreamWriter stTextOut = File.CreateText(sOutFileName );
        stTextOut.WriteLine( "Marry had a little lamb." );
        stTextOut.WriteLine( "This is line 2!" );
        stTextOut.Close();
    }
    catch( Exception ex )
    {
        Console.Out.WriteLine( "Error: {0} writing to created file {1} ", ex.Message, sOutFileName );       
    }

Appending to a file

Appending is simular to writing except, as you would expect the file is not truncated. Here the sLogNote is appended to the end of the file. This is a good example of a log file where entries are appended to the end of the file against the current date and time. Here the text is read from the file line by line until no more data remains.

    string sOutFileName = "SomeWrite.txt";
    string sLogNote = "<The Log note goes here>";
    try 
    {
        StreamWriter stTextOut = File.AppendText(sOutFileName );
        stTextOut.WriteLine( "* {0} - {1}", DateTime.Now, sLogNote );
        stTextOut.Close();
    }
    catch( Exception ex )
    {
        Console.Out.WriteLine( "Error: {0} Writing to log file {1} ", ex.Message, sOutFileName );       
    }

Reading from the file

To be really useful the data must be read back from the file. To do this a StreamReader is created on the input file. Each call to the ReadLine command will return the next line in the string. If the return is null then there is no more data in the file. Note, if a line is empty and empty string "" is returned, which is not the same as a null.

    string sInFileName = "SomeWrite.txt";
    try 
    {
        StreamReader stTextIn = File.OpenText( sInFileName );
        do
        {           
            string sIn = stTextIn.ReadLine();
            if( sIn == null )
                break;
            else
                Console.Out.WriteLine( sIn );
        } while( true ); 
        
    }
    catch( Exception ex )
    {
        Console.Out.WriteLine( "Error: {0} reading from {1} ", ex.Message, sInFileName );               
    }
Comments Date
Home Search Contact us About us