C# 可以读取不存在的文件吗?
我们有一些使用 StreamReader 从文本文件读取数据的 C# 代码。在一台计算机上,即使文本文件已被删除或替换为其他文本文件,我们也可以从该文本文件中读取数据 - File.Exists 调用会报告该文件存在,即使该文件不存在于 Windows 资源管理器中。但是,在另一台计算机上不会发生此行为。两台计算机都运行 Vista Business 和 .NET 2.0.50727 SP2。
我们尝试过重启机器,但没有解决。
有谁知道这如何可能以及有关可能解决方案的信息吗?
谢谢, 艾伦
We have some C# code that reads data from a text file using a StreamReader. On one computer we can read data from the text file even after it has been deleted or replaced with a different text file - the File.Exists call reports that the file exists even when it doesn't in Windows Explorer. However, on another computer this behaviour doesn't happen. Both computers are running Vista Business and .NET 2.0.50727 SP2.
We have tried restarting the machine without a resolution.
Does anyone have any understanding on how this could be possible and information about possible solutions?
Thanks,
Alan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 MSDN
Exists 方法不应该是用于路径验证,该方法仅检查路径中指定的文件是否存在。
请注意,在您调用 Exists 方法和对文件执行其他操作(例如删除)之间,另一个进程可能会对该文件执行某些操作。推荐的编程实践是将 Exists 方法以及对文件执行的操作包装在 try...catch 块中,如示例中所示。这有助于缩小潜在冲突的范围。 Exists 方法只能帮助确保文件可用,但不能保证文件可用。
From MSDN
The Exists method should not be used for path validation, this method merely checks if the file specified in path exists.
Be aware that another process can potentially do something with the file in between the time you call the Exists method and perform another operation on the file, such as Delete. A recommended programming practice is to wrap the Exists method, and the operations you take on the file, in a try...catch block as shown in the example. This helps to narrow the scope for potential conflicts. The Exists method can only help to ensure that the file will be available, it cannot guarantee it.
这可能是文件夹虚拟化问题吗?
Could this be a folder virtualization issue?
文件在删除之前是否已打开以供读取?如果是的话,即使文件系统已经释放了打开的文件,仍然能够读取它也就不足为奇了。
RE:
File.Exists()
:File.Exists
本质上容易出现竞争条件。它不应该用作在执行某些操作之前验证文件是否存在的唯一方式。此错误经常会导致软件中存在安全缺陷。相反,始终处理打开的实际文件操作等可能引发的异常,并在打开后验证您的输入。
Is the file being opened for reading before it's being deleted? If it is, it's not unexpected to still be able to read from the opened file even after the filesystem has otherwise let it go.
RE:
File.Exists()
:File.Exists
is inherently prone to race-conditions. It should not be used as the exclusive manner to verify that a file does or doesn't exist before performing some operation. This mistake can frequently result in a security flaw within your software.Rather, always handle the exceptions that can be thrown from your actual file operations that open, etc, and verify your input once it's open.