File.OpenWrite追加,而不是抹内容是什么? [英] File.OpenWrite appends instead of wiping contents?

查看:742
本文介绍了File.OpenWrite追加,而不是抹内容是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面写一个文件:

using(Stream FileStream = File.OpenWrite(FileName)) 
   FileStream.Write(Contents, 0, Contents.Length);



我注意到,它只是简单地写入文件正确的文件,但没有擦去的内容第一个文件。于是我决定简单地使用:

I noticed that it was simply writing to file file correctly, but didn't wipe the contents of the file first. I then decided to simply use:

File.WriteAllBytes(FileName, Contents);

这工作得很好。

不过,为什么不会自动File.OpenWrite删除该文件的内容,因为我已经用于其OpenWrite风格的函数做其他的语言,具有附加的呢?

However, why doesn't File.OpenWrite automatically delete the contents of the file as the other languages i've used do for their OpenWrite style function, and have a instead of appending?

有没有什么方法来做到这一点?

Is there any method to do this?

推荐答案

这是

如果该文件存在,它是开放之初写作。 。现有的文件不被截断。

If the file exists, it is opened for writing at the beginning. The existing file is not truncated.

要做到你以后,只是做:

To do what you're after, just do:

using(Stream fileStream = File.Open(FileName, FileMode.Create)) 
   fileStream.Write(Contents, 0, Contents.Length);

您当前的呼叫等同用FileMode.OpenOrCreate,这不会导致现有的文件被截断。

Your current call is equivalent to use FileMode.OpenOrCreate, which does not cause truncation of an existing file.

FileMode.Create 选项将导致文件的方法来创建一个新的文件,如果它不存在,或者使用FileMode.Truncate如果这样做,给你所需的行为。另外,您也可以使用 File.Create 直接做到这一点。

The FileMode.Create option will cause the File method to create a new file if it does not exist, or use FileMode.Truncate if it does, giving you the desired behavior. Alternatively, you can use File.Create to do this directly.

这篇关于File.OpenWrite追加,而不是抹内容是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆