Closing a file after File.Create

I check if the file exists with

if(!File.Exists(myPath)) { File.Create(myPath); } 

However, when I go to create a StreamReader with this newly created file, I get an error message

The process cannot access the file '[my file path is here]' because it is being used by another process.

There is no File.Close(myPath) that I can name so that it is closed after creation, so how do I free this resource so that I can open it later in my program?

+50
c # file-io
01 Mar. 2018-11-11T00:
source share
5 answers

File.Create(string) returns an instance of the FileStream class. You can call the Stream.Close() method on this object to close it and free up the resources it uses:

 var myFile = File.Create(myPath); myFile.Close(); 

However, since FileStream implements IDisposable , you can use the using statement (usually the preferred way to handle this situation). This ensures that the thread is closed and disposed of correctly when you are done with it:

 using (var myFile = File.Create(myPath)) { // interact with myFile here, it will be disposed automatically } 
+113
Mar 01 '11 at 15:08
source share

The function returns a FileStream object. Therefore, you can use its return value to open your StreamWriter or close it using the correct object method:

 File.Create(myPath).Close(); 
+31
Mar 01 '11 at 15:09
source share

File.Create returns a FileStream object that you can call Close() .

+4
Mar 01 '11 at 15:09
source share

The reason is that FileStream is returning from your method to create the file. You must return the FileStream to a variable or call the close method immediately after the File.Create file.

It is best to let the using block help you implement the IDispose pattern for such a task. Perhaps best would work:

 if(!File.Exists(myPath)){ using(FileStream fs = File.Create(myPath)) using(StreamWriter writer = new StreamWriter(fs)){ // do your work here } } 
+2
Mar 01 2018-11-11T00:
source share
 File.WriteAllText(file,content) 

create record close

 File.WriteAllBytes-- type binary 

:)

+2
Feb 13 '13 at 17:24
source share



All Articles