Skip to content

MockFileStream unexpected behavior when used via BinaryWriter #519

@RThomasHyde

Description

@RThomasHyde

Using the latest stable NuGet version (7.0.7)

If I initialize a BinaryWriter with a MockFileStream (obtained e.g. by using MockFileSystem.File.Create), and then manipulate it via BinaryWriter.BaseStream, I get unexpected behavior. For instance, examine the following:

var fileSystem = new MockFileSystem();
using (var s = fileSystem.File.Create(@"C:\testfile.bin"))
using (var writer = new System.IO.BinaryWriter(s))
{
    writer.Write(new byte[400], 0, 400);
    writer.BaseStream.Seek(200, System.IO.SeekOrigin.Begin);
    Console.WriteLine(writer.BaseStream.Position);   // prints 400, expect 200
    Console.WriteLine(s.Position); // prints 400, expect 200
}

Presumably this is because BinaryWriter.BaseStream calls Flush on the underlying stream before returning it, though it's not immediately clear to me why this should be a problem. Avoiding accessing BaseStream by calling e.g. writer.Seek directly does avoid the problem, but the point is that MockFileStream does not replicate the behavior of a real FileStream in this regard:

using (var s = System.IO.File.Create(@"C:\testfile.bin")
using (var writer = new System.IO.BinaryWriter(s))
{
    writer.Write(new byte[400], 0, 400);
    writer.BaseStream.Seek(200,  System.IO.SeekOrigin.Begin);
    Console.WriteLine(writer.BaseStream.Position);   // prints 200 as expected
    Console.WriteLine(s.Position); // prints 200 as expected
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: testinghelpersIssues that address the testing helpersstate: ready to pickIssues that are ready for being worked ontype: bugIssues that describe misbehaving functionality

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions