Die Events werden nahezu parallel gefeuert. Das merke ich daran, dass ich, sobald sich eine Datei ändert, ich die Datei anzeigen möchte.
Oft erhalte ich aber eine Exception, weil bereits ein StreamReader die Datei geöffnet hat.
Hier mal mein Quellcode:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85:
| public partial class Form1 : Form { #region Fiels private FileInfo _OpenedFile; private FileSystemWatcher _FileSystemWatcher; #endregion
#region Constructors public Form1() { InitializeComponent(); } #endregion
#region Private Methods private void ShowFile(string filePath) { InvokeIfRequired(this.textBoxFileContent, (MethodInvoker)delegate() { for (int i = 0; i < 5; i++) { try { using (StreamReader sr = new StreamReader(filePath)) { this.textBoxFileContent.Text = sr.ReadToEnd(); sr.Close(); } break; } catch (IOException) { System.Threading.Thread.Sleep(50); } } }); }
private void InvokeIfRequired(Control target, Delegate methodToInvoke) { if (target.InvokeRequired) { target.Invoke(methodToInvoke); } else { methodToInvoke.DynamicInvoke(); } } #endregion
private void buttonOpenFile_Click(object sender, EventArgs e) { string filePath = textBoxFilePath.Text;
if (File.Exists(filePath) == true) { this._OpenedFile = new FileInfo(filePath);
this._FileSystemWatcher = new FileSystemWatcher() { Path = this._OpenedFile.DirectoryName, Filter = this._OpenedFile.Name, NotifyFilter = NotifyFilters.Attributes, IncludeSubdirectories = false, EnableRaisingEvents = true, }; this._FileSystemWatcher.Changed += new FileSystemEventHandler(this._FileSystemWatcher_Changed);
this.ShowFile(this._OpenedFile.FullName); } }
void _FileSystemWatcher_Changed(object sender, FileSystemEventArgs e) { this.ShowFile(this._OpenedFile.FullName); } } |
Wenn ich auf den Button klicke, wird die Datei angezeigt.
Bei Änderung soll die Anzeige aktualisiert werden.
Problem ist nur, dass das Event 2x gefeuert wird.
Mit
NotifyFilter = NotifyFilters.Size
wird das Event nur 1x gefeuert.
Aber ich bekomme dann nicht mit, wenn sich die Datei ändert, jedoch die Größe konstant bleibt.
Grüße Peter