Hello every one
i want know i can read one text file in c#
i f we can do it please explean for me how can i do it
thanks alot

4 Years
Discussion Span
Last Post by castajiz_2

There are many ways to read a text file in C#. Which do you want to do:
1) Read 1 character at a time
2) Read 1 line at a time
3) Read all the lines and put them into an array.
4) Read the entire file as one long line.


First of all remember to use a namespace called IO by typing,,, using System.IO;
I suggest you to use this

        string z=null; // make it global
        OpenFileDialog ofd = new OpenFileDialog();
        if (ofd.ShowDialog() == DialogResult.OK)

                StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName));

                while (!sr.EndOfStream)
                       z=sr.ReadLine();  / there are a lot of methods that the streamreader provides by using the name of the streamreader in this example sr. you can acces all of them
                      // do someting else if you want

Use the open file dialog so you can open your txt file. Also you ve got a great property ofd.FileName which uses the file that you clicked on it rather than giving the path to the exact file that you want to use. at the end you just store your strings inside the variable. The loop is here because we want to read till the end otherwrise you could just use the method called ReadToEnd();
I suggest you to find more on the Net , there are so many things about it.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.