File-Stream is being used by another process

FileStream f=new FileStream("c:\\file.xml",FileMode.Create);
StreamWriter sf=new StreamWriter(f);
sf.WriteLine(stroka);
sf.Close();
sf.Dispose();
f.Close();
f.Dispose();
FileStream f1=new FileStream("c:\\file.xml",FileMode.Open);
StreamReader sr=new StreamReader("c:\\file.xml");
xmlreader=new XmlTextReader(sr);
sr.Close();
sr.Dispose();
f1.Close();
f1.Dispose();

I am getting this error:

The process cannot access the file 'c:\file.xml' because it is being used by another process

I've closed all and disposed all. What's the problem?

Upvotes: 6

Views: 9404

Answers (4)

gdoron
gdoron

Reputation: 150253

Replace:

StreamReader sr=new StreamReader("c:\\file.xml");

With:

StreamReader sr=new StreamReader(f1);

You're creating new StreamReader without the FileStream


Additional data:

  • The StreamReader object calls Dispose on the provided Stream object when StreamReader.Dispose is called.

  • Dispose method calls the Close method. Read this for more info.

Meaning: you can remove the Dispose and Close you wrote on the FileStream

FileStream f = new FileStream("c:\\file.xml", FileMode.Create);
StreamWriter sf = new StreamWriter(f);
sf.WriteLine(stroka);
sf.Dispose();

FileStream f1 = new FileStream("c:\\file.xml", FileMode.Open);
StreamReader sr = new StreamReader(f1);
xmlreader = new XmlTextReader(sr);
sr.Dispose();

But you really should use the using statement for unmanaged resources, read this.

Upvotes: 9

Brian Warfield
Brian Warfield

Reputation: 377

The problem may be at:

FileStream f1=new FileStream("c:\\file.xml",FileMode.Open);
StreamReader sr=new StreamReader("c:\\file.xml");

Filestream may be accessing the file and then StreamReader tries to access the file separately. Try having your StreamReader use the same defined Stream.

Upvotes: 1

David
David

Reputation: 73564

Change

StreamReader sr=new StreamReader("c:\\file.xml"); 

to

StreamReader sr=new StreamReader(f1); 

both of the followiong lines of code are separate objects trying to access the same file:

FileStream f1=new FileStream("c:\\file.xml",FileMode.Open); 
StreamReader sr=new StreamReader("c:\\file.xml"); 

so each is attempting to access teh file indivodually, whereas changing your code to my connection cases sr to access the file Through f1

Upvotes: 2

Alexandre
Alexandre

Reputation: 4602

You have a FileStream and a StreamReader on the same file. Remove this line:

FileStream f1=new FileStream("c:\\file.xml",FileMode.Open);     

Upvotes: 2

Related Questions