IO Exception in C#

Maj*_*jid 0 .net c# io visual-studio

In my c# application which developed with c# in visual studio 2012 I created a file by this command : System.IO.File.Create("config.conf"); after that in the next line I want to use the file by this command : System.IO.StreamReader rd = new System.IO.StreamReader("config.conf"); But I get This exception :

"The process cannot access the file '\config.far' because it is being used by >another process."

I used thread.sleep(2000) to make application wait but still it doesn't answer.

I will appropriate any help.

ang*_*son 5

File.Create creates the file and returns a FileStream holding the file open.

You can do this:

System.IO.File.Create("config.conf").Dispose();
Run Code Online (Sandbox Code Playgroud)

by disposing of the returned stream object, you close the file.

Or you can do this:

using (var stream = File.Create("config.conf"))
using (var rd = new StreamReader(stream))
{
    .... rest of your code here
Run Code Online (Sandbox Code Playgroud)

Additionally, since disposing of the StreamReader will also dispose of the underlying stream, you can reduce this to just:

using (var rd = new StreamReader(File.Create("config.conf")))
{
    .... rest of your code here
Run Code Online (Sandbox Code Playgroud)

Final question: Why are you opening a newly created stream for reading? It will contain nothing, so there's nothing to read.