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();
}
或者,您可以在关闭后使writer对象无效。
try to use writer.Flush();
before writer.Close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.