unable to overwrite file using streamwriter despite append= false, without closing file

放肆的年华 提交于 2019-12-31 05:36:08

问题


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.

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

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

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

Any ideas what I Am doing wrong?


回答1:


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.

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.

EDIT

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



回答2:


You need to use

FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);



来源:https://stackoverflow.com/questions/28815111/unable-to-overwrite-file-using-streamwriter-despite-append-false-without-closi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!