Skip to content

Instantly share code, notes, and snippets.

@MrZoidberg
Created October 12, 2012 13:17
Show Gist options
  • Save MrZoidberg/3879152 to your computer and use it in GitHub Desktop.
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.
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