Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 '<filename here>' 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?

like image 260
Arseni Mourzenko Avatar asked Dec 06 '10 23:12

Arseni Mourzenko


Video Answer


1 Answers

Nice question there. Have a look at this, it seems to suggest using FileShare.ReadWrite only is the key, it's worth a shot.

http://www.geekzilla.co.uk/viewD21B312F-242A-4038-9E9B-AE6AAB53DAE0.htm

like image 121
Tom Avatar answered Oct 21 '22 04:10

Tom