6
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?

gdoron
  • 147,333
  • 58
  • 291
  • 367

4 Answers4

9

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.

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • I had this problem , please note that you should 'Close' the stream before 'Disposing' – Mironline Mar 28 '12 at 10:42
  • @Mironline. That is being done automatically. read **all** of my answer... you can see what is Dispose doing [here](http://stackoverflow.com/a/911431/601179) – gdoron Mar 28 '12 at 10:46
2

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

FileStream f1=new FileStream("c:\\file.xml",FileMode.Open);     
Alexandre
  • 4,382
  • 2
  • 23
  • 33
2

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

David
  • 72,686
  • 18
  • 132
  • 173
1

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.

Brian Warfield
  • 367
  • 1
  • 11