KMC
KMC

Reputation: 20036

Understand FileStream in File.Create and File.Write

I cannot understand why I need to dispose the File.Create or wrap the creation within a using station before accessing the file and write to it. Why do I need to dispose that instances of Stream class that File.Create initialized, and have to create another Stream instance to write to it? Are they on a different thread, why?

Why can't creation, text-writing, and deletion share the same Stream? Perhaps I just do not understand Stream.

For example:

File.Create(...);
File.ReadLine(...); <-- The process cannot access the file ... because it is being used by another process

using (File.Create(...)) {};
File.ReadLine(...); <-- OK

Upvotes: 0

Views: 104

Answers (1)

Clemens
Clemens

Reputation: 128077

See the Remarks section on the File.Create page on MSDN (emphasis mine):

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.

Upvotes: 3

Related Questions