Friday 27 April 2012

Beginning .Net , C# Tips : Reading and writing a text file with a StreamReader in C# Programming

StreamReader and StreamWriter classes to write a string to a text file and then read the contents of that text file.

Here are Exmaple for Write and Read File.

C# Example :
         /////Write to a file
        System.IO.StreamWriter streamwriter = new System.IO.StreamWriter(System.IO.File.Open
(MapPath("TextFile.txt"),System.IO.FileMode.OpenOrCreate));
        streamwriter.Write("This is a sample string");
        streamwriter.Close();

        //////Read from a file
        System.IO.StreamReader reader =new System.IO.StreamReader(System.IO.File.Open(MapPath
("TextFile.txt"),System.IO.FileMode.Open));
        string tmp = reader.ReadToEnd();
        reader.Close();


When you create a StreamReader, you must pass an existing stream instance as a constructor
parameter. The reader uses this stream as its underlying data source.
In this sample, you use the File class’s Open method to open a writable FileStream for your StreamWriter.

Also notice that you no longer have to deal with byte arrays. The StreamReader takes care of converting the data to a type that’s more user-friendly than a byte array. In this example, you are using the ReadToEnd method to read the entire stream and convert it to a string.The StreamReader provides a number of different methods for reading data that you can use depending on exactly how you want to read the data, from reading a single character using the Read method, to reading the entire file using the ReadToEnd method.

VB.net Example :
    /////Write to a file
    Dim streamwriter As New System.IO.StreamWriter(System.IO.File.Open(MapPath
                     ("TextFile.txt"),System.IO.FileMode.Open))
    streamwriter.Write("This is a string")
    streamwriter.Close()

    //////Read from a file
    Dim reader As New System.IO.StreamReader(System.IO.File.Open(MapPath
                   ("TextFile.txt"),System.IO.FileMode.Open))
    Dim tmp As String = reader.ReadToEnd()
    reader.Close()

No comments:

Post a Comment