Environment.Win32.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. using System.Collections;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Reflection;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. using Internal.Win32;
  11. namespace System
  12. {
  13. public static partial class Environment
  14. {
  15. private static string GetEnvironmentVariableFromRegistry(string variable, bool fromMachine)
  16. {
  17. Debug.Assert(variable != null);
  18. #if FEATURE_APPX
  19. if (ApplicationModel.IsUap)
  20. return null; // Systems without the Windows registry pretend that it's always empty.
  21. #endif
  22. using (RegistryKey environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false))
  23. {
  24. return environmentKey?.GetValue(variable) as string;
  25. }
  26. }
  27. private static void SetEnvironmentVariableFromRegistry(string variable, string value, bool fromMachine)
  28. {
  29. Debug.Assert(variable != null);
  30. #if FEATURE_APPX
  31. if (ApplicationModel.IsUap)
  32. return; // Systems without the Windows registry pretend that it's always empty.
  33. #endif
  34. const int MaxUserEnvVariableLength = 255; // User-wide env vars stored in the registry have names limited to 255 chars
  35. if (!fromMachine && variable.Length >= MaxUserEnvVariableLength)
  36. {
  37. throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable));
  38. }
  39. using (RegistryKey environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: true))
  40. {
  41. if (environmentKey != null)
  42. {
  43. if (value == null)
  44. {
  45. environmentKey.DeleteValue(variable, throwOnMissingValue: false);
  46. }
  47. else
  48. {
  49. environmentKey.SetValue(variable, value);
  50. }
  51. }
  52. }
  53. // send a WM_SETTINGCHANGE message to all windows
  54. IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST), Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
  55. Debug.Assert(r != IntPtr.Zero, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
  56. }
  57. private static IDictionary GetEnvironmentVariablesFromRegistry(bool fromMachine)
  58. {
  59. var results = new Hashtable();
  60. #if FEATURE_APPX
  61. if (ApplicationModel.IsUap) // Systems without the Windows registry pretend that it's always empty.
  62. return results;
  63. #endif
  64. using (RegistryKey environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false))
  65. {
  66. if (environmentKey != null)
  67. {
  68. foreach (string name in environmentKey.GetValueNames())
  69. {
  70. string value = environmentKey.GetValue(name, "").ToString();
  71. try
  72. {
  73. results.Add(name, value);
  74. }
  75. catch (ArgumentException)
  76. {
  77. // Throw and catch intentionally to provide non-fatal notification about corrupted environment block
  78. }
  79. }
  80. }
  81. }
  82. return results;
  83. }
  84. private static RegistryKey OpenEnvironmentKeyIfExists(bool fromMachine, bool writable)
  85. {
  86. RegistryKey baseKey;
  87. string keyName;
  88. if (fromMachine)
  89. {
  90. baseKey = Registry.LocalMachine;
  91. keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
  92. }
  93. else
  94. {
  95. baseKey = Registry.CurrentUser;
  96. keyName = "Environment";
  97. }
  98. return baseKey.OpenSubKey(keyName, writable: writable);
  99. }
  100. public static string UserName
  101. {
  102. get
  103. {
  104. #if FEATURE_APPX
  105. if (ApplicationModel.IsUap)
  106. return "Windows User";
  107. #endif
  108. // 40 should be enough as we're asking for the SAM compatible name (DOMAIN\User).
  109. // The max length should be 15 (domain) + 1 (separator) + 20 (name) + null. If for
  110. // some reason it isn't, we'll grow the buffer.
  111. // https://support.microsoft.com/en-us/help/909264/naming-conventions-in-active-directory-for-computers-domains-sites-and
  112. // https://msdn.microsoft.com/en-us/library/ms679635.aspx
  113. Span<char> initialBuffer = stackalloc char[40];
  114. var builder = new ValueStringBuilder(initialBuffer);
  115. GetUserName(ref builder);
  116. ReadOnlySpan<char> name = builder.AsSpan();
  117. int index = name.IndexOf('\\');
  118. if (index != -1)
  119. {
  120. // In the form of DOMAIN\User, cut off DOMAIN\
  121. name = name.Slice(index + 1);
  122. }
  123. return name.ToString();
  124. }
  125. }
  126. private static void GetUserName(ref ValueStringBuilder builder)
  127. {
  128. uint size = 0;
  129. while (Interop.Secur32.GetUserNameExW(Interop.Secur32.NameSamCompatible, ref builder.GetPinnableReference(), ref size) == Interop.BOOLEAN.FALSE)
  130. {
  131. if (Marshal.GetLastWin32Error() == Interop.Errors.ERROR_MORE_DATA)
  132. {
  133. builder.EnsureCapacity(checked((int)size));
  134. }
  135. else
  136. {
  137. builder.Length = 0;
  138. return;
  139. }
  140. }
  141. builder.Length = (int)size;
  142. }
  143. public static string UserDomainName
  144. {
  145. get
  146. {
  147. #if FEATURE_APPX
  148. if (ApplicationModel.IsUap)
  149. return "Windows Domain";
  150. #endif
  151. // See the comment in UserName
  152. Span<char> initialBuffer = stackalloc char[40];
  153. var builder = new ValueStringBuilder(initialBuffer);
  154. GetUserName(ref builder);
  155. ReadOnlySpan<char> name = builder.AsSpan();
  156. int index = name.IndexOf('\\');
  157. if (index != -1)
  158. {
  159. // In the form of DOMAIN\User, cut off \User and return
  160. return name.Slice(0, index).ToString();
  161. }
  162. // In theory we should never get use out of LookupAccountNameW as the above API should
  163. // always return what we need. Can't find any clues in the historical sources, however.
  164. // Domain names aren't typically long.
  165. // https://support.microsoft.com/en-us/help/909264/naming-conventions-in-active-directory-for-computers-domains-sites-and
  166. Span<char> initialDomainNameBuffer = stackalloc char[64];
  167. var domainBuilder = new ValueStringBuilder(initialBuffer);
  168. uint length = (uint)domainBuilder.Capacity;
  169. // This API will fail to return the domain name without a buffer for the SID.
  170. // SIDs are never over 68 bytes long.
  171. Span<byte> sid = stackalloc byte[68];
  172. uint sidLength = 68;
  173. while (!Interop.Advapi32.LookupAccountNameW(null, ref builder.GetPinnableReference(), ref MemoryMarshal.GetReference(sid),
  174. ref sidLength, ref domainBuilder.GetPinnableReference(), ref length, out _))
  175. {
  176. int error = Marshal.GetLastWin32Error();
  177. // The docs don't call this out clearly, but experimenting shows that the error returned is the following.
  178. if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
  179. {
  180. throw new InvalidOperationException(Win32Marshal.GetMessage(error));
  181. }
  182. domainBuilder.EnsureCapacity((int)length);
  183. }
  184. domainBuilder.Length = (int)length;
  185. return domainBuilder.ToString();
  186. }
  187. }
  188. private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option)
  189. {
  190. #if FEATURE_APPX
  191. if (ApplicationModel.IsUap)
  192. return WinRTFolderPaths.GetFolderPath(folder, option);
  193. #endif
  194. // We're using SHGetKnownFolderPath instead of SHGetFolderPath as SHGetFolderPath is
  195. // capped at MAX_PATH.
  196. //
  197. // Because we validate both of the input enums we shouldn't have to care about CSIDL and flag
  198. // definitions we haven't mapped. If we remove or loosen the checks we'd have to account
  199. // for mapping here (this includes tweaking as SHGetFolderPath would do).
  200. //
  201. // The only SpecialFolderOption defines we have are equivalent to KnownFolderFlags.
  202. string folderGuid;
  203. switch (folder)
  204. {
  205. case SpecialFolder.ApplicationData:
  206. folderGuid = Interop.Shell32.KnownFolders.RoamingAppData;
  207. break;
  208. case SpecialFolder.CommonApplicationData:
  209. folderGuid = Interop.Shell32.KnownFolders.ProgramData;
  210. break;
  211. case SpecialFolder.LocalApplicationData:
  212. folderGuid = Interop.Shell32.KnownFolders.LocalAppData;
  213. break;
  214. case SpecialFolder.Cookies:
  215. folderGuid = Interop.Shell32.KnownFolders.Cookies;
  216. break;
  217. case SpecialFolder.Desktop:
  218. folderGuid = Interop.Shell32.KnownFolders.Desktop;
  219. break;
  220. case SpecialFolder.Favorites:
  221. folderGuid = Interop.Shell32.KnownFolders.Favorites;
  222. break;
  223. case SpecialFolder.History:
  224. folderGuid = Interop.Shell32.KnownFolders.History;
  225. break;
  226. case SpecialFolder.InternetCache:
  227. folderGuid = Interop.Shell32.KnownFolders.InternetCache;
  228. break;
  229. case SpecialFolder.Programs:
  230. folderGuid = Interop.Shell32.KnownFolders.Programs;
  231. break;
  232. case SpecialFolder.MyComputer:
  233. folderGuid = Interop.Shell32.KnownFolders.ComputerFolder;
  234. break;
  235. case SpecialFolder.MyMusic:
  236. folderGuid = Interop.Shell32.KnownFolders.Music;
  237. break;
  238. case SpecialFolder.MyPictures:
  239. folderGuid = Interop.Shell32.KnownFolders.Pictures;
  240. break;
  241. case SpecialFolder.MyVideos:
  242. folderGuid = Interop.Shell32.KnownFolders.Videos;
  243. break;
  244. case SpecialFolder.Recent:
  245. folderGuid = Interop.Shell32.KnownFolders.Recent;
  246. break;
  247. case SpecialFolder.SendTo:
  248. folderGuid = Interop.Shell32.KnownFolders.SendTo;
  249. break;
  250. case SpecialFolder.StartMenu:
  251. folderGuid = Interop.Shell32.KnownFolders.StartMenu;
  252. break;
  253. case SpecialFolder.Startup:
  254. folderGuid = Interop.Shell32.KnownFolders.Startup;
  255. break;
  256. case SpecialFolder.System:
  257. folderGuid = Interop.Shell32.KnownFolders.System;
  258. break;
  259. case SpecialFolder.Templates:
  260. folderGuid = Interop.Shell32.KnownFolders.Templates;
  261. break;
  262. case SpecialFolder.DesktopDirectory:
  263. folderGuid = Interop.Shell32.KnownFolders.Desktop;
  264. break;
  265. case SpecialFolder.Personal:
  266. // Same as Personal
  267. // case SpecialFolder.MyDocuments:
  268. folderGuid = Interop.Shell32.KnownFolders.Documents;
  269. break;
  270. case SpecialFolder.ProgramFiles:
  271. folderGuid = Interop.Shell32.KnownFolders.ProgramFiles;
  272. break;
  273. case SpecialFolder.CommonProgramFiles:
  274. folderGuid = Interop.Shell32.KnownFolders.ProgramFilesCommon;
  275. break;
  276. case SpecialFolder.AdminTools:
  277. folderGuid = Interop.Shell32.KnownFolders.AdminTools;
  278. break;
  279. case SpecialFolder.CDBurning:
  280. folderGuid = Interop.Shell32.KnownFolders.CDBurning;
  281. break;
  282. case SpecialFolder.CommonAdminTools:
  283. folderGuid = Interop.Shell32.KnownFolders.CommonAdminTools;
  284. break;
  285. case SpecialFolder.CommonDocuments:
  286. folderGuid = Interop.Shell32.KnownFolders.PublicDocuments;
  287. break;
  288. case SpecialFolder.CommonMusic:
  289. folderGuid = Interop.Shell32.KnownFolders.PublicMusic;
  290. break;
  291. case SpecialFolder.CommonOemLinks:
  292. folderGuid = Interop.Shell32.KnownFolders.CommonOEMLinks;
  293. break;
  294. case SpecialFolder.CommonPictures:
  295. folderGuid = Interop.Shell32.KnownFolders.PublicPictures;
  296. break;
  297. case SpecialFolder.CommonStartMenu:
  298. folderGuid = Interop.Shell32.KnownFolders.CommonStartMenu;
  299. break;
  300. case SpecialFolder.CommonPrograms:
  301. folderGuid = Interop.Shell32.KnownFolders.CommonPrograms;
  302. break;
  303. case SpecialFolder.CommonStartup:
  304. folderGuid = Interop.Shell32.KnownFolders.CommonStartup;
  305. break;
  306. case SpecialFolder.CommonDesktopDirectory:
  307. folderGuid = Interop.Shell32.KnownFolders.PublicDesktop;
  308. break;
  309. case SpecialFolder.CommonTemplates:
  310. folderGuid = Interop.Shell32.KnownFolders.CommonTemplates;
  311. break;
  312. case SpecialFolder.CommonVideos:
  313. folderGuid = Interop.Shell32.KnownFolders.PublicVideos;
  314. break;
  315. case SpecialFolder.Fonts:
  316. folderGuid = Interop.Shell32.KnownFolders.Fonts;
  317. break;
  318. case SpecialFolder.NetworkShortcuts:
  319. folderGuid = Interop.Shell32.KnownFolders.NetHood;
  320. break;
  321. case SpecialFolder.PrinterShortcuts:
  322. folderGuid = Interop.Shell32.KnownFolders.PrintersFolder;
  323. break;
  324. case SpecialFolder.UserProfile:
  325. folderGuid = Interop.Shell32.KnownFolders.Profile;
  326. break;
  327. case SpecialFolder.CommonProgramFilesX86:
  328. folderGuid = Interop.Shell32.KnownFolders.ProgramFilesCommonX86;
  329. break;
  330. case SpecialFolder.ProgramFilesX86:
  331. folderGuid = Interop.Shell32.KnownFolders.ProgramFilesX86;
  332. break;
  333. case SpecialFolder.Resources:
  334. folderGuid = Interop.Shell32.KnownFolders.ResourceDir;
  335. break;
  336. case SpecialFolder.LocalizedResources:
  337. folderGuid = Interop.Shell32.KnownFolders.LocalizedResourcesDir;
  338. break;
  339. case SpecialFolder.SystemX86:
  340. folderGuid = Interop.Shell32.KnownFolders.SystemX86;
  341. break;
  342. case SpecialFolder.Windows:
  343. folderGuid = Interop.Shell32.KnownFolders.Windows;
  344. break;
  345. default:
  346. return string.Empty;
  347. }
  348. return GetKnownFolderPath(folderGuid, option);
  349. }
  350. private static string GetKnownFolderPath(string folderGuid, SpecialFolderOption option)
  351. {
  352. Guid folderId = new Guid(folderGuid);
  353. int hr = Interop.Shell32.SHGetKnownFolderPath(folderId, (uint)option, IntPtr.Zero, out string path);
  354. if (hr != 0) // Not S_OK
  355. {
  356. return string.Empty;
  357. }
  358. return path;
  359. }
  360. #if FEATURE_APPX
  361. private static class WinRTFolderPaths
  362. {
  363. private static Func<SpecialFolder, SpecialFolderOption, string> s_winRTFolderPathsGetFolderPath;
  364. public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption option)
  365. {
  366. if (s_winRTFolderPathsGetFolderPath == null)
  367. {
  368. Type winRtFolderPathsType = Type.GetType("System.WinRTFolderPaths, System.Runtime.WindowsRuntime, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", throwOnError: false);
  369. MethodInfo getFolderPathsMethod = winRtFolderPathsType?.GetMethod("GetFolderPath", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(SpecialFolder), typeof(SpecialFolderOption) }, null);
  370. var d = (Func<SpecialFolder, SpecialFolderOption, string>)getFolderPathsMethod?.CreateDelegate(typeof(Func<SpecialFolder, SpecialFolderOption, string>));
  371. s_winRTFolderPathsGetFolderPath = d ?? delegate { return null; };
  372. }
  373. return s_winRTFolderPathsGetFolderPath(folder, option);
  374. }
  375. }
  376. #endif
  377. }
  378. }