1

HI ALL,
i am writing this snippet to working with text files, here i explain the basic functionality of read/write operation on text files.....:)


Here each method has a single parameter, the file name you wish to work with.

Edited by avirag: n/a

// 1) Write to a text file
public void WriteToFile(string file)
{
    //create a TextWriter then open the file
    TextWriter writer = new StreamWriter(file);
    //now write the date to the file
    writer.WriteLine(DateTime.Now);
    //close the writer
    writer.Close();
}

// 2) Read a single line from text file
public void readALine(string file)
{
    //create a new TextReader then open the file
    TextReader reader = new StreamReader(file);
    //read a single line from the file
    reader.ReadLine();
}

// 3) Read entire file into a variable then
// return the contenxt
public string ReadWholeFile(string file)
{
     //create a string variable to hold the file contents
     string fileContents;
     //create a new TextReader then open the file
     TextReader reader = new StreamReader(file);
     //loop through the entire file
     while (reader.Peek() != -1)
     {
         //add each line to the fileContents variable
         fileContents += reader.ReadLine().ToString();
     }
     //close the reader
     reader.Close()
     //return the results
     return fileContents;
}
2
Contributors
1
Reply
6
Views
7 Years
Discussion Span
Last Post by jonsca
0

All of your reader/writer definitions should probably be wrapped in using() , e.g.,

public string ReadWholeFile(string file)
{
     //create a string variable to hold the file contents
     string fileContents;
     //create a new TextReader then open the file
     using(TextReader reader = new StreamReader(file))
    {
     //loop through the entire file
       while (reader.Peek() != -1)
       {
           //add each line to the fileContents variable
           fileContents += reader.ReadLine().ToString();
       }
     //close the reader
       reader.Close()
     }
     //return the results
     return fileContents;
}

so that the objects are disposed of properly (using in this context adopts a try/catch/finally implicitly, and the finally is always run to Dispose())

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.