Created
October 12, 2012 13:17
-
-
Save MrZoidberg/3879152 to your computer and use it in GitHub Desktop.
C# FileStream Lock. How to wait for a file to get released and lock safely.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static FileStream OpenFileWithRetry(string path, FileMode mode, FileAccess fileAccess, FileShare fileShare) | |
{ | |
ArgumentsChecker.ArgumentNotNull(path, "path"); | |
var autoResetEvent = new AutoResetEvent(false); | |
while (true) | |
{ | |
try | |
{ | |
using (FileStream fileStream = new FileStream(path, mode, fileAccess, fileShare)) | |
{ | |
return fileStream; | |
} | |
} | |
catch (IOException ex) | |
{ | |
int win32Error = Marshal.GetLastWin32Error(); | |
Logger.TraceException(String.Format("Cannot open file {0}. Win32 error: {1}", path, win32Error), ex); | |
if (win32Error == ERROR_SHARING_VIOLATION) | |
{ | |
using ( | |
var fileSystemWatcher = new FileSystemWatcher(Path.GetDirectoryName(path), | |
"*" + Path.GetExtension(path)) | |
{ | |
EnableRaisingEvents = true | |
}) | |
{ | |
fileSystemWatcher.Changed += | |
(o, e) => | |
{ | |
if (Path.GetFullPath(e.FullPath) == Path.GetFullPath(path)) | |
{ | |
autoResetEvent.Set(); | |
} | |
}; | |
autoResetEvent.WaitOne(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment