且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

覆盖现有的文本文件,并用一个新的替换

更新时间:2023-12-02 21:21:40

您尝试了什么?

关闭文件后,只需使用相同的文件名创建一个新的StreamWriter.默认情况下,它应该覆盖现有文件.

您正在关闭较旧的StreamWriter,不是吗?如果yu同时在同一文件上打开2,我不确定会发生什么.
What have you tried?

Once you''ve closed the file, just create a new StreamWriter with the same file name. By default, it should overwrite the existing file.

You are closing the older StreamWriter, aren''t you? If yu have 2 open on the same file at the same time, I''m not sure what would happen.


在对StreamWriter构造函数的调用中,您使用了第二个true的(布尔)参数,表示将数据追加到现有文件中",也就是说,您所做的与您想做的相反.将其更改为false.

—SA
In your call to the of StreamWriter constructor you have uses the second (Boolean) parameter of true, which means "append data to an existing file", that is, you have done the opposite to what you wanted to do. Change it to false.

—SA


您好,亲爱的
如果要创建一个没有数据的新文件,则必须执行此操作.
1首先删除当前文件
Hello Dear
if you want to have a new file with no data in it you must do this.
1 first delete current file
string Filepath = @"G:\Users\Reza\Desktop\a.txt";
System.IO.File.Delete(Filepath);


2创建要写入的新文件


2 create new file to write in

System.IO.FileStream Str = System.IO.File.Create(Filepath);



但是如果您想将数据追加到当前文件中,则您的操作是正确的,并且如果您想覆盖当前文件中当前数据中的数据,例如SAKryukov所说的将第二个参数设置为false,这样当前数据就在当前文件中,但是您插入的每个新数据都将替换为文件首位的当前数据



but if you want to append data to current file , what yo did is true ,and if you want overwrite data in current data in current file , like what SAKryukov said set second parameter to false , in this way current data are in current file but each new data which yout insert will replace in current data from fisrt of the file