File.Replace on Unix throws exceptions to match Windows implementation
The behavior of File.Replace on Unix-based operating systems has changed. The exceptions it throws now match those that are thrown by the Windows implementation.
Previous behavior
On Unix, with .NET 5, the File.Replace method:
- Throws IOException with the message
Is a directory
whensourceFileName
is a file anddestinationFileName
is a directory. - Throws IOException with the message
Not a directory
whensourceFileName
is a directory anddestinationFileName
is a file. - Silently succeeds when both
sourceFileName
anddestinationFileName
point to the same file or directory.
New behavior
On Unix, with .NET 6, the File.Replace method:
- Throws UnauthorizedAccessException with the message
The specified path <path> is not a path
, when eithersourceFileName
ordestinationFileName
exists and is not a file, or when bothsourceFileName
anddestinationFileName
point to the same existing directory. - Throws IOException with the message
The source <sourceFileName> and destination <destinationFileName> are the same file
whensourceFileName
anddestinationFileName
point to the same existing file.
Version introduced
.NET 6
Type of breaking change
This change can affect source compatibility.
Reason for change
This change was made to ensure that File.Replace throws the same exceptions for the same reasons across platforms.
Recommended action
If you invoke File.Replace on Unix inside a try catch
block, make sure to now also catch UnauthorizedAccessException. Also, be aware of the new behaviors that are caught.
Affected APIs
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.