This question already has an answer here:
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?
create write close
:)
The function returns a
FileStream
object. So you could use it's return value to open yourStreamWriter
or close it using the proper method of the object:File.Create(string)
returns an instance of theFileStream
class. You can call theStream.Close()
method on this object in order to close it and release resources that it's using:However, since
FileStream
implementsIDisposable
, you can take advantage of theusing
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: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:
File.Create
returns aFileStream
object that you can callClose()
on.