diff --git a/Library/DiscUtils.Fat/Directory.cs b/Library/DiscUtils.Fat/Directory.cs index 05b3123c1..5e7b24709 100644 --- a/Library/DiscUtils.Fat/Directory.cs +++ b/Library/DiscUtils.Fat/Directory.cs @@ -532,6 +532,15 @@ private void PopulateNewChildDirectory(DirectoryEntry newEntry) // Populate new directory with initial (special) entries. First one is easy, just change the name! using var stream = new ClusterStream(FileSystem, FileAccess.Write, newEntry.FirstCluster, uint.MaxValue); + + // Clear cluster with zeroes in case it contains existing data from quick formatting + var blankCluster = new byte[FileSystem.ClusterSize]; + for (var cluster = 0; cluster < stream.Length / FileSystem.ClusterSize; cluster++) + { + stream.Write(blankCluster); + } + stream.Position = 0; + // First is the self-referencing entry... var selfEntry = new DirectoryEntry(newEntry, FatFileName.SelfEntryName); selfEntry.WriteTo(stream, FileSystem.FatOptions.FileNameEncodingTable); diff --git a/Tests/LibraryTests/Fat/FatFileSystemTest.cs b/Tests/LibraryTests/Fat/FatFileSystemTest.cs index 2afceb2e2..130a04534 100644 --- a/Tests/LibraryTests/Fat/FatFileSystemTest.cs +++ b/Tests/LibraryTests/Fat/FatFileSystemTest.cs @@ -582,4 +582,31 @@ public void TestFindPosition() Assert.True(pattern.SequenceEqual(buffer)); } + + [Fact] + public void CreateDirectoryWithExistingData() + { + const int highDensitySize = 1474560; + using var diskStream = new SparseMemoryStream(); + + byte[] existingData = [ + 0x00, 0x00, 0x00, 0x4E, 0x00, 0x0A, 0x7B, 0x9B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, + 0x00, 0x0A, 0x7B, 0xE9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0A, 0x7B, 0xEB, + ]; + + for (var i = 0; i < 1474560 / existingData.Length; i++) + { + diskStream.Seek(i * existingData.Length, SeekOrigin.Begin); + diskStream.Write(existingData, 0, existingData.Length); + } + + diskStream.Position = 0; + using var fs = FatFileSystem.FormatFloppy(diskStream, FloppyDiskType.HighDensity, "FLOPPY_IMG "); + + fs.CreateDirectory("dir"); + + var entries = fs.GetFileSystemEntries("dir").ToList(); + + Assert.Empty(entries); + } }