diff --git a/csharp/Platform.IO.Tests/FileHelpersTests.cs b/csharp/Platform.IO.Tests/FileHelpersTests.cs index 3bdba03..88ab8df 100644 --- a/csharp/Platform.IO.Tests/FileHelpersTests.cs +++ b/csharp/Platform.IO.Tests/FileHelpersTests.cs @@ -15,5 +15,33 @@ public void WriteReadTest() Assert.Equal(readValue, originalValue); File.Delete(temporaryFile); } + + [Fact] + public void ReadFirstOrDefaultShouldReturnDefaultForMisalignedFile() + { + var temporaryFile = Path.GetTempFileName(); + // Write 5 bytes to create a file that's not aligned to ulong (8 bytes) + File.WriteAllBytes(temporaryFile, new byte[] { 1, 2, 3, 4, 5 }); + + // This should return default(ulong) = 0, not throw an exception + var result = FileHelpers.ReadFirstOrDefault(temporaryFile); + Assert.Equal(0UL, result); + + File.Delete(temporaryFile); + } + + [Fact] + public void ReadLastOrDefaultShouldReturnDefaultForMisalignedFile() + { + var temporaryFile = Path.GetTempFileName(); + // Write 5 bytes to create a file that's not aligned to ulong (8 bytes) + File.WriteAllBytes(temporaryFile, new byte[] { 1, 2, 3, 4, 5 }); + + // This should return default(ulong) = 0, not throw an exception + var result = FileHelpers.ReadLastOrDefault(temporaryFile); + Assert.Equal(0UL, result); + + File.Delete(temporaryFile); + } } } diff --git a/csharp/Platform.IO/FileHelpers.cs b/csharp/Platform.IO/FileHelpers.cs index fd412a3..00c65dd 100644 --- a/csharp/Platform.IO/FileHelpers.cs +++ b/csharp/Platform.IO/FileHelpers.cs @@ -85,7 +85,7 @@ private static FileStream GetValidFileStreamOrDefault(string path, int elementSi var fileSize = GetSize(path); if (fileSize % elementSize != 0) { - throw new InvalidOperationException($"File is not aligned to elements with size {elementSize}."); + return null; } return fileSize > 0 ? File.OpenRead(path) : null; }