如何读取当前正在使用的文件,就像 Windows 复制文件时那样?
我的应用程序之一旨在读取(并且仅读取)可能正在使用的文件。
但是,当读取已在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好问题。看看这个,似乎建议仅使用 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
尝试删除 FileShare.ReadWrite | FileStream 构造函数中的 FileShare.Delete,或者至少是 FileShare.Delete。
try removing
FileShare.ReadWrite | FileShare.Delete
from the FileStream constructor, or at least FileShare.Delete.