From 5fcc58524569d95d38427336bfae557c1cbbb9d6 Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Thu, 13 Jan 2022 18:24:34 +0100 Subject: [PATCH 1/2] don't check for file existence if there is no need for it --- .../src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs index 417da0b825fd03..345ac38865d566 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs @@ -148,7 +148,12 @@ public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, nameof(access)); } - bool existed = File.Exists(path); + bool existed = mode switch + { + FileMode.Open => true, // if it's not true, the line below is going to throw + FileMode.CreateNew => false, + _ => File.Exists(path) + }; FileStream fileStream = new FileStream(path, mode, GetFileAccess(access), FileShare.Read, 0x1000, FileOptions.None); if (capacity == 0 && fileStream.Length == 0) From 85498fda09bcd66018178c9b510b16bd112ac09f Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Thu, 13 Jan 2022 19:02:18 +0100 Subject: [PATCH 2/2] Apply suggestions from code review Co-authored-by: Stephen Toub --- .../src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs index 345ac38865d566..cc8d30ca73ef19 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs @@ -150,7 +150,7 @@ public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string bool existed = mode switch { - FileMode.Open => true, // if it's not true, the line below is going to throw + FileMode.Open => true, // FileStream ctor will throw if the file doesn't exist FileMode.CreateNew => false, _ => File.Exists(path) };