[英]Why doesn't FileShare work as expected?
在編寫一些處理日志和文件的代碼時,我發現Windows文件io中有些令人困惑的行為。 有誰知道為什么該測試會失敗並顯示“無法讀取文件”消息?
[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");
}
您有var file =用FileAccess.Write打開,並且同時試圖以文件共享模式FileShare.Read打開var file3 =,不允許同時進行寫訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.