Closing a file after File.Create

C#File Io

C# Problem Overview


I check to see if a 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 saying that

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

There isn't a File.Close(myPath) that I can call so that it is closed after being created, so how do I free this resource so that I can open it later in my program?

C# Solutions


Solution 1 - C#

File.Create(string) returns an instance of the FileStream class. You can call the Stream.Close() method on this object in order to close it and release resources that it's using:

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

However, since FileStream implements IDisposable, you can take advantage of the using statement (generally the preferred way of handling a situation like this). This will ensure that the stream is closed and disposed of properly when you're done with it:

using (var myFile = File.Create(myPath))
{
   // interact with myFile here, it will be disposed automatically
}

Solution 2 - C#

The function returns a FileStream object. So you could use it's return value to open your StreamWriter or close it using the proper method of the object:

File.Create(myPath).Close();

Solution 3 - C#

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

Solution 4 - C#

File.WriteAllText(file,content)

create write close

File.WriteAllBytes--   type binary

:)

Solution 5 - C#

The reason is because a FileStream is returned from your method to create a file. You should return the FileStream into a variable or call the close method directly from it after the File.Create.

It is a best practice to let the using block help you implement the IDispose pattern for a task like this. Perhaps what might work better would be:

if(!File.Exists(myPath)){
   using(FileStream fs = File.Create(myPath))
   using(StreamWriter writer = new StreamWriter(fs)){
      // do your work here
   }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - C#DonutView Answer on Stackoverflow
Solution 2 - C#MarioView Answer on Stackoverflow
Solution 3 - C#Klaus Byskov PedersenView Answer on Stackoverflow
Solution 4 - C#danisView Answer on Stackoverflow
Solution 5 - C#t3rseView Answer on Stackoverflow