From 71df1c8595715b20b0aa99b2840e669a4988bdeb Mon Sep 17 00:00:00 2001 From: "Kasper F. Brandt" Date: Mon, 18 Sep 2017 03:01:31 +0200 Subject: [PATCH] FileStream should not truncate files when opening fails. Fixes dotnet/corefx#24081 --- .../shared/System/IO/FileStream.Unix.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/mscorlib/shared/System/IO/FileStream.Unix.cs b/src/mscorlib/shared/System/IO/FileStream.Unix.cs index 8499595361a4..99a337728807 100644 --- a/src/mscorlib/shared/System/IO/FileStream.Unix.cs +++ b/src/mscorlib/shared/System/IO/FileStream.Unix.cs @@ -97,11 +97,17 @@ private void Init(FileMode mode, FileShare share) ignoreNotSupported: true); // just a hint. } - // Jump to the end of the file if opened as Append. if (_mode == FileMode.Append) { + // Jump to the end of the file if opened as Append. _appendStart = SeekCore(_fileHandle, 0, SeekOrigin.End); } + else if (mode == FileMode.Create || mode == FileMode.Truncate) + { + // Truncate the file now if the file mode requires it. This ensures that the file only will be truncated + // if opened successfully. + CheckFileCall(Interop.Sys.FTruncate(_fileHandle, 0)); + } } /// Initializes a stream from an already open file handle (file descriptor). @@ -128,24 +134,18 @@ private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mo { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. + case FileMode.Truncate: // We truncate the file after getting the lock break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: + case FileMode.Create: // We truncate the file after getting the lock flags |= Interop.Sys.OpenFlags.O_CREAT; break; - case FileMode.Create: - flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_TRUNC); - break; - case FileMode.CreateNew: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL); break; - - case FileMode.Truncate: - flags |= Interop.Sys.OpenFlags.O_TRUNC; - break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open.