У меня есть 2 программы: приложение C# GUI и служба Windows C#, обращающиеся к одному и тому же текстовому файлу;Процесс не может получить доступ к файлу, потому что он используется другим процессом с использованием streamwriter
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.
Когда действие происходило одновременно, я получил сообщение об ошибке, как показано ниже:
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)
---- часть C# Windows сервис, как показано ниже ----------
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");
}
}
------- C# код окна приложения GUI как ниже -------
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();
}
Сообщение об ошибке высылается приложением GUI. Какая у вас ошибка или плохая практика?
------------ модифицированный код к следующему согласно совету Петра --------------
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);
}
}
Как служба windows принимает решение о начале копирования файла? Пожалуйста, объясните процедуру или покажите больше кода. –
Ошибка говорит, что файл использовался. Не так ли? Возможно, он копируется, когда GUI хочет добавить что-то еще. – luk32
Привет luk32, да, ошибка произошла, когда графический интерфейс добавляется к файлу, а служба Windows пыталась его скопировать. Могу ли я избежать этого исключения? как определить, используется ли файл перед добавлением? также, используя оператор C# 'using', исключение будет обработано уже? – sqr