覆盖现有的文本文件,并用一个新的替换 [英] overwrite the existing textfile and replace it with a new one
问题描述
你好:
我在自己创建的文本文件中写入数据(文本文件)
但是问题是,当我再次运行该过程并创建一个新的文本时,我想覆盖旧的文本文件,这是代码:
Hello:
I''m writting data in a text file that I created by myself(text file)
but the problem is that I want to overwrite the older text file when I run the procedure again and create a new one this is the code:
string path = @"D:\Results new r_r.txt";
using (StreamWriter sw = new StreamWriter(path, true))
{
清理标签
Cleaned up tags
推荐答案
您尝试了什么?
关闭文件后,只需使用相同的文件名创建一个新的StreamWriter
.默认情况下,它应该覆盖现有文件.
您正在关闭较旧的StreamWriter
,不是吗?如果yu同时在同一文件上打开2,我不确定会发生什么.
What have you tried?
Once you''ve closed the file, just create a newStreamWriter
with the same file name. By default, it should overwrite the existing file.
You are closing the olderStreamWriter
, 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 ofStreamWriter
constructor you have uses the second (Boolean) parameter oftrue
, which means "append data to an existing file", that is, you have done the opposite to what you wanted to do. Change it tofalse
.
—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
这篇关于覆盖现有的文本文件,并用一个新的替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!