Search code examples
c#c++windowsbackupvolume-shadow-service

Reading a file without causing access denial to other processes


I've been thinking about writing a small specialized backup app, similar to newly introduced file history in Windows 8. The basic idea is to scan some directories every N hours for changed files and copy them to another volume. The problem is, some other apps may request access to these files while they are being backed up and get an access denial, potentially causing all kinds of nasty problems.

I far as i can tell, there are several approaches to that problem:

1) Using Volume Shadow Copy service

From my point of view, the future of this thing is uncertain and it's overhead during heavy IO loads may cripple the system.

2) Using Sharing Mode when opening files

Something like this mostly works...

using (var stream = new FileStream("test.txt", FileMode.Open, FileAccess.Read,
    FileShare.Delete | FileShare.ReadWrite | FileShare.Read | FileShare.Write))
{
    [Copy data]
}

... until some other process request access to the same file without FileShare.Read, at which point an IOException will be thrown.

3) Using Opportunistic Lock that may be "broken" by other (write?) requests.

This behaviour of FileIO.ReadTextAsync looks exactly like what I want, but it also looks very implementation-specific and may be changed in the future. Does someone knows, how to explicitly oplock a file locally via C# or C++?

Maybe there is some simple C# method like File.TryReadBytes that provides such "polite" reading? I'm interested in the solutions that will work on Windows 7 and above.


Solution

  • My vote's on VSS. The main reason is that it doesn't interfere with other processes modifying your files, thus it provides consistency. A possible inconsistency pretty much defeats the purpose of a backup. The API is stable and I wouldn't worry about its future.