Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

c# - File.OpenWrite appends instead of wiping contents?

I was using the following to write to a file:

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);

This worked fine.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is the specified behavior for File.OpenWrite:

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);

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...