-3

In C#, do I need to close the Filestream

File.Close()

after calling its create method

File.Create(path)

?

Tim
  • 1
  • 141
  • 372
  • 590
  • 1
    The answer is in the example of your link. You need call Close of the object return by the File.Create method. In the example, the close call is implicitly invoked by the using statement. – Kalten Feb 16 '17 at 22:56
  • Possible duplicate of [Closing a file after File.Create](http://stackoverflow.com/questions/5156254/closing-a-file-after-file-create) – Daniel Bernsons Feb 16 '17 at 23:52

2 Answers2

5

According to the MSDN Page you've linked to in the question, the answer is Yes.
Note the remarks section:

The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

However, if you are writing it in a using statement, then the c# compiler handles the closing and disposal of the file stream for you:

using (var fs = File.Create(path))
{
// Do your stuff here
}
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
0

You should if you do not intend to use the Filestream any longer or else you will receive errors if you try to open the file somewhere else like in the following example:

FileStream fs = File.Create("test.txt");            
string[] s = File.ReadAllLines("test.txt");//Will cause an IOException
cesar21
  • 23
  • 6