While writing some code dealing with logs and files, I’ve discovered some baffling behaviour in windows file io. Does anyone know why this test would fail with “cannot read file” message?
[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();
EDIT:
I’ll mark elevener answer as correct one, but there is one thing that bothers me in this design. .NET methods such as File.ReadAllText(_path) throw exceptions, which just shouldn’t happen.
For example this snipped my test would also fail assertion:
try
{
string text = File.ReadAllText(_path);
}
catch (IOException)
{
Assert.Fail("cannot read file");
}
You have var file = open with FileAccess.Write and at the same time are trying to open var file3 = with fileshare mode FileShare.Read that doesn’t allows concurrent write access.