diff --git a/src/mscorlib/shared/System/IO/Path.Unix.cs b/src/mscorlib/shared/System/IO/Path.Unix.cs index f364b84df074..b5c9e09fae39 100644 --- a/src/mscorlib/shared/System/IO/Path.Unix.cs +++ b/src/mscorlib/shared/System/IO/Path.Unix.cs @@ -69,6 +69,35 @@ private static string RemoveLongPathPrefix(string path) return path; // nop. There's nothing special about "long" paths on Unix. } + private static void GetTempPath(ref ValueStringBuilder builder) + { + const string TempEnvVar = "TMPDIR"; + const string DefaultTempPath = "/tmp/"; + + // Get the temp path from the TMPDIR environment variable. + int requiredSize = 0; + while ((requiredSize = Microsoft.Win32.Win32Native.GetEnvironmentVariable(TempEnvVar, builder.Span)) > builder.Capacity) + { + // Reported size is greater than the buffer size. Increase the capacity. + builder.EnsureCapacity(requiredSize); + } + + if (requiredSize == 0 && Runtime.InteropServices.Marshal.GetLastWin32Error() == Interop.Errors.ERROR_ENVVAR_NOT_FOUND) + { + builder.EnsureCapacity(DefaultTempPath.Length); + // If it's not set, just return the default path. + builder.Append(DefaultTempPath.AsSpan()); + } + else + { + // If it is, return it, ensuring it ends with a slash. + if (!PathInternal.IsDirectorySeparator(builder[builder.Length - 1])) + { + builder.Append(PathInternal.DirectorySeparatorChar); + } + } + } + public static string GetTempPath() { const string TempEnvVar = "TMPDIR"; diff --git a/src/mscorlib/shared/System/IO/Path.cs b/src/mscorlib/shared/System/IO/Path.cs index 1e40ab5e602f..3d7d1fe2c4e9 100644 --- a/src/mscorlib/shared/System/IO/Path.cs +++ b/src/mscorlib/shared/System/IO/Path.cs @@ -477,6 +477,14 @@ public static bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, R return true; } + public static bool TryGetTempPath(Span destination, out int charsWritten) + { + charsWritten = 0; + ValueStringBuilder vsb = new ValueStringBuilder(); + Path.GetTempPath(ref vsb); + return vsb.TryCopyTo(destination, out charsWritten); + } + private static string CombineInternal(string first, string second) { if (string.IsNullOrEmpty(first)) diff --git a/src/mscorlib/shared/System/Text/ValueStringBuilder.cs b/src/mscorlib/shared/System/Text/ValueStringBuilder.cs index b1abdd59bc65..7e81057df17b 100644 --- a/src/mscorlib/shared/System/Text/ValueStringBuilder.cs +++ b/src/mscorlib/shared/System/Text/ValueStringBuilder.cs @@ -34,6 +34,8 @@ public int Length public int Capacity => _chars.Length; + public Span Span => _chars; + public void EnsureCapacity(int capacity) { if (capacity > _chars.Length)