While writing a file in a single thread application, I get the error
"The process cannot access the file because it is being used by another process".
I open all writer objects in the using keyword. Although it is a single thread, I lock functions every time with ReaderWriterLockSlim and unlock them when I'm done. However, I am getting an error. Anything on your mind?
There are only these two functions that communicate with the file. One is appending, the other is cleaning the file.
public void WriteToFileThreadSafe(string text, string fileName)
{
string path = ApplicationDirectory + "/" + fileName;
_readWriteLock.EnterWriteLock();
try
{
if (File.Exists(path))
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(text);
sw.Close();
}
}
}
finally
{
_readWriteLock.ExitWriteLock();
}
}
public void ClearTextFile(string fileName)
{
string path = ApplicationDirectory + "/" + fileName;
_readWriteLock.EnterWriteLock();
try
{
using (FileStream sw = File.Create(path))
{
sw.Close();
}
}
finally
{
_readWriteLock.ExitWriteLock();
}
}