How to Overwrite Existing Text Using FileStream
14,674
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..
Author by
user1447343
Updated on June 04, 2022Comments
-
user1447343 almost 2 years
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?
-
user1447343 over 11 yearsI'm trying to create a program that allows multiple users to edit the same file at the same time. I have FileSystemWatcher to monitor the change in file so that I could update my screen. I have TextChanged monitored to make changes to the file. If I have FileMode.Create sometimes it triggers FileSystemWatcher's event when it creates a new file and before it starts writing to it and results in my textbox to be blank (my textbox's content is binded to the file). This will trigger TextChanged and then write nothing to the file and eventually everything is empty...
-
MethodMan over 11 yearsThis sounds rather dangerous what assurances do you have that the latest update will be shown...? this sounds like if multiple users want to update the same file .. perhaps you would want to implement a SharePoint solution .. I don't see how you will know which file contents are valid in regards to the multiple
Deltas
that you are potentially running into.. -
MethodMan over 11 yearsPerhaps you would create the file by allowing the users to have their data appended into the existing file, log the users machine name\user id, datetime, data content, then use some sort of delim to show that they are done with the updating of the file something like this at the beginning and end of the file writing string strSeprate = new string('*',25); will =
"*************************"
-
user1447343 over 11 yearsThanks for your suggestions! I solve the multi-thread by using a lock