From b341d06ca6de032b82fb0b3fe6c09c26f497a7a9 Mon Sep 17 00:00:00 2001 From: Florin Daneliuc Date: Mon, 15 Jun 2020 12:17:32 +0300 Subject: [PATCH] Don't throw on Delete for missing file This way we match behavior of System.IO.File.Delete and avoid unexpected errors --- Pri.LongPath/File.cs | 22 ++++++++++++++-------- Tests/FileTests.cs | 6 ++++++ 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/Pri.LongPath/File.cs b/Pri.LongPath/File.cs index 4a0d11f..3091a95 100644 --- a/Pri.LongPath/File.cs +++ b/Pri.LongPath/File.cs @@ -220,17 +220,23 @@ public static FileStream Create(string path, int bufferSize, FileOptions options /// public static void Delete(string path) { - if (Common.IsRunningOnMono() && Common.IsPlatformUnix()) - { - SysFile.Delete(path); - return; - } + const int fileNotFoundWindowsErrorCode = 2; - string normalizedPath = Path.NormalizeLongPath(path); - if (!NativeMethods.DeleteFile(normalizedPath)) + if (Common.IsRunningOnMono() && Common.IsPlatformUnix()) { - throw Common.GetExceptionFromLastWin32Error(); + SysFile.Delete(path); + return; } + + string normalizedPath = Path.NormalizeLongPath(path); + + if (NativeMethods.DeleteFile(normalizedPath)) + return; + + if (fileNotFoundWindowsErrorCode == Marshal.GetLastWin32Error()) + return; + + throw Common.GetExceptionFromLastWin32Error(); } public static void Decrypt(string path) diff --git a/Tests/FileTests.cs b/Tests/FileTests.cs index 6566b73..d142fc5 100644 --- a/Tests/FileTests.cs +++ b/Tests/FileTests.cs @@ -1343,6 +1343,12 @@ public void TestGetLastWriteTimeOnMissingFileHasNoException() var dt = File.GetLastWriteTime("gibberish"); } + [Test] + public void TestDeleteOnMissingFileDoesNotThrow() + { + File.Delete("missing.file"); + } + [TearDown] public void TearDown() {