Monday, June 15, 2009

How to read data from a txt file using c#

Before going to the code ,just know about stream reader

StreamReader:
streamreader is nothing but file pointer and here I used the stream reader to read the data from the text file(.txt) and displaying that it is in a label. System.IO.this is the name space required to deal with the files. To read a text file we need to create the instance of the object,StreamReader The instance will be the file pointer for us. Once we have a File Pointer, we need to invoke the method, OpenText method of the object, File. The method, OpenText takes a string as an argument. The string is nothing but the path of file that is going to get created.
Now, let us see an example.

String filename=Server.MapPath("new.txt");//here in the string we are storing the filepath StreamReader strrr;
strrr=File.OpenText(filename);//here streamreader pointing the files..means stream reader is nothing but a file pointer
lbltxt.Text=str;//here we are displaying the txt file data in the label.
strrr.Close();..
fstring str=strrr.ReadToEnd();

No comments:

Post a Comment