Writing to ASP.NET C # files and NOT blocking them later

I get this error: the process cannot access the file (...) because it is being used by another process. I tried using File.WriteAllText ;

 StreamWriter sw = new StreamWriter(myfilepath); sw.Write(mystring); sw.Close(); sw.Dispose(); 

;

 using (FileStream fstr = File.Create(myfilepath)) { StreamWriter sw = new StreamWriter(myfilepath); sw.Write(mystring); sw.Close(); sw.Dispose(); fstr.Close(); } 

All I'm trying to do is access the file, write on it, and then close it. I could make a stupid mistake, but I would like to understand what I am doing wrong and why. How to make sure that the file is closed and does not cause this error.

Answers helped so far I did this:

 using (FileStream fstr = File.Open(myfilepath,FileMode.OpenOrCreate,FileAccess.ReadWrite)) { StreamWriter sw = new StreamWriter(fstr); sw.Write(mystring); sw.Close(); } 

This seems to be better because it seems to close / stop the process of my file if I try to access another file the second time I access the page. But if I try to access the same file a second time, it will again give me an error.

+4
source share
4 answers

I want to thank everyone for their help. In fact, in addition to this code, I found out that I had a stremReader that was still open somewhere else after the code above. In the end, I changed the code I had before:

 using (FileStream fstr = File.Open(myfile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { StreamWriter sw = new StreamWriter(fstr); sw.Write(mystring); sw.Flush(); sw.Dispose(); } 

and on my StreamReader I did this:

 StreamReader sr = new StreamReader(myfile); string sometext = sr.ReadToEnd(); sr.Dispose(); 

I could also use this:

 File.ReadAllText(myfile); 

If there is anything that I could do better, please tell me. Thank you very much.

+1
source

Why not just use:

 System.IO.File.WriteAllText(myfilepath, mystring"); 

This should not lock your file.

Internall WriteAllText uses FileShare.Read and releases the lock as soon as it is done.

+3
source

"because it is being used by another process," that is the key. Did you accidentally open a file in Notepad or something?

You may need to set the sharing mode when you open the file to allow reading, and request only the required permission (write access).

+2
source

try it

 FileStream fs = new FileStream(myfilepath, FileMode.Create, FileAccess.Write); byte[] bt = System.Text.Encoding.ASCII.GetBytes(mystring); fs.Write(bt, 0, bt.Length); fs.Close(); 
0
source

All Articles