Skip to content

fix: keep existing parent directories when creating a subdirectory - #1612

Open
Esquetta wants to merge 1 commit into
TestableIO:mainfrom
Esquetta:fix/directory-times-839
Open

Esquetta wants to merge 1 commit into
TestableIO:mainfrom
Esquetta:fix/directory-times-839

Conversation

@Esquetta

Copy link
Copy Markdown

Related to #839.

Problem

Creating a directory resets the existing parent directories. Their creation, last access and last write times go back to the current time, and their attributes are lost:

var fileSystem = new MockFileSystem();
fileSystem.Directory.CreateDirectory(@"c:\foo\bar");
fileSystem.Directory.SetLastWriteTimeUtc(@"c:\foo\bar", new DateTime(2001, 2, 3));

fileSystem.Directory.CreateDirectory(@"c:\foo\bar\baz");

fileSystem.Directory.GetLastWriteTimeUtc(@"c:\foo\bar"); // now, not 2001-02-03

AddDirectory checks each parent with DirectoryExistsWithoutFixingPath(segment), where segment ends with a separator (c:\foo\bar\). Entries are stored without one (SetEntry trims it), so the check never finds an existing parent and every parent is replaced by a new MockDirectoryData. The same happens when AddFile creates the parent directories of a new file.

Change

Trim the separator before the existence check. Drive roots are kept as they are by TrimSlashes.

Tests

Two tests in MockDirectoryTests: times and attributes of an existing parent are kept after creating a subdirectory. Both fail without the change. The full solution passes on Windows (net472, net8.0, net9.0, net10.0, net11.0).

Note on #839

The repro in the issue (set LastWriteTime on a DirectoryInfo, read it from EnumerateDirectories) already passes on main. I compared the mock with NTFS while looking at it: creating or deleting an entry updates the parent's last write and last access time on NTFS, and the mock never does that for directories, which is the directory side of what #875 did for files. If you want that too, I can do it in a separate PR; it is OS-specific for last access time, as discussed in the issue.

AddDirectory checked each parent with a trailing separator, but entries are stored without one, so every existing parent was replaced by a new MockDirectoryData. Creating a subdirectory therefore reset the parent's times and attributes.
@mergify

mergify Bot commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request once it meets the queue conditions

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant