I have an exe that gets called multiple times per second and within that exe, there is a function that writes to a textfile as a log.
This is my Logging class:
public static class Log
{
private static ReaderWriterLockSlim lock_ = new ReaderWriterLockSlim();
public static void Output(string Input)
{
string MyDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string logPath = @MyDocuments + "\\SCV";
lock_.EnterWriteLock();
Directory.CreateDirectory(logPath);
string logFilePath = @logPath+"\\SCVLog -" + DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
FileInfo logFileInfo = new FileInfo(logFilePath);
DirectoryInfo logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
try
{
using (FileStream fileStream = new FileStream(logFilePath, FileMode.Append))
{
using (StreamWriter log = new StreamWriter(fileStream))
{
log.WriteLine(Input);
}
}
}
finally
{
lock_.ExitWriteLock();
}
}
}
This is how I call it:
Log.Output(finalFile + " processed");
It seems like the logging class is thread safe, however, I still get this error:
The process cannot access the file because it is being used by another process
What else do I need to do to make this thread safe?
ReaderWriterLockSlimwould point to the fact your are, otherwise you would use another synchronization primitive.. And if you are, are you sure you are opening the file in the correct share mode. In short I think this question maybe lacking some vital informationlock