File.OpenWrite appends instead of wiping contents?

后端 未结 2 1026
名媛妹妹
名媛妹妹 2020-12-11 14:12

I was using the following to write to a file:

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


        
相关标签:
2条回答
  • 2020-12-11 14:53

    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.

    0 讨论(0)
  • 2020-12-11 14:58

    Yes you are right. File.OpenWrite does not overwrite the file.

    The File.Create is used to overwrite the file if exists.

    0 讨论(0)
提交回复
热议问题