1 // Licensed to the .NET Foundation under one or more agreements. 2 // The .NET Foundation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using System.Collections; 6 using System.Collections.Generic; 7 using System.IO; 8 using System.Runtime.ExceptionServices; 9 using System.Runtime.InteropServices; 10 using System.Text; 11 12 namespace System 13 { 14 public static partial class AppContext 15 { 16 /// <summary> 17 /// Return the directory of the executable image for the current process 18 /// as the default value for AppContext.BaseDirectory 19 /// </summary> GetBaseDirectoryCore()20 private static string GetBaseDirectoryCore() 21 { 22 StringBuilder buffer = new StringBuilder(Interop.mincore.MAX_PATH); 23 while (true) 24 { 25 int size = Interop.mincore.GetModuleFileName(IntPtr.Zero, buffer, buffer.Capacity); 26 if (size == 0) 27 { 28 throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); 29 } 30 31 if (Marshal.GetLastWin32Error() == Interop.mincore.ERROR_INSUFFICIENT_BUFFER) 32 { 33 // Enlarge the buffer and try again. 34 buffer.EnsureCapacity(buffer.Capacity * 2); 35 continue; 36 } 37 38 // Return path to the executable image including the terminating slash 39 string fileName = buffer.ToString(); 40 return fileName.Substring(0, fileName.LastIndexOf('\\') + 1); 41 } 42 } 43 } 44 } 45