internal BotJournalFileWatcher(string directory, string fileName) { using (FileStream fs = new FileStream(Path.Combine(directory, fileName), FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite)) { field = BotJournalFileHelper.ReadFieldFromStream(fs); } fsWatcher = new FileSystemWatcher(directory); fsWatcher.NotifyFilter = NotifyFilters.LastWrite; fsWatcher.EnableRaisingEvents = true; fsWatcher.Changed += FsWatcher_Changed; watchingFilePath = Path.Combine(directory, fileName); }
/// <summary> /// Reacts to file change and process it. Changes can be 2 types: Field data edited, or last bot command (added/edited). /// If lastLine stays the same -> we update our field /// Else we update last command /// </summary> /// <param name="sender">Request sender</param> /// <param name="e"> EventArgs for this kind of event. </param> private void FsWatcher_Changed(object sender, FileSystemEventArgs e) { Console.WriteLine("BOT_FILE_WATCHER file edited"); if (e.FullPath != watchingFilePath) { return; } string fileContent; using (FileStream fs = new FileStream(watchingFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { StreamReader sr = new StreamReader(fs); fileContent = sr.ReadToEnd(); } string[] lines = fileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); if (lastLine.Equals(lines.Last())) { using (MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(fileContent))) { field = BotJournalFileHelper.ReadFieldFromStream(ms); } Console.WriteLine("field edited"); FieldEdited?.Invoke(this, new FieldChangedEventArgs(this.field, field)); } else { GameCommand command = BotJournalFileHelper.ParseGameCommand(lines.Last()); Console.WriteLine("command edited"); CommandEdited?.Invoke(this, new CommandChangedEventArgs(this.command, command)); this.command = command; lastLine = lines.Last(); } }