【发布时间】:2011-08-20 14:24:05
【问题描述】:
在编写一些处理日志和文件的代码时,我在 windows 文件 io.xml 中发现了一些令人费解的行为。有谁知道为什么这个测试会因“无法读取文件”消息而失败?
[TestMethod]
public void SouldAllowReads()
{
using (var file = File.Open(_path, FileMode.Create, FileAccess.Write, FileShare.Read))
{
using (var file2 = File.Open(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
//works ok, doesn't throw
}
try
{
using (var file3 = File.Open(_path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
//fails
}
}
catch (IOException)
{
Assert.Fail("cannot read file");
}
}
}
PS。 _path = Path.GetTempFileName();
编辑:
我会将 11 者的答案标记为正确的答案,但在这个设计中有一件事让我感到困扰。 .NET 方法,例如 File.ReadAllText(_path) 抛出异常,这是不应该发生的。
例如,这个剪断我的测试也会失败断言:
try
{
string text = File.ReadAllText(_path);
}
catch (IOException)
{
Assert.Fail("cannot read file");
}
【问题讨论】:
-
最后一个 sn-p 在什么情况下给你 IOexcpetion?
-
ReadAllText 抛出异常的事实已记录在案。如果操作失败,您希望/期望发生什么?