开发者

File.Create is appending to the file rather than overwriting it [closed]

开发者 https://www.devze.com 2023-01-07 17:08 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. 开发者_运维问答 Closed 10 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消