如何读取当前正在使用的文件,就像 Windows 复制文件时那样?

发布于 2024-10-06 00:39:19 字数 879 浏览 0 评论 0原文

我的应用程序之一旨在读取(并且仅读取)可能正在使用的文件。

但是,当读取已在 Microsoft Word 等中打开的文件时,此应用程序会抛出 System.IO.IOException:

进程无法访问文件“<文件名>”因为它正在被另一个进程使用。

用于读取该文件的代码是:

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

当然,由于该文件已被使用,因此出现此异常是预料之中的。

现在,如果我要求操作系统将文件复制到新位置,然后读取它,它就会起作用:

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.
}

File.Copy 的魔力是什么,它允许读取已被使用的文件应用程序,特别是如何使用这个魔法来读取文件而不制作临时副本?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空气里的味道 2024-10-13 00:39:19

好问题。看看这个,似乎建议仅使用 FileShare.ReadWrite 是关键,值得一试。

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

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

热风软妹 2024-10-13 00:39:19

尝试删除 FileShare.ReadWrite | FileStream 构造函数中的 FileShare.Delete,或者至少是 FileShare.Delete。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文