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 when sourceFileName is a file and destinationFileName is a directory.
  • Throws IOException with the message Not a directory when sourceFileName is a directory and destinationFileName is a file.
  • Silently succeeds when both sourceFileName and destinationFileName 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 either sourceFileName or destinationFileName exists and is not a file, or when both sourceFileName and destinationFileName point to the same existing directory.
  • Throws IOException with the message The source <sourceFileName> and destination <destinationFileName> are the same file when sourceFileName and destinationFileName 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.

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