How to read a file which is currently used, like Windows does when copying it?

One of my applications is intended to read (and only read) files which may be in use.

But, when reading a file which is already opened in, for example, Microsoft Word, this application throws a System.IO.IOException:

The process cannot access the file '' because it is being used by another process.

The code used to read the file is:

using (Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
    // Do stuff here.
}

Of course, since the file is already used, this exception is expected.

Now, if I ask the operating system to copy the file to a new location, then to read it, it works:

string tempFileName = Path.GetTempFileName();
File.Copy(fileName, tempFileName, true);
//                                         ↓ We read the newly created file.
using (Stream stream = new FileStream(tempFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
    // Do stuff here.
}

What is the magic of File.Copy which allows to read the file already used by an application, and especially how to use this magic to read the file without making a temporary copy?

8
задан Arseni Mourzenko 6 December 2010 в 23:04
поделиться