Skip to content

Fix DirectoryInfo.CreateSubdirectory for root directories #117519

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

Copilot
Copy link
Contributor

@Copilot Copilot AI commented Jul 10, 2025

DirectoryInfo.CreateSubdirectory was incorrectly throwing ArgumentException when called on root directories (like "/" on Unix or "C:\" on Windows), preventing users from creating subdirectories under the filesystem root.

Problem

The validation logic in CreateSubdirectory expected that the character immediately following the current directory path would be a directory separator when validating that the new path is a proper subdirectory. However, for root directories, Path.Combine produces paths where this character is actually the first letter of the subdirectory name, not a separator.

For example:

  • Current path: "/"
  • Subdirectory: "test"
  • Combined path: "/test"
  • Character at position 1: 't' (not a directory separator)

This caused the validation to fail and throw: "The directory specified, 'test', is not a subdirectory of '/'"

Solution

Added a special case in the validation logic to allow subdirectory creation when the current path is a root directory by checking PathInternal.IsRoot(trimmedCurrentPath). This preserves all existing security validations while enabling the legitimate use case of creating subdirectories under root directories.

Testing

  • ✅ All existing CreateSubdirectory tests continue to pass (15/15)
  • ✅ All DirectoryInfo tests pass (1575 passed, 17 skipped)
  • ✅ Added new test case that verifies root directory subdirectory creation
  • ✅ Security validations remain intact (parent traversal, rooted paths still properly rejected)
  • ✅ Edge cases work correctly (trailing separators, nested paths, etc.)

The fix is minimal and surgical, changing only the specific validation condition while preserving all existing behavior.

Fixes #116087.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copy link
Contributor

Tagging subscribers to this area: @dotnet/area-system-io
See info in area-owners.md if you want to be subscribed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

DirectoryInfo.CreateSubdirectory fails when DirectoryInfo path is a root directory
3 participants