Filestream create

This syntax

FileStream fs = new FileStream(strFilePath, FileMode.Create); 

same as this?

 FileStream fs = File.Create(strFilePath); 

When yes, which one is better?

+7
source share
6 answers

This matters, according to JustDecompile, because File.Create ultimately calls:

 new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, options); 

With bufferSize of 4096 (by default) and FileOptions.None (also the same as with the FileStream constructor), but the FileShare flag FileShare different: the FileStream constructor creates a Stream with FileShare.Read .

So, I say: go for readability and use File.Create(string) if you don't need other parameters.

+9
source

In my opinion, I use this option:

 using (FileStream fs = new FileStream(strFilePath, FileMode.Create)) { fs.Write("anything"); fs.Flush(); } 

They basically do the same, but it creates a file and opens it in create / write mode, and you can set the buffer size and all the parameters.

 new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, options); 

With File.Create, it wraps all of these buffers and default parameters. You will have more flexibility and control with my new FileStream (strFilePath, FileMode.Create); But at the moment this is a more personal choice if you want more reading or management opportunities!

+6
source

They do the same thing. The only real difference is that the former will allow you to use another FileMode at runtime if you want (by controlling it with a variable), and the latter will perform the Create operation.

As a side note, an agreement needs to handle things like a thread in a usage block to automatically get rid of them when they go beyond.

 using (var fs = new FileStream(strFilePath, FileMode.Create)) { //do some stuff } 
+1
source

The second uses only another FileMode for the stream: take a look at this article

http://msdn.microsoft.com/en-us/library/47ek66wy.aspx

to control the default values โ€‹โ€‹of this method!

But use the 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! } 
+1
source

First, a read-only file is created or overwritten with None. So it depends on whether you want to allow access while processing the file or not.

0
source

With the first you will get more options: a descriptor, file access, file mode, int buffer size, .... but with the second you have less options.

0
source

All Articles