Can you just append to the file, rather than keeping track of where you are?
Object mLogLock = new Object(); //to make logging thread safe
string mLogFile = ""; //set your log location
string mLogDirectory = "";
public void HandleMessage(string inMessage)
{
lock (mLogLock)
{
if (!System.IO.Directory.Exists(mLogDirectory ))
{
System.IO.Directory.CreateDirectory(mLogDirectory );
}
String theMessage = DateTime.Now.ToString("s");
if (inMessage != null)
theMessage += " : " + inMessage;
StreamWriter sw = new StreamWriter(mLogFile, true);
sw.WriteLine(theMessage );
sw.Dispose();
sw.Close();
}
}
Otherwise, if you have a writer writing at one point and something else consuming, and you have no locking, then your program will corrupt your logs. That's just not even a question. You can try to lock your file by having the file opened for exclusive read/write by whatever wants to read or write to it, but then the other code will throw exceptions when it can't read it.
If the log file is in the same program, you can just keep all of the information in one large stream, like a MemoryStream, and use the StreamWriter as above instead (or as well as) to the MemoryStream. Then, your readers and writers can lock on the MemoryStream, rather than on the file itself. Would that help?