Working with text files

avirag 1 Tallied Votes 201 Views Share

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.

// 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;
}
jonsca 1,059 Quantitative Phrenologist Team Colleague Featured Poster

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())

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.