Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File-Stream is being used by another process

Tags:

c#

.net

file

stream

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?

like image 240
Артём Царионов Avatar asked Dec 10 '22 01:12

Артём Царионов


1 Answers

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.

like image 53
gdoron is supporting Monica Avatar answered Dec 11 '22 14:12

gdoron is supporting Monica