尽管append = false,但无法使用streamwriter覆盖文件,而没有关闭文件 [英] unable to overwrite file using streamwriter despite append= false, without closing file

查看:171
本文介绍了尽管append = false,但无法使用streamwriter覆盖文件,而没有关闭文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#VS 2010,Windows窗体. 我的目标是只打开和关闭文件一次,然后覆盖"多次.我永远不想追加.一次打开和关闭文件的原因是我希望写操作最快.

using C# VS 2010, windows forms. My goal is to open and close the file only once and "overwrite" it multiple times. I never want to append. The reason for opening and closing the file once is I want the write operation to be fastest.

我在streamwriter构造函数中传递了append = false,但它仍会追加并且不会被覆盖.

I am passing append = false in streamwriter constructor but it still appends and not overwrite.

private void testSpeed()
{
StreamWriter sw1 = new StreamWriter(@"d:\logfolder\overwrite.txt", false);
            sw1.AutoFlush = true;
            for (int i = 0; i < 5000; i++)
            {               
                    sw1.Write(i);            
            }
            sw1.Close();
}

我的预期输出是文件应该只有4999 但是我得到了这个 0123456789101112131415161718192021222324252627282930313233 ............... 一直到4999

My expected output is the file should only have 4999 but I am getting this instead 0123456789101112131415161718192021222324252627282930313233............... all the way to 4999

此文件已存在 d:\ logfolder \ overwrite.txt

this file already exists d:\logfolder\overwrite.txt

有什么主意我做错了吗?

Any ideas what I Am doing wrong?

推荐答案

append = false参数仅适用于流执行的单个整体写入.每次对stream.Write()的调用都会将数据附加到流中已有的数据上.

The append = false parameter is only good for the single overall write that the stream does. Each call to stream.Write() appends the data to what is already in the stream.

您可能需要在每次迭代期间Flush()Clear()流,尽管这很可能行不通.

You would either need to Flush() or Clear() the stream during each iteration, though that most likely won't work.

要获得所需的内容,您要么每次都要打开一个新连接,要么等到最后一个要写的内容.

To get what you want, you'll either have to open a new connection every time, or wait until the last item to write.

编辑

具有sw1.autoflush = true只是意味着它将立即将Write()方法中的上下文写入文件,而不是等待直到连接关闭.

Having sw1.autoflush = true only means that it will write the context in the Write() method to the file immediately, instead of waiting until the connection is closed.

如果您只想写集合中的最后一项,则可以执行以下操作:

If you only want to write the last item in your collection, you can just do the following:

for (int i = 0; i < 5000; i++)
{
    if (i == 4999)
    {
        sw1.Write(i);
    }
}

但是,如果您使用的是列表或项目数组,则可以执行以下操作:

However, if you're working with a List, or Array of items, then you can just do something like the following:

List<int> nums = new List<int>();

// Note that this requires the inclusion of the System.Linq namespace.
sw1.Write(nums.Last());

这篇关于尽管append = false,但无法使用streamwriter覆盖文件,而没有关闭文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆