I have 2 programs: a C# GUI application and a C# windows service accessing the same text file;
a) the C# GUI application will write/append to the text file
b) the windows service will copy the file to a network location every 20 mins.
When the action happened concurrently, I got error message like below:
2014/09/08 21:15:56 mscorlib
The process cannot access the file 'C:\09082014.log' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamWriter.CreateFile(String path, Boolean append)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path, Boolean append)
at DataloggerUI.DataHelper.WriteDataLog(String msg, Int64& downTimeSince)
at DataloggerUI.Form1.ReceiveData(IAsyncResult asyncResult)
---- the C# windows service part is like below ----------
if (File.Exists(destination + @"\" + fi.Name))
{
FileInfo fi_dest = new FileInfo(destination + @"\" + fi.Name);
if (fi.LastWriteTime > fi_dest.LastWriteTime)
{
File.Copy(fi.FullName, destination + @"\" + fi.Name, true);
WriteLog("Send " + fi.FullName + " to server");
}
}
else
{
File.Copy(fi.FullName, destination + @"\" + fi.Name, true);
WriteLog("Send " + fi.FullName + " to server");
}
}
------- the C# windows GUI application code is like below -------
string logfile = DataHelper.GetAppConfigString("MPRS_LogDir") + @"\" + DateTime.Now.ToString("MMddyyyy") + ".log";
using (StreamWriter sw = new StreamWriter(logfile, true))
{
sw.WriteLine(tick + " " + "KYEC" + Environment.MachineName + " " + msg);
sw.Close();
}
The error message is thrown out by the GUI application. Was there any error or bad practice in my code?
------------ modified code to the following as per Peter's advice --------------
try
{
using (StreamWriter sw = new StreamWriter(logfile, true))
{
sw.WriteLine(tick + " " + "KYEC" + Environment.MachineName + " " + msg);
}
}
catch (IOException ex)
{
WriteErrorLog("IOException " + ex.Message);
System.Threading.Thread.Sleep(2000); //2 secs
using (StreamWriter sw = new StreamWriter(logfile, true))
{
sw.WriteLine(tick + " " + "KYEC" + Environment.MachineName + " " + msg);
}
}