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

前端 未结 2 828
野趣味
野趣味 2021-01-27 08:24

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

相关标签:
2条回答
  • 2021-01-27 08:33

    You need to use

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

    0 讨论(0)
  • 2021-01-27 08:45

    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());
    
    0 讨论(0)
提交回复
热议问题