Read text files in .NET using the System.IO StreamReader

The easiest way is to use the StreamReader class in the System.IO namespace.

Create a form, drop on the OpenFileDialog control and set its Filter property to Text (*.txt) |*.txt. Add a button and in its Click event add the following C# code:

    string myFile = openFileDialog.FileName;

Open the file:

    Using System.IO;

    string strLine = "";
    StreamReader rdr;

        rdr = new StreamReader(myFile);
    catch (Exception ex)
        MessageBox.Show(ex.Message, "Error Opening File", MessageBoxButtons.OK);

Loop through the file:

    while (strLine != null)
        strLine = rdr.ReadLine();
        if ((strLine != null) && (strLine != ""))
         ... process the line of text ...;

About TheScarms
About TheScarms

Sample code
version info

If you use this code, please mention ""

Email this page

© Copyright 2016 TheScarms
Goto top of page