Merge pull request #405 from NextTurn/move

Throw correct exceptions for IO errors
pull/414/head
Oleg Nenashev 2020-02-11 17:07:00 +01:00 committed by GitHub
commit eb712f8088
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 10 additions and 2 deletions

View File

@ -1,5 +1,5 @@
#if !NETCOREAPP #if !NETCOREAPP
using System.ComponentModel; using System;
#endif #endif
using System.IO; using System.IO;
#if !NETCOREAPP #if !NETCOREAPP
@ -20,12 +20,20 @@ namespace winsw.Util
if (!NativeMethods.MoveFileEx(sourceFilePath, destFilePath, NativeMethods.MOVEFILE_REPLACE_EXISTING | NativeMethods.MOVEFILE_COPY_ALLOWED)) if (!NativeMethods.MoveFileEx(sourceFilePath, destFilePath, NativeMethods.MOVEFILE_REPLACE_EXISTING | NativeMethods.MOVEFILE_COPY_ALLOWED))
{ {
throw new Win32Exception(); throw GetExceptionForLastWin32Error(sourceFilePath);
} }
#endif #endif
} }
#if !NETCOREAPP #if !NETCOREAPP
private static Exception GetExceptionForLastWin32Error(string path) => Marshal.GetLastWin32Error() switch
{
2 => new FileNotFoundException(null, path), // ERROR_FILE_NOT_FOUND
3 => new DirectoryNotFoundException(), // ERROR_PATH_NOT_FOUND
5 => new UnauthorizedAccessException(), // ERROR_ACCESS_DENIED
_ => new IOException()
};
private static class NativeMethods private static class NativeMethods
{ {
internal const uint MOVEFILE_REPLACE_EXISTING = 0x01; internal const uint MOVEFILE_REPLACE_EXISTING = 0x01;