示例#1
0
 /// <summary>
 /// Try to open a file for exclusive read/write access
 /// </summary>
 /// <param name="filename">Path to file</param>
 /// <returns>A <see cref="Stream"/> for the opened file, or <see langword="null"/> on failure to open the file.</returns>
 public static Stream FileOpenExclusive(string filename)
 {
     for (int attempts = 0; attempts < 10; ++attempts)
     {
         try {
             return(File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None));
         } catch (IOException e) {
             _log.TraceExceptionMethodCall(e, "FileOpenExclusive", filename, attempts);
         } catch (UnauthorizedAccessException e) {
             _log.TraceExceptionMethodCall(e, "FileOpenExclusive", filename, attempts);
         }
         AsyncUtil.Sleep(((attempts + 1) * Randomizer.Next(100)).Milliseconds());
     }
     return(null);
 }