Miles Kim
Miles Kim

Reputation: 59

Overwriting txt file in C#

Update Sorry for not explaining it clearly. The output i want is to update the save file with new text and not continue writing it at the end of line. Not sure if I explaining it correctly. Please correct me if i'm wrong. Thank you.


Was trying to overwrite the whole .txt file. But it only continue to add on more line to the file instead of overwriting it. Tried putting true inside outfile but still don't work. It will be great if anyone can teach me on how to overwrite the text file.

Thanks in advance.

   private void bttSave_Click(object sender, EventArgs e)
        {
            outFile = new FileStream(FILENAME, FileMode.Append, FileAccess.Write); //Creating a file stream object to open file for reading
            writer = new StreamWriter(outFile); //creating a stream writer with the outfile file stream object
            for(int i = 0; i < DataGridResult.RowCount; i++)
            {
                writer.WriteLine(adminNoTxt.Text + DELIM + DataGridResult.Rows[i].Cells[0].Value.ToString() + DELIM + DataGridResult.Rows[i].Cells[1].Value.ToString() + DELIM + DataGridResult.Rows[i].Cells[2].Value.ToString());
                //using stream writer to write a record
            }

            writer.Close();
            outFile.Close();

        }

Upvotes: 0

Views: 241

Answers (2)

Reyhaneh Sharifzadeh
Reyhaneh Sharifzadeh

Reputation: 795

Just use FileMode.Create instead of FileMode.Append .

Both of them check if the file is not exist , create it , then write in the file from the first .

But the difference is that "Append" does not delete the old data and add new data in the end of the file , but "Create" delete all of old data at first , then write new data in the first of the file .

Upvotes: 1

Flat Eric
Flat Eric

Reputation: 8111

Use FileMode.Create instead of FileMode.Append.

  • Create creates a new file if it does not exist or overwrites it if it does.
  • Append does append it at the end.

See http://msdn.microsoft.com/library/system.io.filemode%28v=vs.110%29.aspx

Upvotes: 6

Related Questions