Siemka!
Mam usługę, która robi kopie zapasową bazy MSSQL o określonej godzinie. Za timer wykorzystałem TaskSchedulerEngine
. Konfiguracja jest zapisana w pliku .xml, deserializuję ją podczas uruchamiania usługi i ustawiam odpowiednio timer. Potrzebuje aktualizować konfigurację w trakcie pracy usługi. Na tą chwilę żeby nowe ustawienia zostały wczytane muszę usługę uruchomić ponownie.
Zrobiłem sobie sprawdzanie zmian w pliku:
FileSystemWatcher systemWatcher = new FileSystemWatcher(Methods.DefaultBackupPath);
systemWatcher.NotifyFilter = NotifyFilters.LastWrite;
systemWatcher.Filter = "config.xml";
systemWatcher.Changed += SystemWatcher_Changed;
systemWatcher.EnableRaisingEvents = true;
private void SystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
try
{
MainConfig mc = Methods.DeserializeXML<MainConfig>(Methods.ConfigFilePath);
if (mc.Time.Hour != c.Time.Hour || mc.Time.Minute != c.Time.Minute || mc.Time.Second != c.Time.Second)
{
c = mc;
Schedule s = new Schedule().AtHours(c.Time.Hour).AtMinutes(c.Time.Minute).AtSeconds(c.Time.Second).WithLocalTime().Execute<BackupTask>(c);
SchedulerRuntime.UpdateSchedule(s);
}
}
catch (Exception ex)
{
LOG.WriteError(ex);
}
}
Te funkcje są wykorzystywane tylko kiedy zmieni się godzina wywołania kopii, inne zmiany są sprawdzane podczas robienia już kopii.
Dostaje wyjątek:
FUNCTION: WinIOError MESSAGE: Proces nie może uzyskać dostępu do pliku „C:\ProgramData\OptimoBackup\config.xml”, ponieważ jest on używany przez inny proces. SOURCE mscorlib HRESULT: -2147024864 STACKTRACE:
w System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
w 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, Boolean useLongPath, Boolean checkHost)
w System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
w System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
w System.IO.StreamReader..ctor(String path, Encoding encoding)
w OptimoBackup.Classes.Methods.DeserializeXML[T](String filePath)
w OptimoBackup.OptimoBackup.SystemWatcher_Changed(Object sender, FileSystemEventArgs e)
Serializacja i deserializacja
public static void SerializeXML<T>(T obj, string filePath)
{
XmlSerializer xml = new XmlSerializer(typeof(T));
using (TextWriter tw = new StreamWriter(filePath))
{
xml.Serialize(tw, obj);
}
}
public static T DeserializeXML<T>(string filePath)
{
T obj;
XmlSerializer xml = new XmlSerializer(typeof(T));
using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8))
{
obj = (T)xml.Deserialize(sr);
}
return obj;
}