How to append a file on website

joe_pool_is

Contributor
Joined
Jan 18, 2004
Messages
507
Location
Longview, TX [USA]
I used to append a file using Classic ASP on my website.

I finally migrated parts over to .NET, but I can't seem to find out how to append a file. I can still determine if the file exists using File.Exists, but I don't know how to fill it!
C#:
      if (File.Exists(strPath) == true) {
        FileStream fs = null;
        try {
          fs = File.Open(strPath, FileMode.Append);
          char[] data = historyMsg.ToCharArray();
          byte[] bdat = new byte[2 * data.Length];
          for (int i = 0; i < (2 * data.Length); i++) {
            // how do I fill this part???
          }
          fs.Write(bdat, 0, bdat.Length);
        } catch (Exception err) {
          Response.Write("<b>Unable to append to log file: <font color=\"red\">" + err.Message + "</font></b><br/><br/>");
          ok = false;
        } finally {
          if (fs != null) {
            fs.Close();
          }
        }
 
Once you have opened the file stream you could either use it's Write method or a possibly even easier way would be to open a StreamWriter over the FileStream and use it to write the string(s) directly.
 
I had to look up how to use StreamWriter, but you're right! It was MUCH easier!

My code is now simply:
C#:
if (File.Exists(strPath) == true) {
  using (StreamWriter sw = File.AppendText(strPath)) {
    sw.Write(historyMsg);
    sw.WriteLine("<hr>");
  }
}
Thank you! Again, I owe you a cup of coffee!
 
Back
Top