In C#, do I need to close the Filestream
File.Close()
after calling its create method
File.Create(path)
?
In C#, do I need to close the Filestream
File.Close()
after calling its create method
File.Create(path)
?
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
}
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