Is this syntax
FileStream fs = new FileStream(strFilePath, FileMode.Create);
the same as this?
FileStream fs = File.Create(strFilePath);
When yes, which one is better?
Is this syntax
FileStream fs = new FileStream(strFilePath, FileMode.Create);
the same as this?
FileStream fs = File.Create(strFilePath);
When yes, which one is better?
It does matter, according to JustDecompile, because File.Create
ultimately calls:
new FileStream(path,
FileMode.Create,
FileAccess.ReadWrite,
FileShare.None,
bufferSize,
options);
With a bufferSize
of 4096 (default) and FileOptions.None
(also the same as with the FileStream constructor), but the FileShare
flag is different: the FileStream constructor creates the Stream with FileShare.Read
.
So I say: go for readability and use File.Create(string)
if you don't care about the other options.
In my opinion, I use this one:
using (FileStream fs = new FileStream(strFilePath, FileMode.Create))
{
fs.Write("anything");
fs.Flush();
}
They basically doing the same thing, but this one create the file and opens it in create / write mode, and you can set your buffer size and all params.
new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, options);
With File.Create it wraps all those default buffer and params.. You will have a way better flexibility and management with my new FileStream(strFilePath, FileMode.Create); But at this point it's more a personnal choice, if you want more readability or management options!
The second one uses just a different FileMode for the stream: take a look to this article
http://msdn.microsoft.com/en-us/library/47ek66wy.aspx
to manage default values of this method!
But use a using
statement, so any resource will be released in the correct way!
using (FileStream fs = new FileStream(strFilePath, FileMode.Create))
{
// HERE WHAT YOU WANT TO DO!
}
They do exactly the same thing. The only real difference is that the former would let you use a different FileMode at runtime if you wanted to (controlling it with a variable) and the latter will only ever be doing a Create operation.
As a side note, convention is to handle things like a filestream in a using block to automatically dispose of them when they are out of scope.
using (var fs = new FileStream(strFilePath, FileMode.Create))
{
//do some stuff
}
First one creates or overwrites file with sharing Read access second with None. So it depends do you want to allow to give access while processing file or not.
With the first one you have more options to do like : handle, file access, file mode, int buffer size,.... but with the second one you have less options to do.