简体   繁体   中英

FileStream Create

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.

对于第一个,你有更多的选择:句柄,文件访问,文件模式,int缓冲区大小,....但是第二个你可以做的选项较少。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM