Monday, January 9, 2012

A Code Snap About File I/O in C#

This is tend to be a reminder of mind. It was gathered from many of my practice. Therefore some of them may look like odd or not corresponding. Such as MessageBox and Console objects are not suppose to appear in the same program, but they does not affect the whole things. I don't want to revise that parts since it is not important on this topic.

try

{

    // Either create an instance of StreamWriter or TextWriter

    using (TextWriter tr = new StreamWriter("text.txt"))

    using (StreamWriter sw = new StreamWriter("text.txt"))

    {

        // Add some text to the file.

        sw.Write("The date is: ");

        sw.WriteLine(DateTime.Now);

    }

}

catch (System.IO.FileNotFoundException ex)

{

    MessageBox.Show("Sorry, the file does not exist! {0}", ex.Message);

}

catch (System.UnauthorizedAccessException ex)

{

    MessageBox.Show("Sorry, you lack sufficient privileges. {0}", ex.Message);

}

catch (Exception ex)

{

    MessageBox.Show(ex.Message);

}

 

try

{

    // Either create an instance of StreamReader or TextReader

    using (TextReader tr = new StreamReader("text.txt"))

    using (StreamReader sr = new StreamReader("text.txt"))

    {

        // The using statement also closes the StreamReader.

        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);

        }

 

        // How to use Read and Peek.

        // Peek and Read return -1 if no more characters are available.

        // If the stream does not support seek then Peek return -1 too.

        while (sr.Peek() >= 0)

        {

            Console.Write((char)sr.Read());

        }

 

        // How to use ReadToEnd.

        displayTextBox.Text = tr.ReadToEnd();

 

        Console.ReadKey();

    }

}

catch (System.IO.FileNotFoundException ex)

{

    MessageBox.Show("Sorry, the file does not exist! {0}", ex.Message);

}

catch (System.UnauthorizedAccessException ex)

{

    MessageBox.Show("Sorry, you lack sufficient privileges. {0}", ex.Message);

}

catch (Exception ex)

{

    MessageBox.Show(ex.Message);

}

 

Other methods when open a FileStream object for StreamRead or StreamWrite use:

 

using (FileStream fs = File.Open

      (path, FileMode.Open, FileAccess.Write, FileShare.None))

{

    using (TextReader tr = new StreamReader("text.txt"))

    using (StreamReader sr = new StreamReader("text.txt"))

    using (TextWriter tr = new StreamWriter("text.txt"))

    using (StreamWriter sw = new StreamWriter("text.txt"))

    {

         // Your read or write code go there

    }

}

Other exceptions may apply if needed:

Exception

Condition

IOException

An I/O error occurs.

OutOfMemoryException

There is insufficient memory to allocate a buffer for the returned string.

ObjectDisposedException

The TextReader is closed.

ArgumentOutOfRangeException

The number of characters in the next line is larger than MaxValue

ArgumentNullException

buffer is null.

ArgumentException

The buffer length minus index is less than count.

 

See on MSDN about System.IO Namespace for a complete document)

No comments:

Post a Comment