Skip to content

Directory.Move throws when destination not exist #12880

Description

@Daniel-Garmig

Description

Directory.Move() method seems to fail and throw a System.IO.DirectoryNotFoundException when destination path don't exist.

The docs contains the following information about when this exception is thrown (https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.move?view=net-10.0#exceptions):

DirectoryNotFoundException

The path specified by sourceDirName is invalid (for example, it is on an unmapped drive).

This exception is only expected when sourceDirectory is not found, but it's thrown when destination is not found as well.

In issue dotnet/runtime#50833 a fix was applied to remove the path from the exception message as source directory was shown even when was the destination was the error.

This may be resolved by:

  • Changing Directory.Move behavior so destination directory is created (probably quite dangerous?). It can be included as a new overload while been disabled by default (to maintain current behavior).
  • Updating the docs to include this exception and to remark that the destination path must exists (probably a issue should be open in docs repo?).

Update:

I just notice that File.Move() has the same problem.
The docs for this method do mention that DirectoryNotFoundException will be thrown when "destFileName is invalid". It should remark that a "non-existent" destination is considered "invalid".


Reproduction Steps

Can be tested with the following:

using System.IO;

try
{
    // cleanup
    Directory.Delete("dst", true);
}
catch { }
Directory.CreateDirectory("src");
Directory.Move("src", "dst/dst"); // dst/dst is nested and doesn't exist ; move failure

Running this the following exception is thrown:

Unhandled exception. System.IO.DirectoryNotFoundException: Could not find a part of the path.
at System.IO.FileSystem.MoveDirectory(String sourceFullPath, String destFullPath, Boolean _)
at System.IO.FileSystem.MoveDirectory(String sourceFullPath, String destFullPath)
at Program.

$(String[] args) in c:\Dev\tests\dotnet\dirMovTest.cs:line 10

Expected behavior

The directory will be moved to the destination folder. If destination don't exists, it should be created.

Actual behavior

Directory.Move() throws when moving to a non-existent destination path.

Regression?

This was already the behavior in issue dotnet/runtime#50833 (.NET 5).

Known Workarounds

A check must be implemented when using Directory.Move() to create destination path if don't exists.

Configuration

.NET 10.0.103 - Windows 11 (x64).

Other information

No response

Metadata

Metadata

Labels

area-System.IOuntriagedNew issue has not been triaged by the area owner

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions