Skip to content

Commit 2b3700f

Browse files
Use StreamReader when reading file contents (#576)
This mitigates issues when the file has a BOM. Fixes #464 Co-authored-by: Florian Greinacher <fgreinacher@users.noreply.github.com>
1 parent b54d77d commit 2b3700f

2 files changed

Lines changed: 22 additions & 3 deletions

File tree

System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllLinesTests.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,22 @@ public void MockFile_ReadAllLines_NotExistingFile_ThrowsCorrectFileNotFoundExcep
7070
Assert.That(exception.Message, Is.EqualTo("Could not find file '" + absentFileNameFullPath + "'."));
7171
}
7272

73+
[Test]
74+
public void MockFile_ReadAllLines_ShouldNotReturnBom()
75+
{
76+
// Arrange
77+
var testFilePath = XFS.Path(@"c:\a test file.txt");
78+
const string testText = "Hello World";
79+
var fileSystem = new MockFileSystem();
80+
fileSystem.File.WriteAllLines(testFilePath, new[] { testText }, Encoding.UTF8);
81+
82+
// Act
83+
var result = fileSystem.File.ReadAllLines(testFilePath, Encoding.UTF8);
84+
85+
// Assert
86+
Assert.That(result.Length, Is.EqualTo(1));
87+
Assert.That(result[0], Is.EqualTo(testText));
88+
}
7389
#if FEATURE_ASYNC_FILE
7490
[Test]
7591
public async Task MockFile_ReadAllLinesAsync_ShouldReturnOriginalTextData()

System.IO.Abstractions.TestingHelpers/MockFile.cs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -487,9 +487,12 @@ public override string[] ReadAllLines(string path, Encoding encoding)
487487
}
488488

489489
mockFileDataAccessor.GetFile(path).CheckFileAccess(path, FileAccess.Read);
490-
return encoding
491-
.GetString(mockFileDataAccessor.GetFile(path).Contents)
492-
.SplitLines();
490+
491+
using (var ms = new MemoryStream(mockFileDataAccessor.GetFile(path).Contents))
492+
using (var sr = new StreamReader(ms, encoding))
493+
{
494+
return sr.ReadToEnd().SplitLines();
495+
}
493496
}
494497

495498
public override string ReadAllText(string path)

0 commit comments

Comments
 (0)