runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Win32FileSystem File.Move is inconsistent with its Exception throws

Open ianhays opened this issue 11 years ago • 4 comments

There is an inconsistent behavior in File.Move with regards to non existent directories in paths that is present in both the desktop and core frameworks.

If the parent directory of the source file is nonexistent, a FileNotFoundException is thrown. If the parent directory of the dest file is nonexistent, a DirectoryNotFoundException is thrown. Example:

File.Create("test1").Dispose();
File.Move(Path.Combine(Directory.GetCurrentDirectory(), "test2", "test3"), "test4"); // throws a FileNotFoundException
File.Move("test1", Path.Combine(Directory.GetCurrentDirectory(), "test2", "test3")); // throws a DirectoryNotFoundException

The reason for this is that File.Move makes a call to "InternalExists" to check that the sourceFile exists in full and if it doesn't then a FileNotFoundException is thrown regardless of which part of the path caused the failure. Removing this check is simple and will leave path checking to the FileSystem implementation (which would be preferable), but it will need to be mirrored in the desktop as well or ignored/worked around on both.

ianhays avatar Jul 27 '15 17:07 ianhays

cc @ericstj @stephentoub

ianhays avatar Jul 27 '15 17:07 ianhays

This would be a breaking change on desktop. We could quirk it but would need to have a good reason for the change. Why do you suggest we change the behavior?

ericstj avatar Jul 27 '15 17:07 ericstj

The change would be for consistency with the other function calls e.g. File.Copy(source, dest) that throw DirectoryFoundExceptions when the parent directory doesn't exist. Move seems to be an exception to this rule for no particular reason.

File.Create("test1").Dispose();
File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "test2", "test3"), "test4"); // throws a DirectoryNotFoundException
File.Copy("test1", Path.Combine(Directory.GetCurrentDirectory(), "test2", "test3")); // throws a DirectoryNotFoundException

I'm not certain that consistency is a good enough reason for a breaking change (since either exception can be caught as an IOException), but better to be aware of it.

ianhays avatar Jul 27 '15 17:07 ianhays

General consensus for this issue is that this isn't a big enough issue to cause a breaking change for this fix. For situations when the distinction is relevant, catching an IOException (from which both DirectoryNotFoundException and FileNotFoundException inherit) is the better alternative.

ianhays avatar Aug 11 '15 19:08 ianhays