Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing a file after File.Create [duplicate]

Tags:

c#

file-io

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?

like image 688
John Avatar asked Mar 01 '11 15:03

John


People also ask

What should we do to close a file in order to release the resources?

When you're done with a file, use close() to close it and free up the resources that were tied with the file and is done using Python close() method.

How do you copy a file that is being used by another process?

To create a copy of a file that is read- and/or write-locked by another process on Windows, the simplest (and probably only) solution is to use the Volume Shadow Copy Service (VSS). The Volume Shadow Copy Service is complex and difficult to call from managed code.


Video Answer


2 Answers

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 } 
like image 98
Donut Avatar answered Sep 29 '22 11:09

Donut


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(); 
like image 44
Mario Avatar answered Sep 29 '22 10:09

Mario