C# 如何使用FileStream覆盖现有文本

C# 如何使用FileStream覆盖现有文本,c#,io,C#,Io,注意:我不能使用FileMode.Create或FileMode.Truncate,因为它们会导致一些不必要的问题 byte[] data = new UTF8Encoding().GetBytes(this.Box.Text); FileStream f = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); f.Write(data, 0, data.Lengt

注意:我不能使用FileMode.Create或FileMode.Truncate,因为它们会导致一些不必要的问题

 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();
这将在旧文本的顶部追加新文本。如何覆盖所有内容?

您的代码

byte[]data=new UTF8Encoding().GetBytes(this.Box.Text);
FileStream f=File.Open(路径,FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite);
f、 写入(数据,0,数据长度);
f、 Close()

你为什么不能做这样的事。。?请解释为什么不能使用
FileMode.Create

byte[] data = new UTF8Encoding().GetBytes(this.Box.Text);
using(Stream f = File.Open(path, FileMode.Write)) 
{
   f.Write(data, 0, data.Length);
}
您还可以执行以下操作

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);

只是个主意

为什么你不能使用FileMode。创建你需要更具体地说明为什么你不能使用它以及你真正想做什么。我的程序是多线程的,我使用FileSystemWatcher来监视文件。因此,如果我使用FileMode.Create(创建一个新文件,然后覆盖第一个文件),有时它会破坏我程序的功能。我在你回复之前发布了我的答案。。让我改变我的回答。。是否要附加到同一个文件或在多线程中覆盖现有文件…?那么FileMode.Truncate应该可以工作,因为它不会删除文件,而是删除内容。由于文件仍然存在,因此不应启动FileSystemWatcher。如果确实如此,那么您可能还有另一个问题,与FileSystemWatcher、您的业务逻辑或环境有关(例如,对网络驱动器的文件监视通常会导致故障).Desty我同意也许他需要在
FileSystemWatcher
中显示代码,以及他如何在
SystemFileWatcher
中创建
线程。。如果看不到更多相关代码,很难确定。我正在尝试创建一个程序,允许多个用户同时编辑同一个文件。我有FileSystemWatcher来监视文件中的更改,以便更新屏幕。我已更改监控文本以对文件进行更改。如果我有FileMode.Create,有时它会在创建新文件时触发FileSystemWatcher事件,然后再开始写入,并导致我的文本框为空(我的文本框的内容绑定到该文件)。这将触发TextChanged,然后不向文件写入任何内容,最终所有内容都是空的…这听起来相当危险-您有什么保证会显示最新的更新。。。?这听起来像是多个用户想要更新同一个文件。。也许您希望实施SharePoint解决方案。。我不知道您如何知道哪些文件内容对于您可能遇到的多个
delta
是有效的。也许您可以通过允许用户将其数据附加到现有文件中来创建文件,记录用户计算机名\用户id、日期时间、数据内容,然后使用某种形式的delim来表明他们已经完成了文件的更新,比如在文件写入字符串stresprate=new string('*',25)的开头和结尾这样做;威尔=
“**********************”
谢谢你的建议!我通过使用锁来解决多线程问题