1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Writing Data to File with StreamWriter

Discussion in 'C#' started by daffodils180, Jul 14, 2010.

  1. daffodils180

    daffodils180 New Member

    Joined:
    Jul 14, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi all,

    I have to write some data to a text file on click of a checkbox. The code is as follows:
    Code:
    if (checkBox1.Checked == true)
    {
             string filePath = @"C:\Temp\LogFile.text";
             FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write);
             StreamWriter sw = new StreamWriter(fs);
             try
             {
                   sw.Write(string1);
                   sw.Write("\t");
                   sw.Write(string2);
                   sw.Write("\t");
                   sw.WriteLine();
              }
              finally
             {
                   if (sw != null)
                   {
                         sw.Close();
                         fs.Close();
                         sw = null;
                   }
              }                                    
    }
    
    The requirement is: I need to append all the data, every time this function is called and when the application is closed and re-started only the newly configured data should be written into it(the old data should be erased)

    1) If i use "FileMode.Append", all the data will be appended to the file, every time the function is called and all the previous data also exits even after closing the application and restarting it, which is not required.

    2) If i use "FileMode.Create" only the data configured at the end (i.e the last one) is written to the file.
    Please help me with the correct solution.
    Thanks in advance.
     

Share This Page