@@ -126,15 +126,16 @@ public LogWriter(LogLevel minimumLogLevel, string logFilePath, bool deleteExisti
126126 logFilePath ) ;
127127 }
128128
129- // Open the log file for writing with UTF8 encoding
130- this . textWriter =
131- new StreamWriter (
132- new FileStream (
133- logFilePath ,
134- deleteExisting ?
135- FileMode . Create :
136- FileMode . Append ) ,
137- Encoding . UTF8 ) ;
129+ if ( ! this . TryOpenLogFile ( logFilePath , deleteExisting ) )
130+ {
131+ // If the log file couldn't be opened at this location,
132+ // try opening it in a more reliable path
133+ this . TryOpenLogFile (
134+ Path . Combine (
135+ Environment . GetFolderPath ( Environment . SpecialFolder . LocalApplicationData ) ,
136+ Path . GetFileName ( logFilePath ) ) ,
137+ deleteExisting ) ;
138+ }
138139 }
139140
140141 public void Write (
@@ -144,7 +145,8 @@ public void Write(
144145 string callerSourceFile = null ,
145146 int callerLineNumber = 0 )
146147 {
147- if ( logLevel >= this . minimumLogLevel )
148+ if ( this . textWriter != null &&
149+ logLevel >= this . minimumLogLevel )
148150 {
149151 // Print the timestamp and log level
150152 this . textWriter . WriteLine (
@@ -176,5 +178,39 @@ public void Dispose()
176178 this . textWriter = null ;
177179 }
178180 }
181+
182+ private bool TryOpenLogFile (
183+ string logFilePath ,
184+ bool deleteExisting )
185+ {
186+ try
187+ {
188+ // Open the log file for writing with UTF8 encoding
189+ this . textWriter =
190+ new StreamWriter (
191+ new FileStream (
192+ logFilePath ,
193+ deleteExisting ?
194+ FileMode . Create :
195+ FileMode . Append ) ,
196+ Encoding . UTF8 ) ;
197+
198+ return true ;
199+ }
200+ catch ( Exception e )
201+ {
202+ if ( e is UnauthorizedAccessException ||
203+ e is IOException )
204+ {
205+ // This exception is thrown when we can't open the file
206+ // at the path in logFilePath. Return false to indicate
207+ // that the log file couldn't be created.
208+ return false ;
209+ }
210+
211+ // Unexpected exception, rethrow it
212+ throw ;
213+ }
214+ }
179215 }
180216}
0 commit comments