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

문제

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?

도움이 되었습니까?

해결책

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();
}

다른 팁

Or you can nullify the writer object after closing.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top