The process can not access the file 'directory\file' because it is being used by another process in C# File Writer

StackOverflow https://stackoverflow.com/questions/4112674

Question

I receive this error when ever I attempt to save on the existing file:

the process can not access the file because it is being used by another process

It works when a file doesn't exist, but when I attempt to write in it again the error shows up. I'm not accessing or using the file that time.

here is the code:

string directory = filepath + "Updates\\" + dir;
if(!Directory.Exists(directory))
{
    Directory.CreateDirectory(directory);
}
remarks = remarks.Trim();
remarks = remarks.Replace("\r\n","<br>");
remarks = remarks.Replace(",","|");
string file = directory + "\\" +  getIndex(barcode) + ".asdt";
StreamWriter writer = new StreamWriter(file,true);
writer.WriteLine(username + "," + barcode + "," + DateTime.Now.ToString("yyyy-MM-dd HH.mm")+ "," + remarks);
writer.Close();

When I checked it the error occurs on the line:

StreamWriter writer = new StreamWriter(file,true);

what could be the cause of this?

Was it helpful?

Solution

Your program is probably not disposing of the file stream properly, keeping the file open.

Use the using statement to ensure proper disposal:

using(StreamWriter writer = new StreamWriter(file,true))
{
    writer.WriteLine(username + "," + barcode + "," + DateTime.Now.ToString("yyyy-MM-dd HH.mm")+ "," + remarks);
    writer.Close();
}

OTHER TIPS

Or you can nullify the writer object after closing.

try to use writer.Flush(); before writer.Close();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top