开发者

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(fileNa开发者_如何学编程me, 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?


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


try removing FileShare.ReadWrite | FileShare.Delete from the FileStream constructor, or at least FileShare.Delete.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜