You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Directory.CurrentDirectory.cs 7.8 KiB

7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. /* Copyright (C) 2008-2016 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
  2. *
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to deal
  5. * in the Software without restriction, including without limitation the rights
  6. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. * copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. *
  13. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. * THE SOFTWARE.
  20. */
  21. using System;
  22. using System.Diagnostics.CodeAnalysis;
  23. using System.Globalization;
  24. using System.IO;
  25. using System.Runtime.InteropServices;
  26. using System.Security;
  27. using System.Text;
  28. namespace Alphaleonis.Win32.Filesystem
  29. {
  30. partial class Directory
  31. {
  32. /// <summary>
  33. /// Gets the current working directory of the application.
  34. /// <para>
  35. /// MSDN: Multithreaded applications and shared library code should not use the GetCurrentDirectory function and should avoid using relative path names.
  36. /// The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,
  37. /// therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.
  38. /// <para>This limitation also applies to the SetCurrentDirectory and GetFullPathName functions. The exception being when the application is guaranteed to be running in a single thread,
  39. /// for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
  40. /// <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
  41. /// </para>
  42. /// </summary>
  43. /// <returns>The path of the current working directory without a trailing directory separator.</returns>
  44. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate"), SecurityCritical]
  45. public static string GetCurrentDirectory()
  46. {
  47. var nameBuffer = new StringBuilder(NativeMethods.MaxPathUnicode);
  48. // SetCurrentDirectory()
  49. // In the ANSI version of this function, the name is limited to 248 characters.
  50. // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
  51. // 2016-09-29: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
  52. var folderNameLength = NativeMethods.GetCurrentDirectory((uint) nameBuffer.Capacity, nameBuffer);
  53. var lastError = Marshal.GetLastWin32Error();
  54. if (folderNameLength == 0)
  55. NativeError.ThrowException(lastError);
  56. if (folderNameLength > NativeMethods.MaxPathUnicode)
  57. throw new PathTooLongException(string.Format(CultureInfo.InvariantCulture, "Path is greater than {0} characters: {1}", NativeMethods.MaxPathUnicode, folderNameLength));
  58. return nameBuffer.ToString();
  59. }
  60. /// <summary>
  61. /// Sets the application's current working directory to the specified directory.
  62. /// <para>
  63. /// MSDN: Multithreaded applications and shared library code should not use the GetCurrentDirectory function and should avoid using relative path names.
  64. /// The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,
  65. /// therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.
  66. /// <para>This limitation also applies to the SetCurrentDirectory and GetFullPathName functions. The exception being when the application is guaranteed to be running in a single thread,
  67. /// for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
  68. /// <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
  69. /// </para>
  70. /// </summary>
  71. /// <param name="path">The path to which the current working directory is set.</param>
  72. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")]
  73. [SecurityCritical]
  74. public static void SetCurrentDirectory(string path)
  75. {
  76. SetCurrentDirectory(path, PathFormat.RelativePath);
  77. }
  78. /// <summary>
  79. /// Sets the application's current working directory to the specified directory.
  80. /// <para>
  81. /// MSDN: Multithreaded applications and shared library code should not use the GetCurrentDirectory function and should avoid using relative path names.
  82. /// The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,
  83. /// therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.
  84. /// <para>This limitation also applies to the SetCurrentDirectory and GetFullPathName functions. The exception being when the application is guaranteed to be running in a single thread,
  85. /// for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
  86. /// <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
  87. /// </para>
  88. /// </summary>
  89. /// <param name="path">The path to which the current working directory is set.</param>
  90. /// <param name="pathFormat">Indicates the format of the path parameter.</param>
  91. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")]
  92. [SecurityCritical]
  93. public static void SetCurrentDirectory(string path, PathFormat pathFormat)
  94. {
  95. if (Utils.IsNullOrWhiteSpace(path))
  96. throw new ArgumentNullException("path");
  97. var fullCheck = pathFormat == PathFormat.RelativePath;
  98. Path.CheckSupportedPathFormat(path, fullCheck, fullCheck);
  99. var pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.AddTrailingDirectorySeparator);
  100. if (pathFormat == PathFormat.FullPath)
  101. pathLp = Path.GetRegularPathCore(pathLp, GetFullPathOptions.None, false);
  102. // SetCurrentDirectory()
  103. // In the ANSI version of this function, the name is limited to 248 characters.
  104. // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
  105. // 2016-09-29: MSDN confirms LongPath usage starting with Windows 10, version 1607.
  106. if (!NativeMethods.SetCurrentDirectory(pathLp))
  107. NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp);
  108. }
  109. }
  110. }