Sorry all, but there was some other problem. The code is now working correct. Thanks all.
I have the following code for creating a file if it does not exist and overwriting it if it already exists:
FileStream fsExe = File.Create(DestExePath, 4096);
BinaryWriter bw = new BinaryWriter(fsExe);
What ever I write to the BinaryWriter, it is getting appended to the "DestExePath" instead of overwriting the original file.
Anybody have any idea, why it is happening ?
The reason this happens is because you never close the underlying stream and reuse the same binary writer to write to the file which will append of course. I would recommend you close the stream once you've finished writing to the file:
using (var stream = File.Create(DestExePath, 4096))
using (var writer = new BinaryWriter(stream))
{
// Use the writer here to append to the file.
}
If you keep the bw open, and keep writing, of course it will append.
If you want to replace the file, you have to close the file, open it again, and make a new binary writer.
This shouldn't happen according to the documentation:
"If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten."
Source: http://msdn.microsoft.com/en-us/library/d62kzs03.aspx
Do you experience the same behaviour with this code?
using (FileStream fileStream = new FileStream(DestExePath, FileMode.Create))
{
BinaryWriter bw = new BinaryWriter(fsExe);
}
running this work without issue
Sub Main()
Dim fsExe = File.Create("c:\test.txt", 4096)
Dim bw = New BinaryWriter(fsExe)
bw.Write("this is a test 123")
fsExe.Close()
End Sub
it does overwrite
Sorry all, but there was some other problem. The code is now working correct. Thanks all.
精彩评论