user1447343
user1447343

Reputation: 1467

How to Overwrite Existing Text Using FileStream

NOTE: I can't use FileMode.Create or FileMode.Truncate because they would cause some unwanted problem

 byte[] data = new UTF8Encoding().GetBytes(this.Box.Text);
                FileStream f = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
f.Write(data, 0, data.Length);
                f.Close();

This will append new text to the top of the old one. How can I overwrite everything?

Upvotes: 2

Views: 15836

Answers (1)

MethodMan
MethodMan

Reputation: 18863

your code

byte[] data = new UTF8Encoding().GetBytes(this.Box.Text); FileStream f = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); f.Write(data, 0, data.Length); f.Close();

how come you can't do something like this..? please explain why you can't use FileMode.Create

byte[] data = new UTF8Encoding().GetBytes(this.Box.Text);
using(Stream f = File.Open(path, FileMode.Write)) 
{
   f.Write(data, 0, data.Length);
}

you could also do something like the following

1. Let the users write to the same file
2. capture the users Machine Name or User Id then
2. write a line in your file like this 

strSeprate = new string('*',25); 
//will write to the file "*************************";
f.Write(strSeprate);
f.Write(Machine Name or UserId);
f.Write(data);
f.Write(DateTime.Now.ToString());
f.Write(strSeprate);

just an idea..

Upvotes: 1

Related Questions