Creating an empty file in C#

前端 未结 7 516
渐次进展
渐次进展 2020-12-02 07:13

What\'s the simplest/canonical way to create an empty file in C#/.NET?

The simplest way I could find so far is:

System.IO.File.WriteAllLines(filename         


        
7条回答
  •  旧巷少年郎
    2020-12-02 07:34

    To avoid accidentally overwriting an existing file use:

    using (new FileStream(filename, FileMode.CreateNew)) {}
    

    ...and handle the IOException which will occur if the file already exists.

    File.Create, which is suggested in other answers, will overwrite the contents of the file if it already exists. In simple cases you could mitigate this using File.Exists(). However something more robust is necessary in scenarios where multiple threads and/or processes are attempting to create files in the same folder simultaneously.

提交回复
热议问题