Read-Write or Add-Update HTML or Text files in ASP.Net

Sometimes we need to edit or create new HTML files for Email Templates or to make new HTML page. Using this code you can do add/edit /Append in HTML files in asp.net C#. Use Namespace
using System.IO;

Read Existing HTML File

        FileStream objFileHandler = null; 

        StreamReader objWriter;

        String strMailMessageBody = String.Empty;

        String strFileName = String.Empty;

        strFileName = Server.MapPath("HTMLTemplates/"+ EnterYourFileName);

        objFileHandler = new FileStream(strFileName, FileMode.Open, FileAccess.Read);

        objWriter = new StreamReader(objFileHandler);

        strMailMessageBody = objWriter.ReadToEnd();
        txtDescription.Text = strMailMessageBody;

        objWriter.Close();

        objFileHandler.Close();

Edit HTML Files:

using (FileStream fs = new FileStream(Server.MapPath("HTMLTemplates/" + YouFileName), FileMode.Create, FileAccess.Write))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                string str = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"http://infoa2z.com/Includes/css/style.css\" /><title>http://infoa2z.com/</title></head><body>";

                str = str + txtDescription.Text +"</body></html>";

                sw.Write(str);

                sw.Close();
            }
         
        }

There are different options to handle files: Create, Create New,  Append, Open, OpenOrCreate etc. that you can use  in FileMode

using (FileStream fs = new FileStream(Server.MapPath("HTMLTemplates/" + YouFileName), FileMode.Create, FileAccess.Write))

Related Alrticles

FREE!!! Registration