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
You need to use
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.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.
You would either need to that most likely won't work. Flush()
or Clear()
the stream during each iteration, though
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());