1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . IO ;
4+ using System . Linq ;
5+ using System . Threading ;
6+
17namespace EliteAPI . Watcher ;
28
39public class FileWatcher
@@ -68,8 +74,15 @@ private void StartWatching()
6874
6975 _fileWatcher . Changed += ( sender , args ) =>
7076 {
71- Thread . Sleep ( 50 ) ;
72- HandleFileChange ( ) ;
77+ try
78+ {
79+ Thread . Sleep ( 50 ) ;
80+ HandleFileChange ( ) ;
81+ }
82+ catch
83+ {
84+ // Silently ignore exceptions to prevent crashes
85+ }
7386 } ;
7487
7588 _fileWatcher . EnableRaisingEvents = true ;
@@ -79,17 +92,33 @@ private void HandleFileChange()
7992 {
8093 if ( _onContentChanged == null ) return ;
8194
82- if ( _mode == FileWatchMode . LineByLine )
95+ try
8396 {
84- var lines = ReadFileLines ( _file . FullName ) ;
85- for ( int i = _lastLineCount ; i < lines . Length ; i ++ )
86- _onContentChanged ( lines [ i ] ) ;
87- _lastLineCount = lines . Length ;
97+ if ( _mode == FileWatchMode . LineByLine )
98+ {
99+ var lines = ReadFileLines ( _file . FullName ) ;
100+ for ( int i = _lastLineCount ; i < lines . Length ; i ++ )
101+ {
102+ try
103+ {
104+ _onContentChanged ( lines [ i ] ) ;
105+ }
106+ catch
107+ {
108+ // Continue processing other lines even if one fails
109+ }
110+ }
111+ _lastLineCount = lines . Length ;
112+ }
113+ else
114+ {
115+ var content = ReadFileContent ( _file . FullName ) ;
116+ _onContentChanged ( content ) ;
117+ }
88118 }
89- else
119+ catch
90120 {
91- var content = ReadFileContent ( _file . FullName ) ;
92- _onContentChanged ( content ) ;
121+ // Silently ignore exceptions to prevent crashes
93122 }
94123 }
95124
@@ -108,17 +137,24 @@ private void SetupDirectoryWatcher()
108137
109138 private void OnFileInDirectoryChanged ( object sender , FileSystemEventArgs e )
110139 {
111- Thread . Sleep ( 100 ) ;
112-
113- var changedFile = new FileInfo ( e . FullPath ) ;
114-
115- // Only switch if the changed file matches the pattern, is newer than current, and is not the current file
116- if ( _filePattern != null &&
117- MatchesPattern ( changedFile . Name , _filePattern ) &&
118- changedFile . FullName != _file . FullName &&
119- changedFile . LastWriteTimeUtc > _file . LastWriteTimeUtc )
140+ try
141+ {
142+ Thread . Sleep ( 100 ) ;
143+
144+ var changedFile = new FileInfo ( e . FullPath ) ;
145+
146+ // Only switch if the changed file matches the pattern, is newer than current, and is not the current file
147+ if ( _filePattern != null &&
148+ MatchesPattern ( changedFile . Name , _filePattern ) &&
149+ changedFile . FullName != _file . FullName &&
150+ changedFile . LastWriteTimeUtc > _file . LastWriteTimeUtc )
151+ {
152+ SwitchToNewFile ( changedFile ) ;
153+ }
154+ }
155+ catch
120156 {
121- SwitchToNewFile ( changedFile ) ;
157+ // Silently ignore exceptions to prevent crashes
122158 }
123159 }
124160
0 commit comments