0

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?

bsobaid
  • 955
  • 1
  • 16
  • 36
  • 1
    Why are you not using FileStream object? – ArtK Mar 02 '15 at 16:58
  • I tried this, but did'nt help. FileStream sw1 = new FileStream(@"d:\logfolder\overwrite.txt"", FileMode.OpenOrCreate, FileAccess.Write); and then inside the loop sw1.Write(uniEncoding.GetBytes(s), 0, uniEncoding.GetByteCount(s)); it still appends – bsobaid Mar 02 '15 at 17:26
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Mar 02 '15 at 17:32
  • This question has your answer and is probably a duplicate http://stackoverflow.com/questions/2313728/reusing-a-filestream – Steve Mitcham Mar 02 '15 at 17:44
  • so doing_fstrea.SetLength(0) before every write does the overwrite but it is extremely slow. Took 35 seconds to run the loop 50,000 times. The example I have in my original post is less than 1 second but it appends and not overwrites. So my problem remains unsolved. – bsobaid Mar 02 '15 at 18:54

2 Answers2

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());
krillgar
  • 12,596
  • 6
  • 50
  • 86
  • autoflush = true. There is no clear() and I also tried sw1.flush() inside the loop but it did'nt work and I got the same results. How do I know how long to wait till last write is completed? – bsobaid Mar 02 '15 at 16:54
  • [Autoflush](https://msdn.microsoft.com/en-us/library/system.io.streamwriter.autoflush(v=vs.90).aspx) says nothing about listening to the `append` parameter of the `StreamWriter`. As I said, those two methods most likely won't work (and one doesn't exist). You asked what you were doing wrong, I explained what was wrong with your approach. How to wait until the last item to write is up to you, as I doubt your specific use case is as specific as your example. – krillgar Mar 02 '15 at 17:00
  • ok, then how to acheive what I want to achieve i-e overwrite the contents without open and close the streamwriter? – bsobaid Mar 02 '15 at 17:25
0

You need to use

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

Jorge Freitas
  • 790
  • 10
  • 18