Read and Write to Text Files in c#


There are many ways to read and write to text files. We will see one option here. Be sure to add using System.IO namespace.
This is a function to write to a Text File.
private bool writeToTextFile()
    {
        bool success = true;
        //path and filename
        string fileName = Server.MapPath("abc.txt");
        //data to be written in the file
        //\r\n is to insert a new line
        string data = "This is the first line \r\n" +
                      "This is the second line \r\n\r\n" +
                      "This is the third line";
        try
        {
          File.WriteAllText(fileName, data);//write the data to the text file
        }
        catch (Exception e)
        {
            Response.Output.Write(e.Message);
            success = false;
        }
        return success;
    }
In the above function,\r\n is used to insert a new line.
This function is used to read from text file.
 
      private bool readFromTextFile()
    {
        bool success = true;
        //path and filename
        string fileName = Server.MapPath("abc.txt");
        try
        {
            string data = File.ReadAllText(fileName);//read from text file
            data = data.Replace("\r\n", "");//\r\n is replaced by
            Response.Output.Write(data);           
        }
        catch (Exception e)
        {
            Response.Output.Write(e.Message);
            success = false;
        }
        return success;
    }

0 comments:

Post a Comment