<|start_filename|>src/AlphaFS/Filesystem/FileSystemEntryInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Represents information about a file system entry.
   /// <para>This class cannot be inherited.</para>
   /// </summary>
   [Serializable]
   [SecurityCritical]
   public sealed class FileSystemEntryInfo : IEquatable<FileSystemEntryInfo>
   {
      #region Fields

      private string _fullPath;
      private string _longFullPath;

      #endregion // Fields


      #region Constructor

      /// <summary>Initializes a new instance of the <see cref="FileSystemEntryInfo"/> class.</summary>
      /// <param name="findData">The NativeMethods.WIN32_FIND_DATA structure.</param>
      internal FileSystemEntryInfo(NativeMethods.WIN32_FIND_DATA findData)
      {
         Win32FindData = findData;
      }

      #endregion // Constructor


      #region Properties

      /// <summary>The instance 8.3 version of the filename.</summary>
      public string AlternateFileName
      {
         // This property is always empty when NativeMethods.FINDEX_INFO_LEVELS.Basic is used.

         get { return Win32FindData.cAlternateFileName; }
      }


      /// <summary>The instance attributes.</summary>
      public FileAttributes Attributes
      {
         get { return Win32FindData.dwFileAttributes; }
      }


      /// <summary>The instance creation time.</summary>
      public DateTime CreationTime
      {
         get { return CreationTimeUtc.ToLocalTime(); }
      }


      /// <summary>The instance creation time, in coordinated universal time (UTC).</summary>
      public DateTime CreationTimeUtc
      {
         get { return DateTime.FromFileTimeUtc(Win32FindData.ftCreationTime); }
      }


      /// <summary>The instance file extension.</summary>
      public string Extension
      {
         get { return Path.GetExtension(Win32FindData.cFileName, false); }
      }


      /// <summary>The instance file name.</summary>
      public string FileName
      {
         get { return Win32FindData.cFileName; }
      }


      /// <summary>The instance file size.</summary>
      public long FileSize
      {
         get { return NativeMethods.ToLong(Win32FindData.nFileSizeHigh, Win32FindData.nFileSizeLow); }
      }

      
      /// <summary>The instance full path.</summary>
      public string FullPath
      {
         get { return _fullPath; }

         set
         {
            LongFullPath = value;
            _fullPath = Path.GetRegularPathCore(LongFullPath, GetFullPathOptions.None, false);
         }
      }


      /// <summary>The instance is a candidate for backup or removal. </summary>
      public bool IsArchive
      {
         get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Archive) != 0; }
      }


      /// <summary>The instance is compressed.</summary>
      public bool IsCompressed
      {
         get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Compressed) != 0; }
      }


      /// <summary>Reserved for future use.</summary>
      public bool IsDevice
      {
         get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Device) != 0; }
      }


      /// <summary>The instance is a directory.</summary>
      public bool IsDirectory
      {
         get { return File.IsDirectory(Attributes); }
      }


      /// <summary>The instance is encrypted. For a file, this means that all data in the file is encrypted. For a directory, this means that encryption is the default for newly created files and directories.</summary>
      public bool IsEncrypted
      {
         get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Encrypted) != 0; }
      }


      /// <summary>The instance is hidden, and thus is not included in an ordinary directory listing.</summary>
      public bool IsHidden
      {
         get { return File.IsHidden(Attributes); }
      }


      /// <summary>The instance is a mount point. Applicable to local directories and local volumes.</summary>
      public bool IsMountPoint
      {
         get { return ReparsePointTag == ReparsePointTag.MountPoint; }
      }


      /// <summary>The instance is a standard file that has no special attributes. This attribute is valid only if it is used alone.</summary>
      public bool IsNormal
      {
         get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Normal) != 0; }
      }


      /// <summary>The instance will not be indexed by the operating system's content indexing service.</summary>
      public bool IsNotContentIndexed
      {
         get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.NotContentIndexed) != 0; }
      }


      /// <summary>The instance is offline. The data of the file is not immediately available.</summary>
      public bool IsOffline
      {
         get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Offline) != 0; }
      }


      /// <summary>The instance is read-only.</summary>
      public bool IsReadOnly
      {
         get { return File.IsReadOnly(Attributes); }
      }


      /// <summary>The instance contains a reparse point, which is a block of user-defined data associated with a file or a directory.</summary>
      public bool IsReparsePoint
      {
         get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.ReparsePoint) != 0; }
      }


      /// <summary>The instance is a sparse file. Sparse files are typically large files whose data consists of mostly zeros.</summary>
      public bool IsSparseFile
      {
         get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.SparseFile) != 0; }
      }


      /// <summary>The instance is a symbolic link.</summary>
      public bool IsSymbolicLink
      {
         get { return ReparsePointTag == ReparsePointTag.SymLink; }
      }


      /// <summary>The instance is a system file. That is, the file is part of the operating system or is used exclusively by the operating system.</summary>
      public bool IsSystem
      {
         get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.System) != 0; }
      }


      /// <summary>The instance is temporary. A temporary file contains data that is needed while an application is executing but is not needed after the application is finished.
      /// File systems try to keep all the data in memory for quicker access rather than flushing the data back to mass storage.
      /// A temporary file should be deleted by the application as soon as it is no longer needed.</summary>
      public bool IsTemporary
      {
         get { return File.HasValidAttributes(Attributes) && (Attributes & FileAttributes.Temporary) != 0; }
      }


      /// <summary>The instance time this entry was last accessed.</summary>
      public DateTime LastAccessTime
      {
         get { return LastAccessTimeUtc.ToLocalTime(); }
      }


      /// <summary>The instance time, in coordinated universal time (UTC), this entry was last accessed.</summary>
      public DateTime LastAccessTimeUtc
      {
         get { return DateTime.FromFileTimeUtc(Win32FindData.ftLastAccessTime); }
      }


      /// <summary>The instance time this entry was last modified.</summary>
      public DateTime LastWriteTime
      {
         get { return LastWriteTimeUtc.ToLocalTime(); }
      }


      /// <summary>The instance time, in coordinated universal time (UTC), this entry was last modified.</summary>
      public DateTime LastWriteTimeUtc
      {
         get { return DateTime.FromFileTimeUtc(Win32FindData.ftLastWriteTime); }
      }


      /// <summary>The instance full path in long path format.</summary>
      public string LongFullPath
      {
         get { return _longFullPath; }

         private set { _longFullPath = Path.GetLongPathCore(value, GetFullPathOptions.None); }
      }


      /// <summary>The instance reparse point tag.</summary>
      public ReparsePointTag ReparsePointTag
      {
         get { return IsReparsePoint ? Win32FindData.dwReserved0 : ReparsePointTag.None; }
      }


      /// <summary>The instance internal WIN32 FIND Data</summary>
      internal NativeMethods.WIN32_FIND_DATA Win32FindData { get; private set; }

      #endregion // Properties


      #region Methods

      /// <summary>Returns the <see cref="FullPath"/> of the FileSystemEntryInfo instance.</summary>
      /// <returns>Returns the <see cref="FullPath"/> of the FileSystemEntryInfo instance.</returns>
      public override string ToString()
      {
         return FullPath;
      }


      /// <summary>Serves as a hash function for a particular type.</summary>
      /// <returns>A hash code for the current Object.</returns>
      public override int GetHashCode()
      {
         return Utils.CombineHashCodesOf(FullPath, LongFullPath);
      }


      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="other">Another <see cref="FileSystemInfo"/> instance to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public bool Equals(FileSystemEntryInfo other)
      {
         return null != other && GetType() == other.GetType() &&
                Equals(FileName, other.FileName) &&
                Equals(FullPath, other.FullPath) &&
                Equals(Attributes, other.Attributes) &&
                Equals(CreationTimeUtc, other.CreationTimeUtc) &&
                Equals(LastAccessTimeUtc, other.LastAccessTimeUtc);
      }


      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="obj">Another object to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public override bool Equals(object obj)
      {
         var other = obj as FileSystemEntryInfo;

         return null != other && Equals(other);
      }


      /// <summary>Implements the operator ==</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator ==(FileSystemEntryInfo left, FileSystemEntryInfo right)
      {
         return ReferenceEquals(left, null) && ReferenceEquals(right, null) ||
                !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right);
      }


      /// <summary>Implements the operator !=</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator !=(FileSystemEntryInfo left, FileSystemEntryInfo right)
      {
         return !(left == right);
      }
      #endregion // Methods
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Returns an enumerable collection of <see cref="String"/> of all mounted folders (volume mount points) on the specified volume. </summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <param name="volumeGuid">A <see cref="string"/> containing the volume <see cref="Guid"/>.</param>
      /// <returns>An enumerable collection of <see cref="String"/> of all volume mount points on the specified volume.</returns>
      [SecurityCritical]
      public static IEnumerable<string> EnumerateVolumeMountPoints(string volumeGuid)
      {
         if (Utils.IsNullOrWhiteSpace(volumeGuid))
            throw new ArgumentNullException("volumeGuid");

         if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase))
            throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid");


         // A trailing backslash is required.
         volumeGuid = Path.AddTrailingDirectorySeparator(volumeGuid, false);


         var buffer = new StringBuilder(NativeMethods.MaxPathUnicode);


         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
         using (var handle = NativeMethods.FindFirstVolumeMountPoint(volumeGuid, buffer, (uint)buffer.Capacity))
         {
            var lastError = Marshal.GetLastWin32Error();

            if (!NativeMethods.IsValidHandle(handle, false))
            {
               switch ((uint)lastError)
               {
                  case Win32Errors.ERROR_NO_MORE_FILES:
                  case Win32Errors.ERROR_PATH_NOT_FOUND: // Observed with USB stick, FAT32 formatted.
                     yield break;

                  default:
                     NativeError.ThrowException(lastError, volumeGuid);
                     break;
               }
            }

            yield return buffer.ToString();


            while (NativeMethods.FindNextVolumeMountPoint(handle, buffer, (uint)buffer.Capacity))
            {
               lastError = Marshal.GetLastWin32Error();

               var throwException = lastError != Win32Errors.ERROR_NO_MORE_FILES && lastError != Win32Errors.ERROR_PATH_NOT_FOUND && lastError != Win32Errors.ERROR_MORE_DATA;

               if (!NativeMethods.IsValidHandle(handle, lastError, volumeGuid, throwException))
                  yield break;

               yield return buffer.ToString();
            }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Security/PrivilegeEnabler.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace Alphaleonis.Win32.Security
{
   /// <summary>Used to enable one or more privileges. The privileges specified will be enabled during the lifetime of the instance. Users create an instance of this object in a <c>using</c> statement to ensure that it is properly disposed when the elevated privileges are no longer needed.</summary>
   public sealed class PrivilegeEnabler : IDisposable
   {
      #region PrivilegeEnabler

      private readonly List<InternalPrivilegeEnabler> _enabledPrivileges = new List<InternalPrivilegeEnabler>();

      /// <summary>Initializes a new instance of the <see cref="PrivilegeEnabler"/> class.
      /// This will enable the privileges specified (unless already enabled), and ensure that they are disabled again when
      /// the object is disposed. (Any privileges already enabled will not be disabled).
      /// </summary>
      /// <param name="privilege">The privilege to enable.</param>
      /// <param name="privileges">Additional privileges to enable.</param>
      public PrivilegeEnabler(Privilege privilege, params Privilege[] privileges)
      {
         _enabledPrivileges.Add(new InternalPrivilegeEnabler(privilege));

         if (privileges != null)
            foreach (Privilege priv in privileges)
               _enabledPrivileges.Add(new InternalPrivilegeEnabler(priv));
      }

      #endregion // PrivilegeEnabler

      #region Dispose

      /// <summary>Makes sure any privileges enabled by this instance are disabled.</summary>
      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      public void Dispose()
      {
         foreach (InternalPrivilegeEnabler t in _enabledPrivileges)
         {
            try
            {
               t.Dispose();
            }
            catch
            {
               // We ignore any exceptions here
            }
         }
      }

      #endregion // Dispose

      #region EnabledPrivileges

      /// <summary>Gets the enabled privileges. Note that this might not contain all privileges specified to the constructor. Only the privileges actually enabled by this instance is returned.</summary>
      /// <value>The enabled privileges.</value>
      public IEnumerable<Privilege> EnabledPrivileges
      {
         get { return from priv in _enabledPrivileges where priv.EnabledPrivilege != null select priv.EnabledPrivilege; }
      }

      #endregion // EnabledPrivileges
   }
}

<|start_filename|>src/AlphaFS/Safe Handles/SafeGlobalMemoryBufferHandle.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Text;

namespace Alphaleonis.Win32
{
   /// <summary>Represents a block of native memory of a specified size allocated using the LocalAlloc function from Kernel32.dll.</summary>
   internal sealed class SafeGlobalMemoryBufferHandle : SafeNativeMemoryBufferHandle
   {
      /// <summary>Initializes a new instance of the <see cref="SafeGlobalMemoryBufferHandle"/> class, with zero IntPtr.</summary>
      public SafeGlobalMemoryBufferHandle() : base(true)
      {
      }


      /// <summary>Initializes a new instance of the <see cref="SafeGlobalMemoryBufferHandle"/> class allocating the specified number of bytes of unmanaged memory.</summary>
      /// <param name="capacity">The capacity.</param>
      public SafeGlobalMemoryBufferHandle(int capacity) : base(capacity)
      {
         SetHandle(Marshal.AllocHGlobal(capacity));
      }


      private SafeGlobalMemoryBufferHandle(IntPtr buffer, int capacity) : base(buffer, capacity)
      {
      }


      [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
      public static SafeGlobalMemoryBufferHandle FromLong(long? value)
      {
         if (value.HasValue)
         {
            var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(long)));

            Marshal.WriteInt64(safeBuffer.handle, value.Value);

            return safeBuffer;
         }

         return new SafeGlobalMemoryBufferHandle();
      }


      public static SafeGlobalMemoryBufferHandle FromStringUni(string str)
      {
         if (str == null)
            throw new ArgumentNullException("str");

         return new SafeGlobalMemoryBufferHandle(Marshal.StringToHGlobalUni(str), str.Length * UnicodeEncoding.CharSize + UnicodeEncoding.CharSize);
      }


      /// <summary>When overridden in a derived class, executes the code required to free the handle.</summary>
      /// <returns>
      /// <c>true</c> if the handle is released successfully; otherwise, in the event of a catastrophic failure,
      /// <c>false</c>. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant.
      /// </returns>
      protected override bool ReleaseHandle()
      {
         Marshal.FreeHGlobal(handle);
         return true;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_Rename_DifferentCasingDirectory.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class MoveTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void Directory_Move_Rename_DifferentCasingDirectory_LocalAndNetwork_Success()
      {
         Directory_Move_Rename_DifferentCasingDirectory(false);
         Directory_Move_Rename_DifferentCasingDirectory(true);
      }


      private void Directory_Move_Rename_DifferentCasingDirectory(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folderSrc = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(tempRoot.Directory.FullName, "Existing Source Folder"));

            var upperCaseFolderName = System.IO.Path.GetFileName(folderSrc.FullName).ToUpperInvariant();

            var destFolder = System.IO.Path.Combine(folderSrc.Parent.FullName, upperCaseFolderName);

            Console.WriteLine("Input Directory Path: [{0}]\n", folderSrc.FullName);
            Console.WriteLine("\tRename folder [{0}] to [{1}]", folderSrc.Name, upperCaseFolderName);


            Alphaleonis.Win32.Filesystem.Directory.Move(folderSrc.FullName, destFolder);


            var upperDirInfo = new System.IO.DirectoryInfo(destFolder);

            UnitTestConstants.Dump(upperDirInfo);
            

            Assert.AreEqual(upperCaseFolderName, upperDirInfo.Name, "The source folder name is not uppercase, but is expected to.");
         }


         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.WriteAllBytesCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Creates a new file as part of a transaction, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to write to.</param>
      /// <param name="bytes">The bytes to write to the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "bytes")]
      [SecurityCritical]
      internal static void WriteAllBytesCore(KernelTransaction transaction, string path, byte[] bytes, PathFormat pathFormat)
      {
         if (null == bytes)
            throw new ArgumentNullException("bytes");

         using (var fs = OpenCore(transaction, path, FileMode.Create, FileAccess.Write, FileShare.Read, ExtendedFileAttributes.Normal, null, null, pathFormat))

            fs.Write(bytes, 0, bytes.Length);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;

namespace AlphaFS.UnitTest
{
   public partial class EnumerationTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Device_EnumerateDevices_Local_Success()
      {
         Console.WriteLine("\nMSDN Note: Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed.");
         Console.WriteLine("You cannot access remote machines when running on these versions of Windows.\n");

         AlphaFS_Device_EnumerateDevices();
      }


      private void AlphaFS_Device_EnumerateDevices()
      {
         UnitTestConstants.PrintUnitTestHeader(false);

         var tempPath = Environment.MachineName;
         var classCnt = 0;

         foreach (var deviceClass in EnumMemberToList<Alphaleonis.Win32.Filesystem.DeviceGuid>())
         {
            Console.WriteLine("#{0:000}\tClass: [{1}]", ++classCnt, deviceClass);

            foreach (var device in Alphaleonis.Win32.Filesystem.Device.EnumerateDevices(tempPath, deviceClass))
               UnitTestConstants.Dump(device);

            Console.WriteLine();
         }

         if (classCnt == 0)
            UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable();
      }


      private static IEnumerable<T> EnumMemberToList<T>()
      {
         var enumType = typeof(T);

         // Can't use generic type constraints on value types, so have to do check like this.
         if (enumType.BaseType != typeof(Enum))
            throw new ArgumentException("T must be of type System.Enum", "T");


         var enumValArray = Enum.GetValues(enumType).Cast<T>().OrderBy(e => e.ToString()).ToList();
         var enumValList = new List<T>(enumValArray.Count);

         enumValList.AddRange(enumValArray.Select(val => (T) Enum.Parse(enumType, val.ToString())));

         return enumValList;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File.GetProcessForFileLock.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>[AlphaFS] Gets a list of processes that have a lock on the files specified by <paramref name="filePath"/>.</summary>
      /// <returns>
      /// <c>null</c> when no processes found that are locking the file specified by <paramref name="filePath"/>.
      /// A list of processes locking the file specified by <paramref name="filePath"/>.
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="InvalidOperationException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="filePath">The path to the file.</param>
      public static Collection<Process> GetProcessForFileLock(string filePath)
      {
         return GetProcessForFileLockCore(null, new Collection<string>(new[] {filePath}), PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Gets a list of processes that have a lock on the files specified by <paramref name="filePath"/>.</summary>
      /// <returns>
      /// <c>null</c> when no processes found that are locking the file specified by <paramref name="filePath"/>.
      /// A list of processes locking the file specified by <paramref name="filePath"/>.
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="InvalidOperationException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="filePath">The path to the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      public static Collection<Process> GetProcessForFileLock(string filePath, PathFormat pathFormat)
      {
         return GetProcessForFileLockCore(null, new Collection<string>(new[] {filePath}), pathFormat);
      }


      /// <summary>[AlphaFS] Gets a list of processes that have a lock on the file(s) specified by <paramref name="filePaths"/>.</summary>
      /// <returns>
      /// <c>null</c> when no processes found that are locking the file(s) specified by <paramref name="filePaths"/>.
      /// A list of processes locking the file(s) specified by <paramref name="filePaths"/>.
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="InvalidOperationException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="filePaths">A list with one or more file paths.</param>
      public static Collection<Process> GetProcessForFileLock(Collection<string> filePaths)
      {
         return GetProcessForFileLockCore(null, filePaths, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Gets a list of processes that have a lock on the file(s) specified by <paramref name="filePaths"/>.</summary>
      /// <returns>
      /// <c>null</c> when no processes found that are locking the file(s) specified by <paramref name="filePaths"/>.
      /// A list of processes locking the file(s) specified by <paramref name="filePaths"/>.
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="InvalidOperationException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="filePaths">A list with one or more file paths.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      public static Collection<Process> GetProcessForFileLock(Collection<string> filePaths, PathFormat pathFormat)
      {
         return GetProcessForFileLockCore(null, filePaths, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.SetFsoDateTimeCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Sets the date and time, in coordinated universal time (UTC), that the file or directory was created and/or last accessed and/or written to.</summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="NotSupportedException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="isFolder">Specifies that <paramref name="path"/> is a file or directory.</param>
      /// <param name="path">The file or directory for which to set the date and time information.</param>
      /// <param name="creationTimeUtc">A <see cref="DateTime"/> containing the value to set for the creation date and time of <paramref name="path"/>. This value is expressed in UTC time.</param>
      /// <param name="lastAccessTimeUtc">A <see cref="DateTime"/> containing the value to set for the last access date and time of <paramref name="path"/>. This value is expressed in UTC time.</param>
      /// <param name="lastWriteTimeUtc">A <see cref="DateTime"/> containing the value to set for the last write date and time of <paramref name="path"/>. This value is expressed in UTC time.</param>
      /// <param name="modifyReparsePoint">If <c>true</c>, the date and time information will apply to the reparse point (symlink or junction) and not the file or directory linked to. No effect if <paramref name="path"/> does not refer to a reparse point.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void SetFsoDateTimeCore(KernelTransaction transaction, bool isFolder, string path, DateTime? creationTimeUtc, DateTime? lastAccessTimeUtc, DateTime? lastWriteTimeUtc, bool modifyReparsePoint, PathFormat pathFormat)
      {
         if (pathFormat == PathFormat.RelativePath)
            Path.CheckSupportedPathFormat(path, false, false);

         var eaAttributes = ExtendedFileAttributes.BackupSemantics;

         if (modifyReparsePoint)
            eaAttributes |= ExtendedFileAttributes.OpenReparsePoint;


         //// Prevent a System.UnauthorizedAccessException from being thrown by resetting attributes to Normal.

         //var fileAttributes = FileAttributes.Normal;
         //var isReadOnly = IsReadOnly((FileAttributes) eaAttributes);
         //var isHidden = IsHidden((FileAttributes) eaAttributes);

         //if (isReadOnly || isHidden)
         //   SetAttributesCore(transaction, isFolder, path, fileAttributes, PathFormat.LongFullPath);


         using (var creationTime = SafeGlobalMemoryBufferHandle.FromLong(creationTimeUtc.HasValue ? creationTimeUtc.Value.ToFileTimeUtc() : (long?) null))

         using (var lastAccessTime = SafeGlobalMemoryBufferHandle.FromLong(lastAccessTimeUtc.HasValue ? lastAccessTimeUtc.Value.ToFileTimeUtc() : (long?) null))

         using (var lastWriteTime = SafeGlobalMemoryBufferHandle.FromLong(lastWriteTimeUtc.HasValue ? lastWriteTimeUtc.Value.ToFileTimeUtc() : (long?) null))

         using (var safeFileHandle = CreateFileCore(transaction, isFolder, path, eaAttributes, null, FileMode.Open, FileSystemRights.WriteAttributes, FileShare.Delete | FileShare.Write, false, false, pathFormat))
         {
            var success = NativeMethods.SetFileTime(safeFileHandle, creationTime, lastAccessTime, lastWriteTime);

            var lastError = Marshal.GetLastWin32Error();
            
            // Reset file system object attributes.

            if (success)
            {
               //if (isReadOnly || isHidden)
               //{
               //   if (isReadOnly)
               //      fileAttributes |= FileAttributes.ReadOnly;

               //   if (isHidden)
               //      fileAttributes |= FileAttributes.Hidden;

               //   fileAttributes &= ~FileAttributes.Normal;

               //   SetAttributesCore(transaction, isFolder, path, fileAttributes, PathFormat.LongFullPath);
               //}
            }

            else
               NativeError.ThrowException(lastError, isFolder, path);
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Linq;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      #region .NET

      /// <summary>Retrieves the names of the logical drives on the Computer in the form "&lt;drive letter&gt;:\".</summary>
      /// <returns>An array of type <see cref="string"/> that represents the logical drives on the Computer.</returns>
      [SecurityCritical]
      public static string[] GetLogicalDrives()
      {
         return EnumerateLogicalDrivesCore(false, false).Select(drive => drive.Name).ToArray();
      }

      #endregion // .NET
      

      /// <summary>[AlphaFS] Retrieves the names of the logical drives on the Computer in the form "C:\".</summary>
      /// <returns>An array of type <see cref="string"/> that represents the logical drives on the Computer.</returns>
      /// <param name="fromEnvironment">Retrieve logical drives as known by the Environment.</param>
      /// <param name="isReady">Retrieve only when accessible (IsReady) logical drives.</param>
      [SecurityCritical]
      public static string[] GetLogicalDrives(bool fromEnvironment, bool isReady)
      {
         return EnumerateLogicalDrivesCore(fromEnvironment, isReady).Select(drive => drive.Name).ToArray();
      }
   }
}


<|start_filename|>src/AlphaFS/Network/SessionInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Alphaleonis.Win32.Filesystem;

namespace Alphaleonis.Win32.Network
{
   /// <summary>Contains information about Server Message Block (SMB) shares. This class cannot be inherited.</summary>
   [Serializable]
   public sealed class SessionInfo
   {
      #region Private Fields

      private string _netName;

      #endregion // Private Fields


      #region Constructor

      /// <summary>Creates a <see cref="SessionInfo"/> instance.</summary>
      /// <param name="hostName">The DNS or NetBIOS name of the specified host.</param>
      /// <param name="sessionLevel">One of the <see cref="SessionInfoLevel"/> options.</param>
      /// <param name="structure">
      /// A <see cref="NativeMethods.SESSION_INFO_502"/>, <see cref="NativeMethods.SESSION_INFO_2"/>,
      /// <see cref="NativeMethods.SESSION_INFO_1"/>, <see cref="NativeMethods.SESSION_INFO_10"/> or <see cref="NativeMethods.SESSION_INFO_0"/> instance.
      /// </param>
      internal SessionInfo(string hostName, SessionInfoLevel sessionLevel, object structure)
      {
         var flags = 0;


         switch (sessionLevel)
         {
            case SessionInfoLevel.Info502:
               var sesi502 = (NativeMethods.SESSION_INFO_502) structure;
               NetName = sesi502.sesi502_cname;
               UserName = sesi502.sesi502_username;
               OpenedResources = (int) sesi502.sesi502_num_opens;
               ActiveTime = TimeSpan.FromSeconds((int) sesi502.sesi502_time);
               IdleTime = TimeSpan.FromSeconds((int) sesi502.sesi502_idle_time);
               ClientType = sesi502.sesi502_cltype_name;
               TransportType = sesi502.sesi502_transport;
               flags = (int) sesi502.sesi502_user_flags;
               break;


            case SessionInfoLevel.Info2:
               var sesi2 = (NativeMethods.SESSION_INFO_2) structure;
               NetName = sesi2.sesi2_cname;
               UserName = sesi2.sesi2_username;
               OpenedResources = (int) sesi2.sesi2_num_opens;
               ActiveTime = TimeSpan.FromSeconds((int) sesi2.sesi2_time);
               ClientType = sesi2.sesi2_cltype_name;
               flags = (int) sesi2.sesi2_user_flags;
               break;


            case SessionInfoLevel.Info1:
               var sesi1 = (NativeMethods.SESSION_INFO_1) structure;
               NetName = sesi1.sesi1_cname;
               UserName = sesi1.sesi1_username;
               OpenedResources = (int) sesi1.sesi1_num_opens;
               ActiveTime = TimeSpan.FromSeconds((int) sesi1.sesi1_time);
               IdleTime = TimeSpan.FromSeconds((int) sesi1.sesi1_idle_time);
               flags = (int) sesi1.sesi1_user_flags;
               break;


            case SessionInfoLevel.Info10:
               var sesi10 = (NativeMethods.SESSION_INFO_10) structure;
               NetName = sesi10.sesi10_cname;
               UserName = sesi10.sesi10_username;
               ActiveTime = TimeSpan.FromSeconds((int) sesi10.sesi10_time);
               IdleTime = TimeSpan.FromSeconds((int) sesi10.sesi10_idle_time);
               break;


            case SessionInfoLevel.Info0:
               var sesi0 = (NativeMethods.SESSION_INFO_0) structure;
               NetName = sesi0.sesi0_cname;
               break;
         }


         HostName = hostName;

         SessionLevel = sessionLevel;
         
         // SESS_GUEST = 1,
         // SESS_NOENCRYPTION = 2

         GuestSession = flags == 1;

         EncryptedSession = !GuestSession && flags != 2;
      }

      #endregion // Constructor


      #region Methods

      /// <summary>Returns the host name of this session information.</summary>
      /// <returns>A string that represents this instance.</returns>
      public override string ToString()
      {
         return HostName;
      }

      #endregion // Methods


      #region Properties

      /// <summary>The host name of this session information.</summary>
      public string HostName { get; private set; }


      /// <summary>The Computer name or IP address that established the session.</summary>
      public string NetName
      {
         get { return _netName; }

         set { _netName = null != value ? value.ReplaceIgnoreCase(Path.LongPathUncPrefix, string.Empty).Replace(Path.UncPrefix, string.Empty).Trim('[', ']') : null; }
      }


      /// <summary>The name of the User who established the session.</summary>
      public string UserName { get; private set; }


      /// <summary>The number of files, devices, and pipes opened during the session.</summary>
      public int OpenedResources { get; private set; }


      /// <summary>The session active duration.</summary>
      public TimeSpan ActiveTime { get; private set; }


      /// <summary>The session idle duration.</summary>
      public TimeSpan IdleTime { get; private set; }


      ///// <summary>
      ///// <para>Specifies a value that describes how the user established the session. This member can be one of the following values:</para>
      ///// <para>SESS_GUEST: The user specified by the <see cref="UserName"/> member established the session using a guest account.</para>
      ///// <para>SESS_NOENCRYPTION: The user specified by the <see cref="UserName"/> member established the session without using password encryption.</para>
      ///// </summary>
      ////public int Flags { get; private set; }

      /// <summary>A value that describes how the User established the session.</summary>
      public bool GuestSession { get; private set; }

      /// <summary>A value that describes how the User established the session.</summary>
      public bool EncryptedSession { get; private set; }


      /// <summary>The type of client that established the session. Sessions from LAN Manager servers running UNIX also will appear as LAN Manager 2.0.</summary>
      public string ClientType { get; private set; }


      /// <summary>The name of the transport that the client is using to communicate with the server.</summary>
      public string TransportType { get; private set; }


      /// <summary>The structure level for the <see cref="SessionInfo"/> instance.</summary>
      public SessionInfoLevel SessionLevel { get; private set; }

      #endregion // Properties
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Net.NetworkInformation;
using System.Security;
using Alphaleonis.Win32.Filesystem;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>[AlphaFS] Retrieves <see cref="ServerStatisticsInfo"/> operating statistics for the Server service from the local host.</summary>
      /// <returns>A <see cref="ServerStatisticsInfo"/> instance.</returns>
      /// <exception cref="NetworkInformationException"/>
      [SecurityCritical]
      public static ServerStatisticsInfo GetServerStatistics()
      {
         return (ServerStatisticsInfo) GetNetStatisticsCore(true, Environment.MachineName);
      }


      /// <summary>[AlphaFS] Retrieves <see cref="ServerStatisticsInfo"/> operating statistics for the Server service from the specified host.</summary>
      /// <returns>A <see cref="ServerStatisticsInfo"/> instance.</returns>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="hostName">The DNS or NetBIOS name of the local or remote host to retrieve statistics from.</param>
      [SecurityCritical]
      public static ServerStatisticsInfo GetServerStatistics(string hostName)
      {
         return (ServerStatisticsInfo) GetNetStatisticsCore(true, hostName);
      }




      /// <summary>[AlphaFS] Retrieves <see cref="WorkstationStatisticsInfo"/> operating statistics for the Workstation service from the local host.</summary>
      /// <returns>A <see cref="WorkstationStatisticsInfo"/> instance.</returns>
      /// <exception cref="NetworkInformationException"/>
      [SecurityCritical]
      public static WorkstationStatisticsInfo GetWorkstationStatistics()
      {
         return (WorkstationStatisticsInfo) GetNetStatisticsCore(false, Environment.MachineName);
      }


      /// <summary>[AlphaFS] Retrieves <see cref="WorkstationStatisticsInfo"/> operating statistics for the Workstation service from the specified host.</summary>
      /// <returns>A <see cref="WorkstationStatisticsInfo"/> instance.</returns>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="hostName">The DNS or NetBIOS name of the local or remote host to retrieve statistics from.</param>
      [SecurityCritical]
      public static WorkstationStatisticsInfo GetWorkstationStatistics(string hostName)
      {
         return (WorkstationStatisticsInfo) GetNetStatisticsCore(false, hostName);
      }




      /// <summary>[AlphaFS] Retrieves <see cref="ServerStatisticsInfo"/> or <see cref="WorkstationStatisticsInfo"/> operating statistics for the Server- or Workstation service from the specified host.</summary>
      /// <returns>A <see cref="ServerStatisticsInfo"/> or <see cref="WorkstationStatisticsInfo"/> instance, depending on the <paramref name="isServer"/> value.</returns>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="isServer">true returns <see cref="ServerStatisticsInfo"/> information, false <see cref="WorkstationStatisticsInfo"/>.</param>
      /// <param name="hostName">The DNS or NetBIOS name of the local or remote host to retrieve statistics from.</param>
      [SecurityCritical]
      internal static object GetNetStatisticsCore(bool isServer, string hostName)
      {
         return isServer

            ? (object) new ServerStatisticsInfo(hostName, null)

            : new WorkstationStatisticsInfo(hostName, null);
      }


      [SecurityCritical]
      internal static T GetNetStatisticsNative<T>(bool isServer, string hostName)
      {
         SafeGlobalMemoryBufferHandle safeBuffer;


         // hostName is allowed to be null.

         var stripUnc = !Utils.IsNullOrWhiteSpace(hostName) ? Path.GetRegularPathCore(hostName, GetFullPathOptions.CheckInvalidPathChars, false).Replace(Path.UncPrefix, string.Empty) : null;

         var lastError = NativeMethods.NetStatisticsGet(stripUnc, isServer ? "LanmanServer" : "LanmanWorkstation", 0, 0, out safeBuffer);


         using (safeBuffer)
         {
            if (lastError != Win32Errors.NERR_Success)
               throw new NetworkInformationException((int) lastError);


            return safeBuffer.PtrToStructure<T>(0);
         }
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetFileAssociation.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_Shell32Test
   {
      [TestMethod]
      public void AlphaFS_Shell32_GetFileAssociation()
      {
         AlphaFS_Shell32_GetFileAssociation(false);
         AlphaFS_Shell32_GetFileAssociation(true);
      }


      private void AlphaFS_Shell32_GetFileAssociation(bool isNetwork)
      {
         UnitTestConstants.PrintUnitTestHeader(isNetwork);

         var inputPath = Environment.SystemDirectory;
         if (isNetwork)
            inputPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(inputPath);

         Console.WriteLine("Input Directory Path: [{0}]", inputPath);


         var cnt = 0;
         foreach (var file in System.IO.Directory.EnumerateFiles(inputPath))
         {
            var shell32Info = Alphaleonis.Win32.Filesystem.Shell32.GetShell32Info(file);

            // Not much of a test...
            Assert.IsNotNull(shell32Info);

            UnitTestConstants.Dump(shell32Info);

            if (++cnt == 5)
               break;
         }

         Console.WriteLine();

         Assert.IsTrue(cnt > 0, "No entries enumerated.");
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] 
      ///   Retrieves a volume <see cref="Guid"/> path for the volume that is associated with the specified volume mount point (drive letter,
      ///   volume GUID path, or mounted folder).
      /// </summary>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="volumeMountPoint">
      ///   The path of a mounted folder (for example, "Y:\MountX\") or a drive letter (for example, "X:\").
      /// </param>
      /// <returns>The unique volume name of the form: "\\?\Volume{GUID}\".</returns>
      [SuppressMessage("Microsoft.Interoperability", "CA1404:CallGetLastErrorImmediatelyAfterPInvoke", Justification = "Marshal.GetLastWin32Error() is manipulated.")]
      [SecurityCritical]
      public static string GetVolumeGuid(string volumeMountPoint)
      {
         if (Utils.IsNullOrWhiteSpace(volumeMountPoint))
            throw new ArgumentNullException("volumeMountPoint");

         // The string must end with a trailing backslash ('\').
         volumeMountPoint = Path.GetFullPathCore(null, false, volumeMountPoint, GetFullPathOptions.AsLongPath | GetFullPathOptions.AddTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

         var volumeGuid = new StringBuilder(100);
         var uniqueName = new StringBuilder(100);

         try
         {
            using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
            {
               // GetVolumeNameForVolumeMountPoint()
               // 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

               return NativeMethods.GetVolumeNameForVolumeMountPoint(volumeMountPoint, volumeGuid, (uint)volumeGuid.Capacity)

                  // The string must end with a trailing backslash.
                  ? NativeMethods.GetVolumeNameForVolumeMountPoint(Path.AddTrailingDirectorySeparator(volumeGuid.ToString(), false), uniqueName, (uint)uniqueName.Capacity)
                     ? uniqueName.ToString()
                     : null

                  : null;
            }
         }
         finally
         {
            var lastError = (uint) Marshal.GetLastWin32Error();

            switch (lastError)
            {
               case Win32Errors.ERROR_MORE_DATA:
                  // (1) When GetVolumeNameForVolumeMountPoint() succeeds, lastError is set to Win32Errors.ERROR_MORE_DATA.
                  break;

               default:
                  // (2) When volumeMountPoint is a network drive mapping or UNC path, lastError is set to Win32Errors.ERROR_INVALID_PARAMETER.

                  // Throw IOException.
                  NativeError.ThrowException(lastError, volumeMountPoint);
                  break;
            }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Native Other/SESSION_INFO_2.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>Contains information about the session, including name of the computer; name of the user; open files, pipes, and devices on the computer; and the type of client that established the session.</summary>
      /// <remarks>
      /// <para>Minimum supported client: Windows XP [desktop apps only]</para>
      /// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
      /// </remarks>
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      internal struct SESSION_INFO_2
      {
         /// <summary>Pointer to a Unicode string specifying the name of the computer that established the session. This string cannot contain a backslash (\).</summary>
         [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi2_cname;

         /// <summary>Pointer to a Unicode string specifying the name of the user who established the session.</summary>
         [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi2_username;

         /// <summary>Specifies a DWORD value that contains the number of files, devices, and pipes opened during the session.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sesi2_num_opens;

         /// <summary>Specifies a DWORD value that contains the number of seconds the session has been active.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sesi2_time;

         /// <summary>Specifies a DWORD value that contains the number of seconds the session has been idle.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sesi2_idle_time;

         /// <summary>
         /// <para>Specifies a DWORD value that describes how the user established the session. This member can be one of the following values:</para>
         /// <para>SESS_GUEST: The user specified by the <see cref="sesi2_username"/> member established the session using a guest account.</para>
         /// <para>SESS_NOENCRYPTION: The user specified by the <see cref="sesi2_username"/> member established the session without using password encryption.</para>
         /// </summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sesi2_user_flags;


         /// <summary>
         /// <para>Pointer to a Unicode string that specifies the type of client that established the session. Following are the defined types for LAN Manager servers:</para>
         /// <para>DOS LM 1.0: LAN Manager for MS-DOS 1.0 clients</para>
         /// <para>DOS LM 2.0: LAN Manager for MS-DOS 2.0 clients</para>
         /// <para>OS/2 LM 1.0: LAN Manager for MS-OS/2 1.0 clients</para>
         /// <para>OS/2 LM 2.0: LAN Manager for MS-OS/2 2.0 clients</para>
         /// <para>Sessions from LAN Manager servers running UNIX also will appear as LAN Manager 2.0.</para>
         /// </summary>
         [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi2_cltype_name;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.DeleteFileCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Deletes a Non-/Transacted file.</summary>
      /// <remarks>If the file to be deleted does not exist, no exception is thrown.</remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="FileReadOnlyException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The name of the file to be deleted.</param>
      /// <param name="ignoreReadOnly"><c>true</c> overrides the read only <see cref="FileAttributes"/> of the file.</param>
      /// <param name="attributes"></param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void DeleteFileCore(KernelTransaction transaction, string path, bool ignoreReadOnly, FileAttributes attributes, PathFormat pathFormat)
      {
         if (null == path)
            throw new ArgumentNullException("path");

         if (pathFormat == PathFormat.RelativePath)
            Path.CheckSupportedPathFormat(path, true, true);

         var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);


         // Reset attributes to Normal if we already know the facts.

         if (ignoreReadOnly && IsReadOnlyOrHidden(attributes))

            SetAttributesCore(transaction, false, pathLp, FileAttributes.Normal, PathFormat.LongFullPath);


      startDeleteFile:

         if (!(null == transaction || !NativeMethods.IsAtLeastWindowsVista

            // DeleteFile() / DeleteFileTransacted()
            // 2013-01-13: MSDN confirms LongPath usage.
            //
            // If the path points to a symbolic link, the symbolic link is deleted, not the target.

            ? NativeMethods.DeleteFile(pathLp)

            : NativeMethods.DeleteFileTransacted(pathLp, transaction.SafeHandle)))
         {
            var lastError = Marshal.GetLastWin32Error();


            switch ((uint) lastError)
            {
               case Win32Errors.ERROR_FILE_NOT_FOUND:
                  // MSDN: .NET 3.5+: If the file to be deleted does not exist, no exception is thrown.
                  return;


               case Win32Errors.ERROR_PATH_NOT_FOUND:
                  // MSDN: .NET 3.5+: DirectoryNotFoundException: The specified path is invalid (for example, it is on an unmapped drive).
                  NativeError.ThrowException(lastError, pathLp);
                  return;


               case Win32Errors.ERROR_SHARING_VIOLATION:
                  // MSDN: .NET 3.5+: IOException: The specified file is in use or there is an open handle on the file.
                  NativeError.ThrowException(lastError, pathLp);
                  break;


               case Win32Errors.ERROR_ACCESS_DENIED:

                  if (attributes == 0)
                  {
                     var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();

                     if (FillAttributeInfoCore(transaction, pathLp, ref attrs, false, true) == Win32Errors.NO_ERROR)

                        attributes = attrs.dwFileAttributes;
                  }


                  // MSDN: .NET 3.5+: UnauthorizedAccessException: Path is a directory.
                  if (IsDirectory(attributes))
                     throw new UnauthorizedAccessException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", lastError.ToString(CultureInfo.InvariantCulture), string.Format(CultureInfo.InvariantCulture, Resources.Target_File_Is_A_Directory, pathLp)));


                  if (IsReadOnlyOrHidden(attributes))
                  {
                     if (ignoreReadOnly)
                     {
                        // Reset attributes to Normal.
                        SetAttributesCore(transaction, false, pathLp, FileAttributes.Normal, PathFormat.LongFullPath);

                        goto startDeleteFile;
                     }


                     // MSDN: .NET 3.5+: UnauthorizedAccessException: Path specified a read-only file.
                     throw new FileReadOnlyException(pathLp);
                  }

                  
                  // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission.
                  if (attributes == 0)
                     NativeError.ThrowException(lastError, pathLp);

                  break;
            }

            // MSDN: .NET 3.5+: IOException:
            // The specified file is in use.
            // There is an open handle on the file, and the operating system is Windows XP or earlier.

            NativeError.ThrowException(lastError, IsDirectory(attributes), pathLp);
         }
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/DirectoryInfo.MoveTo_Rename.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class MoveTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void DirectoryInfo_MoveTo_Rename_LocalAndNetwork_Success()
      {
         DirectoryInfo_MoveTo_Rename(false);
         DirectoryInfo_MoveTo_Rename(true);
      }


      private void DirectoryInfo_MoveTo_Rename(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var newFolderName = "Rename_to_" + tempRoot.RandomDirectoryName;

            var dirInfoAlphaFS = new Alphaleonis.Win32.Filesystem.DirectoryInfo(tempRoot.RandomDirectoryFullPath);

            var dirInfoSystemIO = new System.IO.DirectoryInfo(System.IO.Path.Combine(tempRoot.Directory.FullName, newFolderName));

            Console.WriteLine("Input Directory Path: [{0}]", dirInfoAlphaFS.FullName);
            Console.WriteLine("\n\tRename folder to: [{0}]", dirInfoSystemIO.Name);


            // Create folder.
            dirInfoAlphaFS.Create();


            // Rename folder.
            dirInfoAlphaFS.MoveTo(dirInfoSystemIO.FullName);


            dirInfoAlphaFS.Refresh();
            dirInfoSystemIO.Refresh();


            Assert.IsTrue(dirInfoAlphaFS.Exists, "It is expected that the source exists, but is does not.");

            Assert.AreEqual(dirInfoAlphaFS.Parent.FullName, dirInfoSystemIO.Parent.FullName);
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Junctions, Links/Directory.CreateJunctionTransacted.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      #region Obsolete

      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J").</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      [SecurityCritical]
      public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, false, false, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J").</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath, PathFormat pathFormat)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, false, false, pathFormat);
      }


      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed.</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      [SecurityCritical]
      public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, false, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed.</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, PathFormat pathFormat)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, false, pathFormat);
      }


      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed.</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// The directory date and time stamps from <paramref name="directoryPath"/> (the target) are copied to the directory junction.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      /// <param name="copyTargetTimestamps"><c>true</c> to copy the target date and time stamps to the directory junction.</param>
      [SecurityCritical]
      public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, copyTargetTimestamps, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed.</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// The directory date and time stamps from <paramref name="directoryPath"/> (the target) are copied to the directory junction.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      /// <param name="copyTargetTimestamps"><c>true</c> to copy the target date and time stamps to the directory junction.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void CreateJunction(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps, PathFormat pathFormat)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, copyTargetTimestamps, pathFormat);
      }

      #endregion // Obsolete


      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J").</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      [SecurityCritical]
      public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, false, false, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J").</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath, PathFormat pathFormat)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, false, false, pathFormat);
      }


      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed.</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      [SecurityCritical]
      public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, false, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed.</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, PathFormat pathFormat)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, false, pathFormat);
      }


      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed.</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// The directory date and time stamps from <paramref name="directoryPath"/> (the target) are copied to the directory junction.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      /// <param name="copyTargetTimestamps"><c>true</c> to copy the target date and time stamps to the directory junction.</param>
      [SecurityCritical]
      public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, copyTargetTimestamps, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed.</summary>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// The directory date and time stamps from <paramref name="directoryPath"/> (the target) are copied to the directory junction.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      /// <param name="copyTargetTimestamps"><c>true</c> to copy the target date and time stamps to the directory junction.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void CreateJunctionTransacted(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps, PathFormat pathFormat)
      {
         CreateJunctionCore(transaction, junctionPath, directoryPath, overwrite, copyTargetTimestamps, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Enumerations/AccessPermissions.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;

namespace Alphaleonis.Win32.Network
{
   /// <summary>A set of bit flags that describe the permissions for the shared resource's on servers running with share-level security.</summary>
   /// <remarks>Note that Windows does not support share-level security. This member is ignored on a server running user-level security.</remarks>
   [Flags]
   public enum AccessPermissions
   {
      /// <summary>No permissions.</summary>
      None = 0,

      /// <summary>ACCESS_READ
      /// <para>Permission to read data from a resource and, by default, to execute the resource.</para>
      /// </summary>
      Read = 1,

      /// <summary>ACCESS_WRITE
      /// <para>Permission to write data to the resource.</para>
      /// </summary>
      Write = 2,

      /// <summary>ACCESS_CREATE
      /// <para>Permission to create an instance of the resource (such as a file); data can be written to the resource as the resource is created.</para>
      /// </summary>
      Create = 4,

      /// <summary>ACCESS_EXEC
      /// <para>Permission to execute the resource.</para>
      /// </summary>
      Execute = 8,

      /// <summary>ACCESS_DELETE
      /// <para>Permission to delete the resource.</para>
      /// </summary>
      Delete = 16,

      /// <summary>ACCESS_ATRIB
      /// <para>Permission to modify the resource's attributes, such as the date and time when a file was last modified.</para>
      /// </summary>
      Attributes = 32,

      /// <summary>ACCESS_PERM
      /// <para>Permission to modify the permissions (read, write, create, execute, and delete) assigned to a resource for a user or application.</para>
      /// </summary>
      Permissions = 64,

      /// <summary>ACCESS_ALL
      /// <para>Permission to read, write, create, execute, and delete resources, and to modify their attributes and permissions.</para>
      /// </summary>
      All = 32768
   }
}

<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_ContinueOnAccessDeniedExceptionUsingDirectoryEnumerationErrorFilter.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;

#if !NET35
using System.Threading;
#endif

namespace AlphaFS.UnitTest
{
   public partial class EnumerationTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_EnumerateFileSystemEntryInfos_ContinueOnAccessDeniedExceptionUsingDirectoryEnumerationErrorFilter_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_EnumerateFileSystemEntryInfos_ContinueOnAccessDeniedExceptionUsingDirectoryEnumerationErrorFilter(false);
         AlphaFS_Directory_EnumerateFileSystemEntryInfos_ContinueOnAccessDeniedExceptionUsingDirectoryEnumerationErrorFilter(true);
      }


      private void AlphaFS_Directory_EnumerateFileSystemEntryInfos_ContinueOnAccessDeniedExceptionUsingDirectoryEnumerationErrorFilter(bool isNetwork)
      {
         UnitTestConstants.PrintUnitTestHeader(isNetwork);
         
         var inputPath = System.IO.Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)).FullName;
         if (isNetwork)
            inputPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(inputPath);

         Console.WriteLine("Input Directory Path: [{0}]\n", inputPath);
         
         Test_ContinueOnAccessDeniedExceptionUsingErrorFilter(inputPath);
         
         Console.WriteLine();
      }




      private void Test_ContinueOnAccessDeniedExceptionUsingErrorFilter(string inputPath)
      {
         var gotException = false;
         const int exceptionCatch = 10;
         var exceptionCount = 0;


#if NET35
         var abortEnumeration = false;


         var filters = new Alphaleonis.Win32.Filesystem.DirectoryEnumerationFilters
         {
            // Filter to decide whether to recurse into subdirectories.
            RecursionFilter = fsei =>
            {
               // Return true to continue recursion, false to skip.
               return !abortEnumeration;
            },


            // Filter to process Exception handling.
            ErrorFilter = delegate(int errorCode, string errorMessage, string pathProcessed)
            {
               if (abortEnumeration)
                  return true;


               gotException = errorCode == Alphaleonis.Win32.Win32Errors.ERROR_ACCESS_DENIED;
               if (gotException)
               {
                  exceptionCount++;

                  if (exceptionCount == exceptionCatch)
                     abortEnumeration = true;
               }


               // Report Exception.
               Console.WriteLine("\t#{0:N0}\t({1}) {2}: [{3}]", exceptionCount, errorCode, errorMessage, pathProcessed);


               // Return true to continue, false to throw the Exception.
               return gotException;
            }
         };
#else
         var cancelSource = new CancellationTokenSource();


         var filters = new Alphaleonis.Win32.Filesystem.DirectoryEnumerationFilters
         {
            // Used to abort the enumeration.
            CancellationToken = cancelSource.Token,


            // Filter to process Exception handling.
            ErrorFilter = delegate(int errorCode, string errorMessage, string pathProcessed)
            {
               gotException = errorCode == Alphaleonis.Win32.Win32Errors.ERROR_ACCESS_DENIED;
               if (gotException)
               {
                  exceptionCount++;

                  if (exceptionCount == exceptionCatch)
                     cancelSource.Cancel();
               }


               // Report Exception.
               Console.WriteLine("\t#{0:N0}\t({1}) {2}: [{3}]", exceptionCount, errorCode, errorMessage, pathProcessed);


               // Return true to continue, false to throw the Exception.
               return gotException;
            }
         };
#endif

         
         const Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions dirEnumOptions = Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive;

         var fsoCount = Alphaleonis.Win32.Filesystem.Directory.EnumerateFileSystemEntryInfos<string>(inputPath, dirEnumOptions, filters).Count();


         Console.WriteLine("\n\tFile system objects counted: {0:N0}", fsoCount);


         Assert.IsTrue(fsoCount > 0, "No file system entries enumerated, but it is expected.");

         Assert.IsTrue(gotException, "The Exception is not caught, but it is expected.");

         Assert.AreEqual(exceptionCatch, exceptionCount, "The number of caught Exceptions does not match, but it is expected.");
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Methods/NativeMethods.Handles.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      /// <summary>Closes an open object handle.</summary>
      /// <remarks>
      ///   <para>The CloseHandle function closes handles to the following objects:</para>
      ///   <para>Access token, Communications device, Console input, Console screen buffer, Event, File, File mapping, I/O completion port,
      ///   Job, Mailslot, Memory resource notification, Mutex, Named pipe, Pipe, Process, Semaphore, Thread, Transaction, Waitable
      ///   timer.</para>
      ///   <para>SetLastError is set to <c>false</c>.</para>
      ///   <para>Minimum supported client: Windows 2000 Professional [desktop apps | Windows Store apps]</para>
      ///   <para>Minimum supported server: Windows 2000 Server [desktop apps | Windows Store apps]</para>
      /// </remarks>
      /// <returns>
      ///   <para>If the function succeeds, the return value is nonzero.</para>
      ///   <para>If the function fails, the return value is zero. To get extended error information, call GetLastError.</para>
      ///   <para>If the application is running under a debugger, the function will throw an exception if it receives either a handle value
      ///   that is not valid or a pseudo-handle value.This can happen if you close a handle twice, or if you call CloseHandle on a handle
      ///   returned by the FindFirstFile function instead of calling the FindClose function.</para>
      /// </returns>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.Bool)]
      internal static extern bool CloseHandle(IntPtr hObject);
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>[AlphaFS] Checks if <paramref name="path"/> is in a logical drive format, such as "C:", "D:".</summary>
      /// <returns>true when <paramref name="path"/> is in a logical drive format, such as "C:", "D:".</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="path">The absolute path to check.</param>
      public static bool IsLogicalDrive(string path)
      {
         return IsLogicalDriveCore(path, false, PathFormat.FullPath);
      }


      /// <summary>[AlphaFS] Checks if <paramref name="path"/> is in a logical drive format, such as "C:", "D:".</summary>
      /// <returns>true when <paramref name="path"/> is in a logical drive format, such as "C:", "D:".</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="path">The absolute path to check.</param>
      /// <param name="isRegularPath"><c>true</c> indicates the path is already a regular path.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      internal static bool IsLogicalDriveCore(string path, bool isRegularPath, PathFormat pathFormat)
      {
         if (pathFormat != PathFormat.LongFullPath)
         {
            if (Utils.IsNullOrWhiteSpace(path))
               throw new ArgumentNullException("path");

            CheckSupportedPathFormat(path, true, true);
         }


         if (!isRegularPath)
            path = GetRegularPathCore(path, GetFullPathOptions.None, false);

         var regularPath = path.StartsWith(LogicalDrivePrefix, StringComparison.OrdinalIgnoreCase) ? path.Substring(LogicalDrivePrefix.Length) : path;
         
         var c = regularPath.ToUpperInvariant()[0];

         // Don't use char.IsLetter() here as that can be misleading; The only valid drive letters are: A-Z.

         return regularPath[1] == VolumeSeparatorChar && c >= 'A' && c <= 'Z';
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.GetProcessForFileLockCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>[AlphaFS] Gets a list of processes that have a lock on the file(s) specified by <paramref name="filePaths"/>.</summary>
      /// <returns>
      /// <c>null</c> when no processes found that are locking the file(s) specified by <paramref name="filePaths"/>.
      /// A list of processes locking the file(s) specified by <paramref name="filePaths"/>.
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="InvalidOperationException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="transaction"></param>
      /// <param name="filePaths">A list with one or more file paths.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Alphaleonis.Win32.Filesystem.NativeMethods.RmEndSession(System.UInt32)")]
      internal static Collection<Process> GetProcessForFileLockCore(KernelTransaction transaction, Collection<string> filePaths, PathFormat pathFormat)
      {
         if (!NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message);
         
         if (null == filePaths)
            throw new ArgumentNullException("filePaths");

         if (filePaths.Count == 0)
            throw new ArgumentOutOfRangeException("filePaths", "No paths specified.");


         var isLongPath = pathFormat == PathFormat.LongFullPath;
         var allPaths = isLongPath ? new Collection<string>(filePaths) : new Collection<string>();

         if (!isLongPath)
            foreach (var path in filePaths)
               allPaths.Add(Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck));




         uint sessionHandle;
         var success = NativeMethods.RmStartSession(out sessionHandle, 0, Guid.NewGuid().ToString()) == Win32Errors.ERROR_SUCCESS;

         var lastError = Marshal.GetLastWin32Error();
         if (!success)
            NativeError.ThrowException(lastError);




         var processes = new Collection<Process>();

         try
         {
            // A snapshot count of all running processes.
            var processesFound = (uint) Process.GetProcesses().Length;
            uint lpdwRebootReasons = 0;


            success = NativeMethods.RmRegisterResources(sessionHandle, (uint) allPaths.Count, allPaths.ToArray(), 0, null, 0, null) == Win32Errors.ERROR_SUCCESS;

            lastError = Marshal.GetLastWin32Error();
            if (!success)
               NativeError.ThrowException(lastError);


         GetList:

            var processInfo = new NativeMethods.RM_PROCESS_INFO[processesFound];
            var processesTotal = processesFound;


            lastError = NativeMethods.RmGetList(sessionHandle, out processesFound, ref processesTotal, processInfo, ref lpdwRebootReasons);


            // There would be no need for this because we already have a/the total number of running processes.
            if (lastError == Win32Errors.ERROR_MORE_DATA)
               goto GetList;


            if (lastError != Win32Errors.ERROR_SUCCESS)
               NativeError.ThrowException(lastError);


            for (var i = 0; i < processesTotal; i++)
            {
               try
               {
                  processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
               }

               // MSDN: The process specified by the processId parameter is not running. The identifier might be expired.
               catch (ArgumentException) {}
            }
         }
         finally
         {
            NativeMethods.RmEndSession(sessionHandle);
         }


         return processes.Count == 0 ? null : processes;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.IsUncPathCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>Determines if a path string is a valid Universal Naming Convention (UNC) path, optionally skip invalid path character check.</summary>
      /// <returns><c>true</c> if the specified path is a Universal Naming Convention (UNC) path, <c>false</c> otherwise.</returns>
      /// <param name="path">The path to check.</param>
      /// <param name="isRegularPath">When <c>true</c> indicates that <paramref name="path"/> is already in regular path format.</param>
      /// <param name="checkInvalidPathChars"><c>true</c> will check <paramref name="path"/> for invalid path characters.</param>
      [SecurityCritical]
      internal static bool IsUncPathCore(string path, bool isRegularPath, bool checkInvalidPathChars)
      {
         if (!isRegularPath)
            path = GetRegularPathCore(path, checkInvalidPathChars ? GetFullPathOptions.CheckInvalidPathChars : GetFullPathOptions.None, false);

         else if (checkInvalidPathChars)
            CheckInvalidPathChars(path, false, false);


         Uri uri;

         return Uri.TryCreate(path, UriKind.Absolute, out uri) && uri.IsUnc;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.CreateHardlinkCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>[AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file as a transacted operation. This function is only supported on the NTFS file system, and only for files, not directories.</summary>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="fileName">The name of the new file. This parameter cannot specify the name of a directory.</param>
      /// <param name="existingFileName">The name of the existing file. This parameter cannot specify the name of a directory.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>      
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlink")]
      [SecurityCritical]
      internal static void CreateHardLinkCore(KernelTransaction transaction, string fileName, string existingFileName, PathFormat pathFormat)
      {
         if (pathFormat != PathFormat.LongFullPath)
         {
            const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck;

            fileName = Path.GetExtendedLengthPathCore(transaction, fileName, pathFormat, options);
            existingFileName = Path.GetExtendedLengthPathCore(transaction, existingFileName, pathFormat, options);
         }


         if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista

            // CreateHardLink() / CreateHardLinkTransacted()
            // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
            // 2017-05-30: CreateHardLink() MSDN confirms LongPath usage: Starting with Windows 10, version 1607

            ? NativeMethods.CreateHardLink(fileName, existingFileName, IntPtr.Zero)
            : NativeMethods.CreateHardLinkTransacted(fileName, existingFileName, IntPtr.Zero, transaction.SafeHandle)))
         {
            var lastError = (uint) Marshal.GetLastWin32Error();

            switch (lastError)
            {
               case Win32Errors.ERROR_INVALID_FUNCTION:
                  throw new NotSupportedException(Resources.HardLinks_Not_Supported);

               default:
                  NativeError.ThrowException(lastError, existingFileName, fileName);
                  break;
            }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File.WriteAllText.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      #region .NET

      /// <summary>Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.</summary>
      /// <remarks>This method uses UTF-8 encoding without a Byte-Order Mark (BOM)</remarks>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The string to write to the file.</param>
      [SecurityCritical]
      public static void WriteAllText(string path, string contents)
      {
         WriteAppendAllLinesCore(null, path, new[] {contents}, new UTF8Encoding(false, true), false, false, PathFormat.RelativePath);
      }


      /// <summary>Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.</summary>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The string to write to the file.</param>
      /// <param name="encoding">The <see cref="Encoding"/> applied to the contents of the file.</param>
      [SecurityCritical]
      public static void WriteAllText(string path, string contents, Encoding encoding)
      {
         WriteAppendAllLinesCore(null, path, new[] {contents}, encoding, false, false, PathFormat.RelativePath);
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.</summary>
      /// <remarks>This method uses UTF-8 encoding without a Byte-Order Mark (BOM)</remarks>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The string to write to the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void WriteAllText(string path, string contents, PathFormat pathFormat)
      {
         WriteAppendAllLinesCore(null, path, new[] {contents}, new UTF8Encoding(false, true), false, false, pathFormat);
      }


      /// <summary>[AlphaFS] Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The string to write to the file.</param>
      /// <param name="encoding">The <see cref="Encoding"/> applied to the contents of the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void WriteAllText(string path, string contents, Encoding encoding, PathFormat pathFormat)
      {
         WriteAppendAllLinesCore(null, path, new[] {contents}, encoding, false, false, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetDirectoryNameCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>Returns the directory information for the specified path string.</summary>
      /// <returns>
      ///   Directory information for <paramref name="path"/>, or <c>null</c> if <paramref name="path"/> denotes a root directory or is
      ///   <c>null</c>. Returns <see cref="string.Empty"/> if <paramref name="path"/> does not contain directory information.
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <param name="path">The path of a file or directory.</param>
      /// <param name="checkInvalidPathChars"><c>true</c> will check <paramref name="path"/> for invalid path characters.</param>
      [SecurityCritical]
      internal static string GetDirectoryNameCore(string path, bool checkInvalidPathChars)
      {
         if (null != path)
         {
            var rootLength = GetRootLength(path, checkInvalidPathChars);

            if (path.Length > rootLength)
            {
               var length = path.Length;

               if (length == rootLength)
                  return null;

               while (length > rootLength && path[--length] != DirectorySeparatorChar && path[length] != AltDirectorySeparatorChar) { }

               return path.Substring(0, length).Replace(AltDirectorySeparatorChar, DirectorySeparatorChar);
            }
         }

         return null;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory.SetCurrentDirectory.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>
      /// Sets the application's current working directory to the specified directory.
      /// <para>
      ///   MSDN: Multithreaded applications and shared library code should not use the GetCurrentDirectory function and should avoid using relative path names.
      ///   The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,
      ///   therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.
      ///   <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,
      ///   for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
      ///   <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
      /// </para>
      /// </summary>
      /// <param name="path">The path to which the current working directory is set.</param>
      [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")]
      [SecurityCritical]
      public static void SetCurrentDirectory(string path)
      {
         SetCurrentDirectory(path, PathFormat.RelativePath);
      }


      /// <summary>
      /// Sets the application's current working directory to the specified directory.
      /// <para>
      ///   MSDN: Multithreaded applications and shared library code should not use the GetCurrentDirectory function and should avoid using relative path names.
      ///   The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,
      ///   therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.
      ///   <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,
      ///   for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
      ///   <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
      /// </para>
      /// </summary>
      /// <param name="path">The path to which the current working directory is set.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")]
      [SecurityCritical]
      public static void SetCurrentDirectory(string path, PathFormat pathFormat)
      {
         if (Utils.IsNullOrWhiteSpace(path))
            throw new ArgumentNullException("path");

         var fullCheck = pathFormat == PathFormat.RelativePath;
         Path.CheckSupportedPathFormat(path, fullCheck, fullCheck);
         var pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.AddTrailingDirectorySeparator);

         if (pathFormat == PathFormat.FullPath)
            pathLp = Path.GetRegularPathCore(pathLp, GetFullPathOptions.None, false);


         // SetCurrentDirectory()
         // 2016-09-29: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
         // 2017-05-30: MSDN confirms LongPath usage: Starting with Windows 10, version 1607

         var success = NativeMethods.SetCurrentDirectory(pathLp);

         var lastError = Marshal.GetLastWin32Error();
         if (!success)
            NativeError.ThrowException(lastError, pathLp);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.GetSize/AlphaFS_Directory.GetSize_NoStreamsOnRootFolder.cs<|end_filename|>
﻿/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   partial class SizeTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_GetSize_NoStreamsOnRootFolder_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_GetSize_NoStreamsOnRootFolder(false, false);
         AlphaFS_Directory_GetSize_NoStreamsOnRootFolder(true, false);
      }


      [TestMethod]
      public void AlphaFS_Directory_GetSize_NoStreamsOnRootFolder_Recursive_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_GetSize_NoStreamsOnRootFolder(false, true);
         AlphaFS_Directory_GetSize_NoStreamsOnRootFolder(true, true);
      }




      private void AlphaFS_Directory_GetSize_NoStreamsOnRootFolder(bool isNetwork, bool recurse)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.CreateTree(5);

            Console.WriteLine("Input Directory Path: [{0}]", folder.FullName);


            var folderSize = Alphaleonis.Win32.Filesystem.Directory.GetSize(folder.FullName, false, recurse);

            Console.WriteLine("\n\tTotal Directory size ({0}recursive): [{1:N0} bytes ({2})]\n", recurse ? string.Empty : "non-", folderSize, Alphaleonis.Utils.UnitSizeToText(folderSize));


            var folderProps = Alphaleonis.Win32.Filesystem.Directory.GetProperties(folder.FullName, Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.FilesAndFolders | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive);

            var count = 0;
            foreach (var key in folderProps.Keys)
               Console.WriteLine("\t\t#{0:000}\t{1, -17} = [{2}]", ++count, key, folderProps[key]);


            Assert.AreEqual(10, folderProps["Total"]);

            Assert.AreEqual(5, folderProps["Directory"]);

            Assert.AreEqual(5, folderProps["File"]);

            Assert.AreNotEqual(0, folderSize);


            if (recurse)
               Assert.AreEqual(folderProps["Size"], folderSize);
            else
               Assert.AreNotEqual(folderProps["Size"], folderSize);
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Globalization;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Contains information that the GetFileInformationByHandle function retrieves.</summary>
   [Serializable]
   public struct FileIdInfo : IComparable, IComparable<FileIdInfo>, IEquatable<FileIdInfo>
   {
      #region Fields

      [NonSerialized] private readonly long _volumeSerialNumber;
      [NonSerialized] private readonly long _fileIdHighPart;
      [NonSerialized] private readonly long _fileIdLowPart;

      #endregion // Fields


      #region Constructors

      internal FileIdInfo(NativeMethods.BY_HANDLE_FILE_INFORMATION fibh)
      {
         _volumeSerialNumber = fibh.dwVolumeSerialNumber;

         _fileIdHighPart = 0;
         _fileIdLowPart = NativeMethods.ToLong(fibh.nFileIndexHigh, fibh.nFileIndexLow);
      }


      internal FileIdInfo(NativeMethods.FILE_ID_INFO fi)
      {
         _volumeSerialNumber = fi.VolumeSerialNumber;

         // The identifier is stored in the array of fi.FileId so that the lowest byte is at index 0.

         ArrayToLong(fi.FileId, 0, 8, out _fileIdLowPart);
         ArrayToLong(fi.FileId, 8, 8, out _fileIdHighPart);
      }

      #endregion // Constructors


      #region Methods

      /// <summary>Construct the value stored in a byte array ordered in Little-Endian.</summary>
      /// <param name="fileId">The array containing the bytes.</param>
      /// <param name="startIndex">The starting index.</param>
      /// <param name="count">The number of bytes to convert.</param>
      /// <param name="value">The output value.</param>        
      private static void ArrayToLong(byte[] fileId, int startIndex, int count, out long value)
      {
         value = 0;

         for (var i = 0; i < count; i++)
            value |= (long) fileId[startIndex + i] << (8 * i);
      }


      /// <summary>Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.</summary>
      /// <param name="obj">An object to compare with this instance.</param>
      /// <returns>A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance precedes <paramref name="obj"/> in the sort order. Zero This instance occurs in the same position in the sort order as <paramref name="obj" />. Greater than zero This instance follows <paramref name="obj"/> in the sort order.</returns>        
      public int CompareTo(object obj)
      {
         if (null == obj)
            return 1;

         if (!(obj is FileIdInfo))
            throw new ArgumentException("Object must be of type FileIdInfo");

         return CompareTo((FileIdInfo) obj);
      }


      /// <summary>Compares the current object with another object of the same type.</summary>
      /// <param name="other">An object to compare with this object.</param>
      /// <returns>A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other" />. Greater than zero This object is greater than <paramref name="other" />.</returns>        
      public int CompareTo(FileIdInfo other)
      {
         return _volumeSerialNumber != other._volumeSerialNumber

            ? Math.Sign(_volumeSerialNumber - other._volumeSerialNumber)

            : (_fileIdHighPart != other._fileIdHighPart

               ? Math.Sign(_fileIdHighPart - other._fileIdHighPart)
               : Math.Sign(_fileIdLowPart - other._fileIdLowPart));
      }


      /// <summary>Returns a <see cref="string"/> that represents this instance.</summary>
      /// <returns>A <see cref="string"/> that represents this instance.</returns>
      public override string ToString()
      {
         unchecked
         {
            // The identifier is composed of 64-bit volume serial number and 128-bit file system entry identifier.

            return string.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2} : {3}-{4}-{5}",

               ((uint) (_volumeSerialNumber >> 32)).ToString("X", CultureInfo.InvariantCulture),
               ((ushort) (_volumeSerialNumber >> 16)).ToString("X", CultureInfo.InvariantCulture),
               ((ushort) _volumeSerialNumber).ToString("X", CultureInfo.InvariantCulture),

               _fileIdHighPart.ToString("X", CultureInfo.InvariantCulture),
               ((uint) (_fileIdLowPart >> 32)).ToString("X", CultureInfo.InvariantCulture),
               ((uint) _fileIdLowPart).ToString("X", CultureInfo.InvariantCulture));
         }
      }


      /// <summary>Returns a hash code for this instance.</summary>
      /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
      public override int GetHashCode()
      {
         unchecked
         {
            // _fileIdHighPart is 0 on NTFS and should be often 0 on ReFS, thus ignore it.

            return (int) _fileIdLowPart ^ ((int) (_fileIdLowPart >> 32) | (int) _volumeSerialNumber);
         }
      }


      /// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
      /// <param name="other">An object to compare with this object.</param>
      /// <returns>true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.</returns>
      public bool Equals(FileIdInfo other)
      {
         return _fileIdLowPart == other._fileIdLowPart && _fileIdHighPart == other._fileIdHighPart && _volumeSerialNumber == other._volumeSerialNumber;
      }


      /// <summary>Determines whether the specified <see cref="object" />, is equal to this instance.</summary>
      /// <param name="obj">The <see cref="object"/> to compare with this instance.</param>
      /// <returns><c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
      public override bool Equals(object obj)
      {
         return obj is FileIdInfo && Equals((FileIdInfo) obj);
      }
      

      /// <summary>Indicates whether the values of two specified <see cref="FileIdInfo"/> objects are equal.</summary>
      /// <param name="first">The first object to compare.</param>
      /// <param name="second">The second object to compare.</param>
      /// <returns>true if <paramref name="first"/> and <paramref name="second"/> are equal; otherwise, false.</returns>
      public static bool operator ==(FileIdInfo first, FileIdInfo second)
      {
         return first._fileIdLowPart == second._fileIdLowPart && first._fileIdHighPart == second._fileIdHighPart && first._volumeSerialNumber == second._volumeSerialNumber;
      }


      /// <summary>Indicates whether the values of two specified <see cref="FileIdInfo"/> objects are not equal.</summary>
      /// <param name="first">The first object to compare.</param>
      /// <param name="second">The second object to compare.</param>
      /// <returns>true if <paramref name="first"/> and <paramref name="second"/> are not equal; otherwise, false.</returns>
      public static bool operator !=(FileIdInfo first, FileIdInfo second)
      {
         return first._fileIdLowPart != second._fileIdLowPart || first._fileIdHighPart != second._fileIdHighPart || first._volumeSerialNumber != second._volumeSerialNumber;
      }


      /// <summary>Implements the operator &lt;.</summary>
      /// <param name="first">The first operand.</param>
      /// <param name="second">The second operand.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator <(FileIdInfo first, FileIdInfo second)
      {
         // Note: Must be tested in this order.

         return first._volumeSerialNumber < second._volumeSerialNumber || first._fileIdHighPart < second._fileIdHighPart || first._fileIdLowPart < second._fileIdLowPart;
      }


      /// <summary>Implements the operator &gt;.</summary>
      /// <param name="first">The first operand.</param>
      /// <param name="second">The second operand.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator >(FileIdInfo first, FileIdInfo second)
      {
         // Note: Must be tested in this order.

         return first._volumeSerialNumber > second._volumeSerialNumber || first._fileIdHighPart > second._fileIdHighPart || first._fileIdLowPart > second._fileIdLowPart;
      }

      #endregion // Methods
   }
}


<|start_filename|>src/AlphaFS/Network/Native Methods/NativeMethods.INetwork.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>The INetwork interface represents a network on the local machine. It can also represent a collection of network connections with a similar network signature.</summary>
      [ComImport, Guid("DCB00002-570F-4A9B-8D69-199FDBA5723B")]
      internal interface INetwork
      {
         // Do not change the order of these interface members.


         /// <summary>The GetName method returns the name of a network.</summary>
         /// <returns>Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         [return: MarshalAs(UnmanagedType.BStr)]
         string GetName();


         /// <summary>The SetName method sets or renames a network.</summary>
         /// <returns>Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values:
         /// E_POINTER: The pointer passed is NULL.
         /// HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE): The given name is too long.
         /// </returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         void SetName([In, MarshalAs(UnmanagedType.BStr)] string szNetworkNewName);


         /// <summary>The GetDescription method returns a description string for the network.</summary>
         /// <returns>Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         [return: MarshalAs(UnmanagedType.BStr)]
         string GetDescription();


         /// <summary>The SetDescription method sets or replaces the description for a network.</summary>
         /// <returns>Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values:
         /// E_POINTER: The pointer passed is NULL.
         /// HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE): The given name is too long.
         /// </returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         void SetDescription([In, MarshalAs(UnmanagedType.BStr)] string szDescription);


         /// <summary>The GetNetworkId method returns the unique identifier of a network.</summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         Guid GetNetworkId();


         /// <summary>The GetDomainType method returns the domain type of a network.</summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         DomainType GetDomainType();


         /// <summary>The GetNetworkConnections method returns an enumeration of all network connections for a network. A network can have multiple connections to it from different interfaces or different links from the same interface.</summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         [return: MarshalAs(UnmanagedType.Interface)]
         IEnumerable GetNetworkConnections();


         /// <summary>The GetTimeCreatedAndConnected method returns the local date and time when the network was created and connected.</summary>
         /// <returns>Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         void GetTimeCreatedAndConnected(out uint pdwLowDateTimeCreated, out uint pdwHighDateTimeCreated, out uint pdwLowDateTimeConnected, out uint pdwHighDateTimeConnected);


         /// <summary>The IsConnected property specifies if the network has any network connectivity.</summary>
         /// <returns>If TRUE, this network is connected; if FALSE, it is not.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         bool IsConnected
         {
            [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            get;
         }


         /// <summary>The IsConnectedToInternet property specifies if the network has internet connectivity.</summary>
         /// <returns>If TRUE, this network has connectivity to the internet; if FALSE, it does not.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         bool IsConnectedToInternet
         {
            [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            get;
         }


         /// <summary>The GetConnectivity method returns the connectivity state of the network.</summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         ConnectivityStates GetConnectivity();


         /// <summary>The GetCategory method returns the category of a network.</summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         NetworkCategory GetCategory();


         /// <summary>The SetCategory method sets the category of a network. Changes made take effect immediately. Callers of this API must be members of the Administrators group.</summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         void SetCategory([In] NetworkCategory newCategory);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateSymbolicLink_And_GetLinkTargetInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_JunctionsLinksTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>

      [TestMethod]
      public void AlphaFS_File_CreateSymbolicLink_And_GetLinkTargetInfo_LocalAndNetwork_Success()
      {
         UnitTestAssert.IsElevatedProcess();

         AlphaFS_File_CreateSymbolicLink_And_GetLinkTargetInfo(false);
         AlphaFS_File_CreateSymbolicLink_And_GetLinkTargetInfo(true);
      }


      private void AlphaFS_File_CreateSymbolicLink_And_GetLinkTargetInfo(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var fileLink = System.IO.Path.Combine(tempRoot.Directory.FullName, "FileLink-ToOriginalFile.txt");

            var fileInfo = new System.IO.FileInfo(System.IO.Path.Combine(tempRoot.Directory.FullName, "OriginalFile.txt"));
            using (fileInfo.CreateText()) {}

            Console.WriteLine("Input File Path: [{0}]", fileInfo.FullName);
            Console.WriteLine("Input File Link: [{0}]", fileLink);
            

            Alphaleonis.Win32.Filesystem.File.CreateSymbolicLink(fileLink, fileInfo.FullName);
            

            var lvi = Alphaleonis.Win32.Filesystem.File.GetLinkTargetInfo(fileLink);
            UnitTestConstants.Dump(lvi);
            Assert.IsTrue(lvi.PrintName.Equals(fileInfo.FullName, StringComparison.OrdinalIgnoreCase));


            UnitTestConstants.Dump(new System.IO.FileInfo(fileLink));

            var alphaFSFileInfo = new Alphaleonis.Win32.Filesystem.FileInfo(fileLink);
            UnitTestConstants.Dump(alphaFSFileInfo.EntryInfo);

            Assert.AreEqual(System.IO.File.Exists(alphaFSFileInfo.FullName), alphaFSFileInfo.Exists);
            Assert.IsFalse(alphaFSFileInfo.EntryInfo.IsDirectory);
            Assert.IsFalse(alphaFSFileInfo.EntryInfo.IsMountPoint);
            Assert.IsTrue(alphaFSFileInfo.EntryInfo.IsReparsePoint);
            Assert.IsTrue(alphaFSFileInfo.EntryInfo.IsSymbolicLink);
            Assert.AreEqual(alphaFSFileInfo.EntryInfo.ReparsePointTag, Alphaleonis.Win32.Filesystem.ReparsePointTag.SymLink);
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/UnitTest Utility/FileAssert.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Globalization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public static class FileAssert
   {
      public static void Exists(string filePath)
      {
         if (!System.IO.File.Exists(filePath))
            throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The file: [{0}] does not exist, but is expected to.", filePath));
      }


      public static void AreEqual(string expectedFilePath, string actualFilePath)
      {
         var position = 0;
         using (var s1 = System.IO.File.OpenRead(expectedFilePath))
         using (var s2 = System.IO.File.OpenRead(actualFilePath))
         {
            if (s1.Length != s2.Length)
               throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The files: [{0}] and \"{1}\" are not equal but are expected to be. Their size differs.", expectedFilePath, actualFilePath));

            var a = s1.ReadByte();
            var b = s2.ReadByte();

            if (a != b)
               throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The files: [{0}] and \"{1}\" are not equal but are expected to be. The first difference was at position: [{2}]", expectedFilePath, actualFilePath, position));

            position++;
         }
      }


      public static void AreNotEqual(string expectedFilePath, string actualFilePath)
      {
         var position = 0;
         using (var s1 = System.IO.File.OpenRead(expectedFilePath))
         using (var s2 = System.IO.File.OpenRead(actualFilePath))
         {
            if (s1.Length != s2.Length)
               return;

            var a = s1.ReadByte();
            var b = s2.ReadByte();

            if (a != b)
               return;

            position++;
         }

         throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The files: [{0}] and \"{1}\" are equal but are not expected to be.", expectedFilePath, actualFilePath));
      }


      public static void IsEncrypted(string filePath)
      {
         if ((System.IO.File.GetAttributes(filePath) & System.IO.FileAttributes.Encrypted) == 0)
            throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The file: [{0}] is not encrypted, but is expected to.", filePath));
      }


      public static void IsNotEncrypted(string filePath)
      {
         if ((System.IO.File.GetAttributes(filePath) & System.IO.FileAttributes.Encrypted) != 0)
            throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The file: [{0}] is encrypted, but is expected not to.", filePath));
      }


      public static void IsCompressed(string filePath)
      {
         if ((System.IO.File.GetAttributes(filePath) & System.IO.FileAttributes.Compressed) == 0)
            throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The file: [{0}] is not compressed, but is expected to.", filePath));
      }


      public static void IsNotCompressed(string filePath)
      {
         if ((System.IO.File.GetAttributes(filePath) & System.IO.FileAttributes.Compressed) != 0)
            throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The file: [{0}] is compressed, but is expected not to.", filePath));
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/File.Move/File.Move_ExistingFile.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class MoveTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void File_Move_ExistingFile_LocalAndNetwork_Success()
      {
         File_Move_ExistingFile(false);
         File_Move_ExistingFile(true);
      }


      private void File_Move_ExistingFile(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var srcFile = tempRoot.CreateFile();

            var dstFile = System.IO.Path.Combine(tempRoot.Directory.FullName, srcFile.Name + "-Moved.File");

            var fileLength = srcFile.Length;

            Console.WriteLine("Src File Path: [{0}] [{1}]", Alphaleonis.Utils.UnitSizeToText(srcFile.Length), srcFile.FullName);
            Console.WriteLine("Dst File Path: [{0}]", dstFile);


            var moveResult = Alphaleonis.Win32.Filesystem.File.Move(srcFile.FullName, dstFile, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);

            UnitTestConstants.Dump(moveResult);


            // Test against moveResult results.

            Assert.IsFalse(moveResult.IsCopy);
            Assert.IsTrue(moveResult.IsMove);
            Assert.IsFalse(moveResult.IsDirectory);
            Assert.IsTrue(moveResult.IsFile);

            Assert.AreEqual(fileLength, moveResult.TotalBytes);

            Assert.AreEqual(1, moveResult.TotalFiles);
            Assert.AreEqual(0, moveResult.TotalFolders);


            Assert.IsFalse(System.IO.File.Exists(srcFile.FullName), "The file does exists, but is expected not to.");
            Assert.IsTrue(System.IO.File.Exists(dstFile), "The file does not exists, but is expected to.");

            var fileLen = new System.IO.FileInfo(dstFile).Length;
            Assert.AreEqual(fileLength, fileLen, "The file copy is: {0} bytes, but is expected to be: {1} bytes.", fileLen, fileLength);


            Assert.IsFalse(System.IO.File.Exists(srcFile.FullName), "The original file exists, but is expected not to.");
         }


         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File.OpenTransacted.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.IO;
using System.Security;
using System.Security.AccessControl;
using FileStream = System.IO.FileStream;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path with read/write access.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">
      ///   A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents
      ///   of existing files are retained or overwritten.
      /// </param>
      /// <returns>A <see cref="FileStream"/> opened in the specified mode and path, with read/write access and not shared.</returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode)
      {
         return OpenCore(transaction, path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path with read/write access.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">
      ///   A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents
      ///   of existing files are retained or overwritten.
      /// </param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>A <see cref="FileStream"/> opened in the specified mode and path, with read/write access and not shared.</returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None, ExtendedFileAttributes.Normal, null, null, pathFormat);
      }


      #region Using FileAccess

      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path, with the specified mode and access.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">
      ///   A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents
      ///   of existing files are retained or overwritten.
      /// </param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param>
      /// <returns>
      ///   An unshared <see cref="FileStream"/> that provides access to the specified file, with the specified mode and access.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access)
      {
         return OpenCore(transaction, path, mode, access, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">
      ///   A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents
      ///   of existing files are retained or overwritten.
      /// </param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param>
      /// <param name="share">A <see cref="FileShare"/> value specifying the type of access other threads have to the file.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the
      ///   specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share)
      {
         return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath);
      }
      

      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path, with the specified mode and access.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">
      ///   A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents
      ///   of existing files are retained or overwritten.
      /// </param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>
      ///   An unshared <see cref="FileStream"/> that provides access to the specified file, with the specified mode and access.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, access, FileShare.None, ExtendedFileAttributes.Normal, null, null, pathFormat);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.</param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param>
      /// <param name="share">A <see cref="FileShare"/> value specifying the type of access other threads have to the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.</returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, null, null, pathFormat);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">
      ///   A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents
      ///   of existing files are retained or overwritten.
      /// </param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param>
      /// <param name="share">A <see cref="FileShare"/> value specifying the type of access other threads have to the file.</param>
      /// <param name="extendedAttributes">The extended attributes.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the
      ///   specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, access, share, extendedAttributes, null, null, pathFormat);
      }

      
      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
      {
         return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, bufferSize, null, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="useAsync">Specifies whether to use asynchronous I/O or synchronous I/O. However, note that the
      /// underlying operating system might not support asynchronous I/O, so when specifying true, the handle might be
      /// opened synchronously depending on the platform. When opened asynchronously, the BeginRead and BeginWrite methods
      /// perform better on large reads or writes, but they might be much slower for small reads or writes. If the
      /// application is designed to take advantage of asynchronous I/O, set the useAsync parameter to true. Using
      /// asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without
      /// redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
      {
         return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal | (useAsync ? ExtendedFileAttributes.Overlapped : ExtendedFileAttributes.Normal), bufferSize, null, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="options">A value that specifies additional file options.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
      {
         return OpenCore(transaction, path, mode, access, share, (ExtendedFileAttributes) options, bufferSize, null, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="extendedAttributes">The extended attributes specifying additional options.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes)
      {
         return OpenCore(transaction, path, mode, access, share, extendedAttributes, bufferSize, null, PathFormat.RelativePath);
      }
      

      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, bufferSize, null, pathFormat);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="useAsync">Specifies whether to use asynchronous I/O or synchronous I/O. However, note that the
      /// underlying operating system might not support asynchronous I/O, so when specifying true, the handle might be
      /// opened synchronously depending on the platform. When opened asynchronously, the BeginRead and BeginWrite methods
      /// perform better on large reads or writes, but they might be much slower for small reads or writes. If the
      /// application is designed to take advantage of asynchronous I/O, set the useAsync parameter to true. Using
      /// asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without
      /// redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal | (useAsync ? ExtendedFileAttributes.Overlapped : ExtendedFileAttributes.Normal), bufferSize, null, pathFormat);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="options">A value that specifies additional file options.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, access, share, (ExtendedFileAttributes) options, bufferSize, null, pathFormat);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="extendedAttributes">The extended attributes specifying additional options.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, access, share, extendedAttributes, bufferSize, null, pathFormat);
      }

      #endregion // Using FileAccess


      #region Using FileSystemRights

      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="options">A value that specifies additional file options.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options)
      {
         return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, null, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="extendedAttributes">Extended attributes specifying additional options.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes)
      {
         return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, null, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="options">A value that specifies additional file options.</param>
      /// <param name="security">A value that determines the access control and audit security for the file.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity security)
      {
         return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, security, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="extendedAttributes">Extended attributes specifying additional options.</param>
      /// <param name="security">A value that determines the access control and audit security for the file.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, FileSecurity security)
      {
         return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, security, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="options">A value that specifies additional file options.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, null, pathFormat);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="extendedAttributes">Extended attributes specifying additional options.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, null, pathFormat);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified  creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="options">A value that specifies additional file options.</param>
      /// <param name="security">A value that determines the access control and audit security for the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity security, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, security, pathFormat);
      }


      /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified  creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A constant that determines how to open or create the file.</param>
      /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the
      /// file.</param>
      /// <param name="share">A constant that determines how the file will be shared by processes.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The
      /// default buffer size is 4096.</param>
      /// <param name="extendedAttributes">Extended attributes specifying additional options.</param>
      /// <param name="security">A value that determines the access control and audit security for the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      /// <returns>
      ///   A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write
      ///   access and the specified sharing option.
      /// </returns>
      [SecurityCritical]
      public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, FileSecurity security, PathFormat pathFormat)
      {
         return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, security, pathFormat);
      }

      #endregion // Using FileSystemRights
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/AlphaFS_Directory.CreateDirectory_And_Delete_UsingMSDOSReservedNames.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class Directory_CreateDirectoryTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_CreateDirectory_And_Delete_UsingMSDOSReservedNames_Local_Success()
      {
         using (var tempRoot = new TemporaryDirectory(false))
         {
            Console.WriteLine("Input Directory Path: [{0}]\n", tempRoot.Directory.FullName);


            var msDosReservedNames = new[]
            {
               "CON", "PRN", "AUX", "NUL",
               "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
               "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
            };


            foreach (var msDosName in msDosReservedNames)
            {
               var folder = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(System.IO.Path.Combine(tempRoot.Directory.FullName, msDosName));

               Console.WriteLine("\tCreated Directory: [{0}]", folder.FullName);

               
               Assert.IsFalse(System.IO.Directory.Exists(folder.FullName));


               Assert.IsTrue(Alphaleonis.Win32.Filesystem.Directory.Exists(folder.FullName));


               // Create subfolder in the MSDOS reserved name folder.
               var subFolder = System.IO.Path.Combine(folder.FullName, tempRoot.RandomString);


               Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(subFolder);

               Console.WriteLine("\tCreated Directory: [{0}]\n", subFolder);


               Assert.IsTrue(Alphaleonis.Win32.Filesystem.Directory.Exists(subFolder));


               Alphaleonis.Win32.Filesystem.Directory.Delete(folder.FullName, true);

               Assert.IsFalse(Alphaleonis.Win32.Filesystem.Directory.Exists(folder.FullName));
            }
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Security/InternalPrivilegeEnabler.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;

namespace Alphaleonis.Win32.Security
{
   /// <summary>
   /// This object is used to enable a specific privilege for the currently running process during its lifetime. 
   /// It should be disposed as soon as the elevated privilege is no longer needed.
   /// For more information see the documentation on AdjustTokenPrivileges on MSDN.
   /// </summary>
   internal sealed class InternalPrivilegeEnabler : IDisposable
   {
      /// <summary>Initializes a new instance of the <see cref="PrivilegeEnabler"/> class and enabling the specified privilege for the currently running process.</summary>
      /// <param name="privilegeName">The name of the privilege.</param>
      [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
      [SecurityCritical]
      public InternalPrivilegeEnabler(Privilege privilegeName)
      {
         if (null == privilegeName)
            throw new ArgumentNullException("privilegeName");

         EnabledPrivilege = privilegeName;
         AdjustPrivilege(true);
      }


      /// <summary>
      /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
      /// In this case the privilege previously enabled will be disabled.
      /// </summary>            
      public void Dispose()
      {
         try
         {
            if (null != EnabledPrivilege)
               AdjustPrivilege(false);
         }
         finally
         {
            EnabledPrivilege = null;
         }
      }


      public Privilege EnabledPrivilege { get; private set; }


      /// <summary>Adjusts the privilege.</summary>
      /// <param name="enable"><c>true</c> the privilege will be enabled, otherwise disabled.</param>
      [SecurityCritical]
      private void AdjustPrivilege(bool enable)
      {
         using (var currentIdentity = WindowsIdentity.GetCurrent(TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges))
         {
            uint length;
            var hToken = currentIdentity.Token;
            var mOldPrivilege = new TOKEN_PRIVILEGES();

            var newPrivilege = new TOKEN_PRIVILEGES
            {
               PrivilegeCount = 1,
               Luid = Filesystem.NativeMethods.LongToLuid(EnabledPrivilege.LookupLuid()),

               // 2 = SePrivilegeEnabled;
               Attributes = (uint) (enable ? 2 : 0)
            };


            var success = NativeMethods.AdjustTokenPrivileges(hToken, false, ref newPrivilege, (uint) Marshal.SizeOf(mOldPrivilege), out mOldPrivilege, out length);

            var lastError = Marshal.GetLastWin32Error();
            if (!success)
               NativeError.ThrowException(lastError);


            // If no privilege was changed, we don't want to reset it.
            if (mOldPrivilege.PrivilegeCount == 0)
               EnabledPrivilege = null;
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path.Helpers.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      internal static void CheckInvalidUncPath(string path)
      {
         // Tackle: Path.GetFullPath(@"\\\\.txt"), but exclude "." which is the current directory.
         if (!IsLongPath(path) && path.StartsWith(UncPrefix, StringComparison.Ordinal))
         {
            var tackle = GetRegularPathCore(path, GetFullPathOptions.None, false).TrimStart(DirectorySeparatorChar, AltDirectorySeparatorChar);

            if (tackle.Length >= 2 && tackle[0] == CurrentDirectoryPrefixChar)

               throw new ArgumentException(Resources.UNC_Path_Should_Match_Format, "path");
         }
      }


      /// <summary>Checks that the given path format is supported.</summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="NotSupportedException"/>
      /// <param name="path">A path to the file or directory.</param>
      /// <param name="checkInvalidPathChars">Checks that the path contains only valid path-characters.</param>
      /// <param name="checkAdditional">.</param>
      internal static void CheckSupportedPathFormat(string path, bool checkInvalidPathChars, bool checkAdditional)
      {
         // "."
         if (Utils.IsNullOrWhiteSpace(path) || path.Length == 1)
            return;

         var regularPath = GetRegularPathCore(path, GetFullPathOptions.None, false);

         var isArgumentException = regularPath[0] == VolumeSeparatorChar;

         var throwException = isArgumentException || regularPath.Length >= 2 && regularPath.IndexOf(VolumeSeparatorChar, 2) != -1;

         if (throwException)
         {
            if (isArgumentException)
               throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Unsupported_Path_Format, regularPath), "path");

            throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Resources.Unsupported_Path_Format, regularPath));
         }

         if (checkInvalidPathChars)
            CheckInvalidPathChars(path, checkAdditional, false);
      }


      /// <summary>Checks that the path contains only valid path-characters.</summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="path">A path to the file or directory.</param>
      /// <param name="checkAdditional"><c>true</c> also checks for ? and * characters.</param>
      /// <param name="allowEmpty">When <c>false</c>, throws an <see cref="ArgumentException"/>.</param>
      [SecurityCritical]
      private static void CheckInvalidPathChars(string path, bool checkAdditional, bool allowEmpty)
      {
         if (null == path)
            throw new ArgumentNullException("path");

         if (!allowEmpty && (path.Trim().Length == 0 || Utils.IsNullOrWhiteSpace(path)))
            throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "path");

         // Will fail on a Unicode path.
         var pathRp = GetRegularPathCore(path, GetFullPathOptions.None, allowEmpty);


         // Handle "\\?\GlobalRoot\" and "\\?\Volume" prefixes.
         if (pathRp.StartsWith(GlobalRootPrefix, StringComparison.OrdinalIgnoreCase))
            pathRp = pathRp.ReplaceIgnoreCase(GlobalRootPrefix, string.Empty);

         if (pathRp.StartsWith(VolumePrefix, StringComparison.OrdinalIgnoreCase))
            pathRp = pathRp.ReplaceIgnoreCase(VolumePrefix, string.Empty);


         for (int index = 0, l = pathRp.Length; index < l; ++index)
         {
            int num = pathRp[index];
            switch (num)
            {
               case 34: // "  (quote)
               case 60: // <  (less than)
               case 62: // >  (greater than)
               case 124: // |  (pipe)
                  throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Illegal_Characters_In_Path, (char) num), "path");

               default:
                  // 32: space
                  if (num >= 32 && (!checkAdditional || num != WildcardQuestionChar && num != WildcardStarMatchAllChar))
                     continue;

                  goto case 34;
            }
         }
      }


      [SecurityCritical]
      internal static string GetCleanExceptionPath(string path)
      {
         return GetRegularPathCore(path, GetFullPathOptions.None, true).TrimEnd(DirectorySeparatorChar, WildcardStarMatchAllChar);
      }


      /// <summary>Gets the path as a long full path.</summary>
      /// <returns>The path as an extended length path.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The path to convert.</param>
      /// <param name="pathFormat">The path format to use.</param>
      /// <param name="options">Options for controlling the operation. Note that on .NET 3.5 the TrimEnd option has no effect.</param>
      [SecurityCritical]
      internal static string GetExtendedLengthPathCore(KernelTransaction transaction, string path, PathFormat pathFormat, GetFullPathOptions options)
      {
         if (null == path)
            return null;


         switch (pathFormat)
         {
            case PathFormat.LongFullPath:
               if (options != GetFullPathOptions.None)
               {
                  // If pathFormat equals LongFullPath it is possible that the trailing backslashg ('\') is not added or removed.
                  // Prevent that.

                  options &= ~GetFullPathOptions.CheckAdditional;
                  options &= ~GetFullPathOptions.CheckInvalidPathChars;
                  options &= ~GetFullPathOptions.FullCheck;
                  options &= ~GetFullPathOptions.TrimEnd;

                  path = ApplyFullPathOptions(path, options);
               }

               return path;


            case PathFormat.FullPath:
               return GetLongPathCore(path, GetFullPathOptions.None);

            case PathFormat.RelativePath:
#if NET35
               // .NET 3.5 the TrimEnd option has no effect.
               options = options & ~GetFullPathOptions.TrimEnd;
#endif
               return GetFullPathCore(transaction, false, path, GetFullPathOptions.AsLongPath | options);

            default:
               throw new ArgumentException("Invalid value: " + pathFormat, "pathFormat");
         }
      }


      [SecurityCritical]
      internal static int GetRootLength(string path, bool checkInvalidPathChars)
      {
         if (checkInvalidPathChars)
            CheckInvalidPathChars(path, false, false);

         var index = 0;
         var length = path.Length;

         if (length >= 1 && IsDVsc(path[0], false))
         {
            index = 1;

            if (length >= 2 && IsDVsc(path[1], false))
            {
               index = 2;
               var num = 2;

               while (index < length && (!IsDVsc(path[index], false) || --num > 0))
                  ++index;
            }
         }

         else if (length >= 2 && IsDVsc(path[1], true))
         {
            index = 2;

            if (length >= 3 && IsDVsc(path[2], false))
               ++index;
         }

         return index;
      }


      /// <summary>Check if <paramref name="c"/> is a directory- and/or volume-separator character.</summary>
      /// <returns><c>true</c> if <paramref name="c"/> is a separator character.</returns>
      /// <param name="c">The character to check.</param>
      /// <param name="checkSeparatorChar">
      ///   If <c>null</c>, checks for all separator characters: <see cref="DirectorySeparatorChar"/>,
      ///   <see cref="AltDirectorySeparatorChar"/> and <see cref="VolumeSeparatorChar"/>
      ///   If <c>false</c>, only checks for: <see cref="DirectorySeparatorChar"/> and <see cref="AltDirectorySeparatorChar"/>
      ///   If <c>true</c> only checks for: <see cref="VolumeSeparatorChar"/>
      /// </param>
      [SecurityCritical]
      internal static bool IsDVsc(char c, bool? checkSeparatorChar)
      {
         return checkSeparatorChar == null

            // Check for all separator characters.
            ? c == DirectorySeparatorChar || c == AltDirectorySeparatorChar || c == VolumeSeparatorChar

            // Check for some separator characters.
            : ((bool) checkSeparatorChar
               ? c == VolumeSeparatorChar
               : c == DirectorySeparatorChar || c == AltDirectorySeparatorChar);
      }


      [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
      [SuppressMessage("Microsoft.Performance", "CA1809:AvoidExcessiveLocals")]
      private static string NormalizePath(string path, GetFullPathOptions options)
      {
         var newBuffer = new StringBuilder(NativeMethods.MaxPathUnicode);
         var index = 0;
         uint numSpaces = 0;
         uint numDots = 0;
         var fixupDirectorySeparator = false;


         // Number of significant chars other than potentially suppressible dots and spaces since the last directory or volume separator char.

         uint numSigChars = 0;


         // Index of last significant character.

         var lastSigChar = -1;


         // Whether this segment of the path (not the complete path) started with a volume separator char.  Reject "c:...".

         var startedWithVolumeSeparator = false;
         var firstSegment = true;
         var lastDirectorySeparatorPos = 0;


         // LEGACY: This code is here for backwards compatibility reasons.
         // It ensures that "\\foo.cs\bar.cs" stays "\\foo.cs\bar.cs" instead of being turned into "\foo.cs\bar.cs".

         if (path.Trim().Length > 0 && (path[0] == DirectorySeparatorChar || path[0] == AltDirectorySeparatorChar))
         {
            newBuffer.Append(DirectorySeparatorChar);
            index++;
            lastSigChar = 0;
         }


         // Normalize the string, stripping out redundant dots, spaces, and slashes.

         while (index < path.Length)
         {
            var currentChar = path[index];

            // We handle both directory separators and dots specially.  For 
            // directory separators, we consume consecutive appearances.  
            // For dots, we consume all dots beyond the second in 
            // succession.  All other characters are added as is.  In 
            // addition we consume all spaces after the last other char
            // in a directory name up until the directory separator.

            if (currentChar == DirectorySeparatorChar || currentChar == AltDirectorySeparatorChar)
            {
               // If we have a path like "123.../foo", remove the trailing dots.
               // However, if we found "c:\temp\..\bar" or "c:\temp\...\bar", do not.
               // Also remove trailing spaces from both files & directory names.
               // This was agreed on with the OS team to fix undeletable directory
               // names ending in spaces.

               // If we saw a '\' as the previous last significant character and
               // are simply going to write out dots, suppress them.
               // If we only contain dots and slashes though, only allow
               // a string like [dot]+ [space]*.  Ignore everything else.
               // Legal: "\.. \", "\...\", "\. \"
               // Illegal: "\.. .\", "\. .\", "\ .\"

               if (numSigChars == 0)
               {
                  // Dot and space handling.
                  if (numDots > 0)
                  {
                     newBuffer.Append(NormalizePathDotSpaceHandler(path, lastSigChar, numDots, startedWithVolumeSeparator));

                     fixupDirectorySeparator = false;

                     // Continue in this case, potentially writing out '\'.
                  }


                  if (numSpaces > 0 && firstSegment)
                  {
                     // Handle strings like " \\server\share".

                     if (index + 1 < path.Length && (path[index + 1] == DirectorySeparatorChar || path[index + 1] == AltDirectorySeparatorChar))

                        newBuffer.Append(DirectorySeparatorChar);
                  }
               }


               numDots = 0;
               numSpaces = 0; // Suppress trailing spaces

               if (!fixupDirectorySeparator)
               {
                  fixupDirectorySeparator = true;
                  newBuffer.Append(DirectorySeparatorChar);
               }

               numSigChars = 0;
               lastSigChar = index;
               startedWithVolumeSeparator = false;
               firstSegment = false;


               var thisPos = newBuffer.Length - 1;

               if (thisPos - lastDirectorySeparatorPos - 1 > NativeMethods.MaxDirectoryLength)
                  throw new PathTooLongException(path);

               lastDirectorySeparatorPos = thisPos;
            } // if (Found directory separator)

            else
               switch (currentChar)
               {
                  case CurrentDirectoryPrefixChar:
                     // Reduce only multiple .'s only after slash to 2 dots. For
                     // instance a...b is a valid file name.
                     numDots++;
                     // Don't flush out non-terminal spaces here, because they may in
                     // the end not be significant.  Turn "c:\ . .\foo" -> "c:\foo"
                     // which is the conclusion of removing trailing dots & spaces,
                     // as well as folding multiple '\' characters.
                     break;

                  case ' ':
                     numSpaces++;
                     break;

                  default: // Normal character logic
                     fixupDirectorySeparator = false;

                     // To reject strings like "C:...\foo" and "C  :\foo"
                     if (firstSegment && currentChar == VolumeSeparatorChar)
                     {
                        // Only accept "C:", not "c :" or ":"
                        // Get a drive letter or ' ' if index is 0.
                        var driveLetter = index > 0 ? path[index - 1] : ' ';

                        var validPath = numDots == 0 && numSigChars >= 1 && driveLetter != ' ';

                        if (!validPath)
                           throw new ArgumentException(path, "path");


                        startedWithVolumeSeparator = true;
                        // We need special logic to make " c:" work, we should not fix paths like "  foo::$DATA"
                        if (numSigChars > 1)
                        {
                           // Common case, simply do nothing.
                           var spaceCount = 0; // How many spaces did we write out, numSpaces has already been reset.

                           while (spaceCount < newBuffer.Length && newBuffer[spaceCount] == ' ')
                              spaceCount++;

                           if (numSigChars - spaceCount == 1)
                           {
                              newBuffer.Length = 0;
                              newBuffer.Append(driveLetter);
                              // Overwrite spaces, we need a special case to not break "  foo" as a relative path.
                           }
                        }

                        numSigChars = 0;
                     }

                     else
                        numSigChars += 1 + numDots + numSpaces;


                     // Copy any spaces & dots since the last significant character to here.
                     // Note we only counted the number of dots & spaces, and don't know what order they're in.  Hence the copy.

                     if (numDots > 0 || numSpaces > 0)
                     {
                        var numCharsToCopy = lastSigChar >= 0 ? index - lastSigChar - 1 : index;

                        if (numCharsToCopy > 0)
                        {
                           for (var i = 0; i < numCharsToCopy; i++)

                              newBuffer.Append(path[lastSigChar + 1 + i]);
                        }

                        numDots = 0;
                        numSpaces = 0;
                     }

                     newBuffer.Append(currentChar);
                     lastSigChar = index;
                     break;
               }

            index++;
         }


         if (newBuffer.Length - 1 - lastDirectorySeparatorPos > NativeMethods.MaxDirectoryLength)
            throw new PathTooLongException(path);


         // Drop any trailing dots and spaces from file & directory names, EXCEPT we MUST make sure that "C:\foo\.." is correctly handled.
         // Also handle "C:\foo\." -> "C:\foo", while "C:\." -> "C:\"

         if (numSigChars == 0)
         {
            // Dot and space handling.
            if (numDots > 0)
               newBuffer.Append(NormalizePathDotSpaceHandler(path, lastSigChar, numDots, startedWithVolumeSeparator));
         }


         // If we ended up eating all the characters, bail out.

         if (newBuffer.Length == 0)
            throw new ArgumentException(path, "path");


         // Disallow URL's here.  Some of our other Win32 API calls will reject them later, so we might be better off rejecting them here.
         // Note we've probably turned them into "file:\D:\foo.tmp" by now.
         // But for compatibility, ensure that callers that aren't doing a full check aren't rejected here.

         if ((options & GetFullPathOptions.FullCheck) != 0)
         {
            var newBufferString = newBuffer.ToString();

            if (newBufferString.StartsWith(Uri.UriSchemeHttp + ":", StringComparison.OrdinalIgnoreCase) ||
                newBufferString.StartsWith(Uri.UriSchemeFile + ":", StringComparison.OrdinalIgnoreCase))
               throw new ArgumentException(path, "path");
         }


         // Call the Win32 API to do the final canonicalization step.

         const int result = 1;

         // Throw an ArgumentException for paths like \\, \\server, \\server\
         // This check can only be properly done after normalizing, so // \\foo\.. will be properly rejected.
         // Also, reject \\?\GLOBALROOT\ (an internal kernel path) because it provides aliases for drives.

         if (newBuffer.Length > 1 && newBuffer[0] == DirectorySeparatorChar && newBuffer[1] == DirectorySeparatorChar)
         {
            var startIndex = 2;

            while (startIndex < result)
            {
               if (newBuffer[startIndex] == DirectorySeparatorChar)
               {
                  startIndex++;
                  break;
               }

               startIndex++;
            }

            if (startIndex == result)
               throw new ArgumentException(path, "path");
         }


         return newBuffer.ToString();
      }


      /// <summary>Dot and space handling.</summary>
      private static StringBuilder NormalizePathDotSpaceHandler(string path, int lastSigChar, uint numDots, bool startedWithVolumeSeparator)
      {
         var newBuffer = new StringBuilder(NativeMethods.MaxPathUnicode);

         // Look for ".[space]*" or "..[space]*".

         var start = lastSigChar + 1;

         if (path[start] != CurrentDirectoryPrefixChar)
            throw new ArgumentException(path, "path");


         // Only allow "[dot]+[space]*", and normalize the legal ones to "." or "..".

         if (numDots >= 2)
         {
            // Reject "C:...".

            if (startedWithVolumeSeparator && numDots > 2)
               throw new ArgumentException(path, "path");


            if (path[start + 1] == CurrentDirectoryPrefixChar)
            {
               // Search for a space in the middle of the dots and throw.

               for (var i = start + 2; i < start + numDots; i++)
               {
                  if (path[i] != CurrentDirectoryPrefixChar)
                     throw new ArgumentException(path, "path");
               }

               numDots = 2;
            }

            else
            {
               if (numDots > 1)
                  throw new ArgumentException(path, "path");

               numDots = 1;
            }
         }


         if (numDots == 2)
            newBuffer.Append(CurrentDirectoryPrefixChar);


         newBuffer.Append(CurrentDirectoryPrefixChar);

         return newBuffer;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/UnitTests/AlphaFS_OperatingSystemTest.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   /// <summary>This is a test class for all OperatingSystem class Unit Tests.</summary>
   [TestClass]
   public class AlphaFS_OperatingSystemTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_OperatingSystem()
      {
         UnitTestConstants.PrintUnitTestHeader(false);

         Console.WriteLine("VersionName          : [{0}]", Alphaleonis.Win32.OperatingSystem.VersionName);
         Console.WriteLine("OsVersion            : [{0}]", Alphaleonis.Win32.OperatingSystem.OSVersion);
         Console.WriteLine("ServicePackVersion   : [{0}]", Alphaleonis.Win32.OperatingSystem.ServicePackVersion);
         Console.WriteLine("IsServer             : [{0}]", Alphaleonis.Win32.OperatingSystem.IsServer);
         Console.WriteLine("IsWow64Process       : [{0}]", Alphaleonis.Win32.OperatingSystem.IsWow64Process);
         Console.WriteLine("ProcessorArchitecture: [{0}]", Alphaleonis.Win32.OperatingSystem.ProcessorArchitecture);

         Console.WriteLine("\nOperatingSystem.IsAtLeast()\n");


         var isTrue = Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.Earlier);
         Console.WriteLine("\tOS Earlier           : [{0}]", isTrue);

         Assert.IsTrue(isTrue);


         isTrue = Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.Windows2000);
         Console.WriteLine("\tWindows 2000         : [{0}]", isTrue);

         Assert.IsTrue(isTrue);


         isTrue = Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.WindowsXP);
         Console.WriteLine("\tWindows XP           : [{0}]", isTrue);

         Assert.IsTrue(isTrue);


         Console.WriteLine("\tWindows Vista        : [{0}]", Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.WindowsVista));
         Console.WriteLine("\tWindows 7            : [{0}]", Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.Windows7));
         Console.WriteLine("\tWindows 8            : [{0}]", Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.Windows8));
         Console.WriteLine("\tWindows 8.1          : [{0}]", Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.Windows81));
         Console.WriteLine("\tWindows 10           : [{0}]", Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.Windows10));

         Console.WriteLine("\tWindows Server 2003  : [{0}]", Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.WindowsServer2003));
         Console.WriteLine("\tWindows Server 2008  : [{0}]", Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.WindowsServer2008));
         Console.WriteLine("\tWindows Server 2008R2: [{0}]", Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.WindowsServer2008R2));
         Console.WriteLine("\tWindows Server 2012  : [{0}]", Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.WindowsServer2012));
         Console.WriteLine("\tWindows Server 2012R2: [{0}]", Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.WindowsServer2012R2));
         Console.WriteLine("\tWindows Server 2016  : [{0}]", Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.WindowsServer2016));


         var isFalse = Alphaleonis.Win32.OperatingSystem.IsAtLeast(Alphaleonis.Win32.OperatingSystem.EnumOsName.Later);

         Console.WriteLine("\tOS Later             : [{0}]", isFalse);

         Assert.IsFalse(isFalse);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory.GetLogicalDrives.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;

namespace AlphaFS.UnitTest
{
   partial class DirectoryTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void Directory_GetLogicalDrives_Local_Success()
      {
         Directory_GetLogicalDrives();
      }


      private void Directory_GetLogicalDrives()
      {
         UnitTestConstants.PrintUnitTestHeader(false);


         var drivesSystemIO = System.IO.Directory.GetLogicalDrives().OrderBy(driveName => driveName).ToArray();

         var drivesAlphaFS = Alphaleonis.Win32.Filesystem.Directory.GetLogicalDrives().OrderBy(driveName => driveName).ToArray();


         Assert.AreEqual(drivesSystemIO.Length, drivesAlphaFS.Length, "The number of logical drives does not match, but is expected to.");

         
         var drivesCount = 0;
         
         foreach (var driveName in drivesAlphaFS)
         {
            Console.WriteLine("\t#{0:000}\tLogical Drive: [{1}]\n", drivesCount, driveName);

            Assert.AreEqual(drivesSystemIO[drivesCount++], driveName, "The logical drive drive name does not match, but is expected to.");
         }
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/File_AccessControl/File.SetAccessControl.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Security.AccessControl;
using System.Security.Principal;

namespace AlphaFS.UnitTest
{
   public partial class AccessControlTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void File_SetAccessControl_LocalAndNetwork_Success()
      {
         UnitTestAssert.IsElevatedProcess();

         File_SetAccessControl(false);
         File_SetAccessControl(true);
      }


      private void File_SetAccessControl(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var file = tempRoot.CreateFile();

            Console.WriteLine("Input File Path: [{0}]", file.FullName);


            var sysIO = System.IO.File.GetAccessControl(file.FullName);
            var sysIOaccessRules = sysIO.GetAccessRules(true, true, typeof(NTAccount));


            var alphaFS = Alphaleonis.Win32.Filesystem.File.GetAccessControl(file.FullName);
            var alphaFSaccessRules = alphaFS.GetAccessRules(true, true, typeof(NTAccount));
            

            Console.WriteLine("\n\tSystem.IO rules found: [{0}]\n\tAlphaFS rules found  : [{1}]", sysIOaccessRules.Count, alphaFSaccessRules.Count);


            Assert.AreEqual(sysIOaccessRules.Count, alphaFSaccessRules.Count);


            // Sanity check.
            UnitTestConstants.TestAccessRules(sysIO, alphaFS);


            // Remove inherited properties.
            // Passing true for first parameter protects the new permission from inheritance,
            // and second parameter removes the existing inherited permissions 
            Console.WriteLine("\n\tRemove inherited properties and persist it.");
            alphaFS.SetAccessRuleProtection(true, false);
            Alphaleonis.Win32.Filesystem.File.SetAccessControl(file.FullName, alphaFS, AccessControlSections.Access);


            // Re-read, using instance methods.
            var sysIOfi = new System.IO.FileInfo(file.FullName);
            var alphaFSfi = new Alphaleonis.Win32.Filesystem.FileInfo(file.FullName);

            sysIO = sysIOfi.GetAccessControl(AccessControlSections.Access);
            alphaFS = alphaFSfi.GetAccessControl(AccessControlSections.Access);

            // Sanity check.
            UnitTestConstants.TestAccessRules(sysIO, alphaFS);


            // Restore inherited properties.
            Console.WriteLine("\n\tRestore inherited properties and persist it.");
            alphaFS.SetAccessRuleProtection(false, true);
            Alphaleonis.Win32.Filesystem.File.SetAccessControl(file.FullName, alphaFS, AccessControlSections.Access);


            // Re-read.
            sysIO = System.IO.File.GetAccessControl(file.FullName, AccessControlSections.Access);
            alphaFS = Alphaleonis.Win32.Filesystem.File.GetAccessControl(file.FullName, AccessControlSections.Access);
            
            // Sanity check.
            UnitTestConstants.TestAccessRules(sysIO, alphaFS);
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.DeleteDosDevice.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Deletes an MS-DOS device name.</summary>
      /// <param name="deviceName">An MS-DOS device name specifying the device to delete.</param>      
      [SecurityCritical]
      public static void DeleteDosDevice(string deviceName)
      {
         DefineDosDeviceCore(false, deviceName, null, DosDeviceAttributes.RemoveDefinition, false);
      }

      /// <summary>[AlphaFS] Deletes an MS-DOS device name.</summary>
      /// <param name="deviceName">An MS-DOS device name string specifying the device to delete.</param>
      /// <param name="targetPath">
      ///   A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the
      ///   <see cref="DosDeviceAttributes.RawTargetPath"/> flag is specified, in which case this string is a path string.
      /// </param>      
      [SecurityCritical]
      public static void DeleteDosDevice(string deviceName, string targetPath)
      {
         DefineDosDeviceCore(false, deviceName, targetPath, DosDeviceAttributes.RemoveDefinition, false);
      }

      /// <summary>[AlphaFS] Deletes an MS-DOS device name.</summary>
      /// <param name="deviceName">An MS-DOS device name string specifying the device to delete.</param>
      /// <param name="targetPath">
      ///   A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the
      ///   <see cref="DosDeviceAttributes.RawTargetPath"/> flag is specified, in which case this string is a path string.
      /// </param>
      /// <param name="exactMatch">
      ///   Only delete MS-DOS device on an exact name match. If <paramref name="exactMatch"/> is <c>true</c>,
      ///   <paramref name="targetPath"/> must be the same path used to create the mapping.
      /// </param>      
      [SecurityCritical]
      public static void DeleteDosDevice(string deviceName, string targetPath, bool exactMatch)
      {
         DefineDosDeviceCore(false, deviceName, targetPath, DosDeviceAttributes.RemoveDefinition, exactMatch);
      }

      /// <summary>[AlphaFS] Deletes an MS-DOS device name.</summary>
      /// <param name="deviceName">An MS-DOS device name string specifying the device to delete.</param>
      /// <param name="targetPath">
      ///   A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the
      ///   <see cref="DosDeviceAttributes.RawTargetPath"/> flag is specified, in which case this string is a path string.
      /// </param>
      /// <param name="deviceAttributes">
      ///   The controllable aspects of the DefineDosDevice function <see cref="DosDeviceAttributes"/> flags which will be combined with the
      ///   default.
      /// </param>
      /// <param name="exactMatch">
      ///   Only delete MS-DOS device on an exact name match. If <paramref name="exactMatch"/> is <c>true</c>,
      ///   <paramref name="targetPath"/> must be the same path used to create the mapping.
      /// </param>      
      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      [SecurityCritical]
      public static void DeleteDosDevice(string deviceName, string targetPath, DosDeviceAttributes deviceAttributes, bool exactMatch)
      {
         DefineDosDeviceCore(false, deviceName, targetPath, deviceAttributes, exactMatch);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_RetryFails2Times_ThrowsUnauthorizedAccessException.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading;

namespace AlphaFS.UnitTest
{
   public partial class CopyTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_Copy_RetryFails2Times_ThrowsUnauthorizedAccessException_LocalAndNetwork()
      {
         AlphaFS_Directory_Copy_RetryFails2Times_ThrowsUnauthorizedAccessException(false);
         AlphaFS_Directory_Copy_RetryFails2Times_ThrowsUnauthorizedAccessException(true);
      }


      private void AlphaFS_Directory_Copy_RetryFails2Times_ThrowsUnauthorizedAccessException(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folderSrc = tempRoot.CreateDirectory().FullName;
            var folderDst = tempRoot.CreateDirectory().FullName;

            Console.WriteLine("Destination Directory Path: [{0}]\n", folderDst);

            
            var existingFileSrc = System.IO.Path.Combine(folderSrc, "ExistingFile.txt");
            var existingFileDst = System.IO.Path.Combine(folderDst, "ExistingFile.txt");

            System.IO.File.WriteAllText(existingFileSrc, DateTime.Now.ToString(CultureInfo.CurrentCulture));
            System.IO.File.WriteAllText(existingFileDst, DateTime.Now.ToString(CultureInfo.CurrentCulture));

            
            // Set destination file read-only attribute so that a System.UnauthorizedAccessException is triggered on folder copy.

            System.IO.File.SetAttributes(existingFileDst, System.IO.FileAttributes.ReadOnly);




            // Copy folder with retry enabled.

            var errorCount = 0;

            using (var cancelSource = new CancellationTokenSource())
            {
               var filters = new Alphaleonis.Win32.Filesystem.DirectoryEnumerationFilters
               {
                  // Used to abort the enumeration.
                  CancellationToken = cancelSource.Token,

                  ErrorRetry = 2,

                  ErrorRetryTimeout = 3,

                  ErrorFilter = delegate(int errorCode, string errorMessage, string pathProcessed)
                  {
                     // Report Exception.
                     Console.WriteLine("\tErrorFilter: Attempt #{0:N0}: ({1}) {2}: [{3}]", ++errorCount, errorCode, errorMessage, pathProcessed);

                     // Return true to continue, false to throw the Exception.
                     return true;
                  }
               };
               

               var sw = Stopwatch.StartNew();

               UnitTestAssert.ThrowsException<UnauthorizedAccessException>(() => Alphaleonis.Win32.Filesystem.Directory.Copy(folderSrc, folderDst, Alphaleonis.Win32.Filesystem.CopyOptions.None, filters));

               sw.Stop();


               var waitTime = filters.ErrorRetry * filters.ErrorRetryTimeout;

               Assert.AreEqual(6, waitTime, "The timeout is not what is expected.");
               Assert.AreEqual(6, sw.Elapsed.Seconds, "The timeout is not what is expected.");
               Assert.AreEqual(errorCount, 1 + filters.ErrorRetry);
            }
         }
         
         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Device/DiskSpaceInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space,
   /// the total amount of free space, and the total amount of free space available to the user that is associated with the calling thread.
   /// <para>This class cannot be inherited.</para>
   /// </summary>
   [Serializable]
   [SecurityCritical]
   public sealed class DiskSpaceInfo
   {
      [NonSerialized] private readonly bool _initGetClusterInfo = true;
      [NonSerialized] private readonly bool _initGetSpaceInfo = true;
      [NonSerialized] private readonly CultureInfo _cultureInfo = CultureInfo.CurrentCulture;
      [NonSerialized] private readonly bool _continueOnAccessError;


      /// <summary>Initializes a DiskSpaceInfo instance.</summary>
      /// <param name="drivePath">A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z' or a network share in the format: \\server\share</param>
      /// <Remark>This is a Lazyloading object; call <see cref="Refresh()"/> to populate all properties first before accessing.</Remark>
      [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")]
      [SecurityCritical]
      public DiskSpaceInfo(string drivePath)
      {
         if (Utils.IsNullOrWhiteSpace(drivePath))
            throw new ArgumentNullException("drivePath");


         drivePath = drivePath.Length == 1 ? drivePath + Path.VolumeSeparatorChar : Path.GetPathRoot(drivePath, false);

         if (Utils.IsNullOrWhiteSpace(drivePath))
            throw new ArgumentException(Resources.InvalidDriveLetterArgument, "drivePath");


         // MSDN:
         // If this parameter is a UNC name, it must include a trailing backslash (for example, "\\MyServer\MyShare\").
         // Furthermore, a drive specification must have a trailing backslash (for example, "C:\").
         // The calling application must have FILE_LIST_DIRECTORY access rights for this directory.
         DriveName = Path.AddTrailingDirectorySeparator(drivePath, false);
      }

      
      /// <summary>Initializes a DiskSpaceInfo instance.</summary>
      /// <param name="drivePath">A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z' or a network share in the format: \\server\share</param>
      /// <param name="spaceInfoType"><c>null</c> gets both size- and disk cluster information. <c>true</c> Get only disk cluster information, <c>false</c> Get only size information.</param>
      /// <param name="refresh">Refreshes the state of the object.</param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public DiskSpaceInfo(string drivePath, bool? spaceInfoType, bool refresh, bool continueOnException) : this(drivePath)
      {
         if (spaceInfoType == null)
         {
            _initGetSpaceInfo = true;
            _initGetClusterInfo = true;
         }

         else
         {
            _initGetSpaceInfo = (bool) !spaceInfoType;
            _initGetClusterInfo = (bool) spaceInfoType;
         }

         _continueOnAccessError = continueOnException;

         if (refresh)
            Refresh();
      }


      /// <summary>Indicates the amount of available free space on a drive, formatted as percentage.</summary>
      public string AvailableFreeSpacePercent
      {
         get
         {
            return PercentCalculate(TotalNumberOfBytes - (TotalNumberOfBytes - TotalNumberOfFreeBytes), 0, TotalNumberOfBytes).ToString("0.##", _cultureInfo) + "%";
         }
      }


      /// <summary>Indicates the amount of available free space on a drive, formatted as a unit size.</summary>
      public string AvailableFreeSpaceUnitSize
      {
         get { return Utils.UnitSizeToText(TotalNumberOfFreeBytes, _cultureInfo); }
      }


      /// <summary>Returns the Clusters size.</summary>
      public long ClusterSize
      {
         get { return SectorsPerCluster * BytesPerSector; }
      }


      /// <summary>Gets the name of a drive.</summary>
      /// <returns>The name of the drive.</returns>
      /// <remarks>This property is the name assigned to the drive, such as C:\ or E:\</remarks>
      public string DriveName { get; private set; }


      /// <summary>The total number of bytes on a disk that are available to the user who is associated with the calling thread, formatted as a unit size.</summary>
      public string TotalSizeUnitSize
      {
         get { return Utils.UnitSizeToText(TotalNumberOfBytes, _cultureInfo); }
      }


      /// <summary>Indicates the amount of used space on a drive, formatted as percentage.</summary>
      public string UsedSpacePercent
      {
         get
         {
            return PercentCalculate(TotalNumberOfBytes - FreeBytesAvailable, 0, TotalNumberOfBytes).ToString("0.##", _cultureInfo) + "%";
         }
      }


      /// <summary>Indicates the amount of used space on a drive, formatted as a unit size.</summary>
      public string UsedSpaceUnitSize
      {
         get { return Utils.UnitSizeToText(TotalNumberOfBytes - FreeBytesAvailable, _cultureInfo); }
      }


      /// <summary>The total number of free bytes on a disk that are available to the user who is associated with the calling thread.</summary>
      public long FreeBytesAvailable { get; private set; }


      /// <summary>The total number of bytes on a disk that are available to the user who is associated with the calling thread.</summary>
      public long TotalNumberOfBytes { get; private set; }


      /// <summary>The total number of free bytes on a disk.</summary>
      public long TotalNumberOfFreeBytes { get; private set; }


      /// <summary>The number of bytes per sector.</summary>
      public int BytesPerSector { get; private set; }


      /// <summary>The total number of free clusters on the disk that are available to the user who is associated with the calling thread.</summary>
      public int NumberOfFreeClusters { get; private set; }


      /// <summary>The number of sectors per cluster.</summary>
      public int SectorsPerCluster { get; private set; }


      /// <summary>The total number of clusters on the disk that are available to the user who is associated with the calling thread.
      /// If per-user disk quotas are in use, this value may be less than the total number of clusters on the disk.
      /// </summary>
      public long TotalNumberOfClusters { get; private set; }




      /// <summary>Refreshes the state of the object.</summary>
      public void Refresh()
      {
         Reset();

         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
         {
            int lastError;


            // Get size information.

            if (_initGetSpaceInfo)
            {
               long freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;

               var success = NativeMethods.GetDiskFreeSpaceEx(DriveName, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes);

               lastError = Marshal.GetLastWin32Error();

               if (!success && !_continueOnAccessError && lastError != Win32Errors.ERROR_NOT_READY)
                  NativeError.ThrowException(lastError, DriveName);


               FreeBytesAvailable = freeBytesAvailable;
               TotalNumberOfBytes = totalNumberOfBytes;
               TotalNumberOfFreeBytes = totalNumberOfFreeBytes;
            }


            // Get cluster information.

            if (_initGetClusterInfo)
            {
               int sectorsPerCluster, bytesPerSector, numberOfFreeClusters;
               uint totalNumberOfClusters;

               var success = NativeMethods.GetDiskFreeSpace(DriveName, out sectorsPerCluster, out bytesPerSector, out numberOfFreeClusters, out totalNumberOfClusters);

               lastError = Marshal.GetLastWin32Error();

               if (!success && !_continueOnAccessError && lastError != Win32Errors.ERROR_NOT_READY)
                  NativeError.ThrowException(lastError, DriveName);


               BytesPerSector = bytesPerSector;
               NumberOfFreeClusters = numberOfFreeClusters;
               SectorsPerCluster = sectorsPerCluster;
               TotalNumberOfClusters = totalNumberOfClusters;
            }
         }
      }


      /// <summary>Initializes all <see ref="Alphaleonis.Win32.Filesystem.DiskSpaceInfo"/> properties to 0.</summary>
      private void Reset()
      {
         if (_initGetSpaceInfo)
         {
            FreeBytesAvailable = 0;
            TotalNumberOfBytes = 0;
            TotalNumberOfFreeBytes = 0;
         }


         if (_initGetClusterInfo)
         {
            BytesPerSector = 0;
            NumberOfFreeClusters = 0;
            SectorsPerCluster = 0;
            TotalNumberOfClusters = 0;
         }
      }


      /// <summary>Returns the drive name.</summary>
      /// <returns>A string that represents this object.</returns>
      public override string ToString()
      {
         return DriveName;
      }


      /// <summary>Calculates a percentage value.</summary>
      private static double PercentCalculate(double currentValue, double minimumValue, double maximumValue)
      {
         return currentValue < 0 || maximumValue <= 0 ? 0 : currentValue * 100 / (maximumValue - minimumValue);
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.GetUniqueVolumeNameForPath.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Get the unique volume name for the given path.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="volumePathName">
      ///   A path string. Both absolute and relative file and directory names, for example "..", is acceptable in this path. If you specify a
      ///   relative file or directory name without a volume qualifier, GetUniqueVolumeNameForPath returns the Drive letter of the current
      ///   volume.
      /// </param>
      /// <returns>
      ///   <para>Returns the unique volume name in the form: "\\?\Volume{GUID}\",</para>
      ///   <para>or <c>null</c> on error or if unavailable.</para>
      /// </returns>
      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      [SecurityCritical]
      public static string GetUniqueVolumeNameForPath(string volumePathName)
      {
         if (Utils.IsNullOrWhiteSpace(volumePathName))
            throw new ArgumentNullException("volumePathName");

         try
         {
            return GetVolumeGuid(GetVolumePathName(volumePathName));
         }
         catch
         {
            return null;
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Security/Native Other/TOKEN_ELEVATION_TYPE.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

namespace Alphaleonis.Win32.Security
{
   internal static partial class NativeMethods
   {
      /// <summary>The TOKEN_ELEVATION_TYPE enumeration indicates the elevation type of token being queried by the GetTokenInformation function.</summary>
      /// <remarks>
      /// <para>Minimum supported client: Windows Vista [desktop apps only]</para>
      /// <para>Minimum supported server: Windows Server 2008 [desktop apps only]</para>
      /// </remarks>
      internal enum TOKEN_ELEVATION_TYPE
      {
         ///// <summary>The token does not have a linked token: UAC is disabled or the process is started by a standard User (not a member of the Administrators group).</summary>
         //TokenElevationTypeDefault = 1,

         /// <summary>The token is an elevated token: UAC is enabled and User is elevated.</summary>
         TokenElevationTypeFull = 2,

         ///// <summary>The token is a limited token: UAC is enabled but User is not elevated.</summary>
         //TokenElevationTypeLimited = 3
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetHostShareFromPath.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Network;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_HostTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Host_GetHostShareFromPath_Network_Success()
      {
         UnitTestConstants.PrintUnitTestHeader(true);

         var folderWithspaces = @"\Folder with spaces";


         // Local Path.
         var uncPath = UnitTestConstants.SysDrive;
         var hostAndShare = Host.GetHostShareFromPath(uncPath);
         Console.WriteLine("Input local path: [{0}]", uncPath);
         Console.WriteLine("\tResult == null: {0}", null == hostAndShare);

         Assert.AreEqual(null, hostAndShare);


         Console.WriteLine();


         // Local Path.
         uncPath = UnitTestConstants.SysDrive + folderWithspaces;
         hostAndShare = Host.GetHostShareFromPath(uncPath);
         Console.WriteLine("Input local path: [{0}]", uncPath);
         Console.WriteLine("\tResult == null: {0}", null == hostAndShare);

         Assert.AreEqual(null, hostAndShare);


         Console.WriteLine();


         // Local Path.
         uncPath = Alphaleonis.Win32.Filesystem.Path.GetLongPath(Environment.SystemDirectory + folderWithspaces);
         hostAndShare = Host.GetHostShareFromPath(uncPath);
         Console.WriteLine("Input local path: [{0}]", uncPath);
         Console.WriteLine("\tResult == null: {0}", null == hostAndShare);
         Assert.AreEqual(null, hostAndShare);


         Console.WriteLine();


         // Network Path as regular path.
         uncPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.SysDrive);
         hostAndShare = Host.GetHostShareFromPath(uncPath);
         Console.WriteLine("Input UNC path: [{0}]", uncPath);
         Console.WriteLine("\tHost : [{0}]", hostAndShare[0]);
         Console.WriteLine("\tShare: [{0}]", hostAndShare[1]);

         Assert.IsTrue(hostAndShare[1].EndsWith(Alphaleonis.Win32.Filesystem.Path.NetworkDriveSeparator));
         Assert.AreEqual(Environment.MachineName, hostAndShare[0].ToUpperInvariant());

         
         Console.WriteLine();


         // Network Path as regular path.
         uncPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.SysDrive + @"\");
         hostAndShare = Host.GetHostShareFromPath(uncPath);
         Console.WriteLine("Input UNC path: [{0}]", uncPath);
         Console.WriteLine("\tHost : [{0}]", hostAndShare[0]);
         Console.WriteLine("\tShare: [{0}]", hostAndShare[1]);

         Assert.IsTrue(hostAndShare[1].EndsWith(@"\"));
         Assert.AreEqual(Environment.MachineName, hostAndShare[0].ToUpperInvariant());


         Console.WriteLine();
         

         // Network Path as regular path.
         uncPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.SysDrive + folderWithspaces);
         hostAndShare = Host.GetHostShareFromPath(uncPath);
         Console.WriteLine("Input UNC path: [{0}]", uncPath);
         Console.WriteLine("\tHost : [{0}]", hostAndShare[0]);
         Console.WriteLine("\tShare: [{0}]", hostAndShare[1]);

         Assert.AreEqual(Environment.MachineName, hostAndShare[0].ToUpperInvariant());


         Console.WriteLine();


         // Network Path as long path.
         uncPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(Environment.SystemDirectory + folderWithspaces, Alphaleonis.Win32.Filesystem.GetFullPathOptions.AsLongPath);
         hostAndShare = Host.GetHostShareFromPath(uncPath);
         Console.WriteLine("Input UNC path: [{0}]", uncPath);
         Console.WriteLine("\tHost : [{0}]", hostAndShare[0]);
         Console.WriteLine("\tShare: [{0}]", hostAndShare[1]);

         Assert.IsFalse(hostAndShare[0].Contains("/"));
         Assert.AreEqual(Environment.MachineName, hostAndShare[0].ToUpperInvariant());
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.GetUncName.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Security;
using Path = Alphaleonis.Win32.Filesystem.Path;

namespace Alphaleonis.Win32.Network
{
   /// <summary>Provides static methods to retrieve network resource information from a local- or remote host.</summary>
   public static partial class Host
   {
      /// <summary>Return the host name in UNC format, for example: \\hostname</summary>
      /// <returns>The unc name.</returns>
      [SecurityCritical]
      public static string GetUncName()
      {
         return string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.UncPrefix, Environment.MachineName);
      }


      /// <summary>Return the host name in UNC format, for example: \\hostname</summary>
      /// <param name="computerName">Name of the computer.</param>
      /// <returns>The unc name.</returns>
      [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")]
      [SecurityCritical]
      public static string GetUncName(string computerName)
      {
         return Utils.IsNullOrWhiteSpace(computerName) ? GetUncName() : (computerName.StartsWith(Path.UncPrefix, StringComparison.Ordinal) ? computerName.Trim() : Path.UncPrefix + computerName.Trim());
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_NoRetry_ThrowsUnauthorizedAccessException.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING F_ROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.Globalization;

namespace AlphaFS.UnitTest
{
   public partial class CopyTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_Copy_NoRetry_ThrowsUnauthorizedAccessException_LocalAndNetwork()
      {
         AlphaFS_Directory_Copy_NoRetry_ThrowsUnauthorizedAccessException(false);
         AlphaFS_Directory_Copy_NoRetry_ThrowsUnauthorizedAccessException(true);
      }

      
      private void AlphaFS_Directory_Copy_NoRetry_ThrowsUnauthorizedAccessException(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folderSrc = tempRoot.CreateDirectory().FullName;
            var folderDst = tempRoot.CreateDirectory().FullName;

            Console.WriteLine("Destination Directory Path: [{0}]\n", folderDst);

            
            var existingFileSrc = System.IO.Path.Combine(folderSrc, "ExistingFile.txt");
            var existingFileDst = System.IO.Path.Combine(folderDst, "ExistingFile.txt");

            System.IO.File.WriteAllText(existingFileSrc, DateTime.Now.ToString(CultureInfo.CurrentCulture));
            System.IO.File.WriteAllText(existingFileDst, DateTime.Now.ToString(CultureInfo.CurrentCulture));


            // Set destination file hidden attribute so that a System.UnauthorizedAccessException is triggered on folder copy.

            System.IO.File.SetAttributes(existingFileDst, System.IO.FileAttributes.Hidden);




            var errorCount = 0;

            var filters = new Alphaleonis.Win32.Filesystem.DirectoryEnumerationFilters
            {
               ErrorFilter = delegate(int errorCode, string errorMessage, string pathProcessed)
               {
                  // Report Exception.
                  Console.WriteLine("\tErrorFilter: Attempt #{0:N0}: ({1}) {2}: [{3}]", ++errorCount, errorCode, errorMessage, pathProcessed);

                  // Return true to continue, false to throw the Exception.
                  return true;
               }
            };
               

            var sw = Stopwatch.StartNew();

            UnitTestAssert.ThrowsException<UnauthorizedAccessException>(() => Alphaleonis.Win32.Filesystem.Directory.Copy(folderSrc, folderDst, Alphaleonis.Win32.Filesystem.CopyOptions.None, filters));

            sw.Stop();


            var waitTime = filters.ErrorRetry * filters.ErrorRetryTimeout;

            Assert.AreEqual(0, waitTime, "The timeout is not what is expected.");
            Assert.AreEqual(0, sw.Elapsed.Seconds, "The timeout is not what is expected.");
            Assert.AreEqual(errorCount, 1 + filters.ErrorRetry);
         }
         
         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.ExistsCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Determines whether the specified file or directory exists.</summary>
      /// <remarks>
      ///   <para>MSDN: .NET 3.5+: Trailing spaces are removed from the end of the <paramref name="path"/> parameter before checking whether
      ///   the directory exists.</para>
      ///   <para>The Exists method returns <c>false</c> if any error occurs while trying to determine if the specified file
      ///   exists.</para>
      ///   <para>This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters,
      ///   </para>
      ///   <para>a failing or missing disk, or if the caller does not have permission to read the file.</para>
      ///   <para>The Exists method should not be used for path validation,
      ///   this method merely checks if the file specified in path exists.</para>
      ///   <para>Passing an invalid path to Exists returns false.</para>
      ///   <para>Be aware that another process can potentially do something with the file in between
      ///   the time you call the Exists method and perform another operation on the file, such as Delete.</para>
      /// </remarks>
      /// <param name="transaction">The transaction.</param>
      /// <param name="isFolder">Specifies that <paramref name="path"/> is a file or directory.</param>
      /// <param name="path">The file to check.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>
      ///   <para>Returns <c>true</c> if the caller has the required permissions</para>
      ///   <para>and <paramref name="path"/> contains the name of an existing file or directory; otherwise, <c>false</c></para>
      /// </returns>
      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      [SecurityCritical]
      internal static bool ExistsCore(KernelTransaction transaction, bool isFolder, string path, PathFormat pathFormat)
      {
         // Will be caught later and be thrown as an ArgumentException or ArgumentNullException.
         // Let's take a shorter route, preventing an Exception from being thrown altogether.
         if (Utils.IsNullOrWhiteSpace(path))
            return false;


         // Check for driveletter, such as: "C:"
         var pathRp = Path.GetRegularPathCore(path, GetFullPathOptions.None, false);

         if (pathRp.Length == 2 && Path.IsLogicalDriveCore(pathRp, true, PathFormat.LongFullPath))
            path = pathRp;


         try
         {
            var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars | GetFullPathOptions.ContinueOnNonExist);

            var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();

            var dataInitialised = FillAttributeInfoCore(transaction, pathLp, ref attrs, false, true);

            if (dataInitialised == Win32Errors.ERROR_INVALID_NAME || dataInitialised == Win32Errors.ERROR_INVALID_PARAMETER)
            {
               // Issue #288: Directory.Exists on root drive problem has come back with recent updates
               //
               // ERROR_INVALID_NAME     : A relative path with a long path prefix: FindFirstFileEx("\\\\?\\C:qr4bxbzb.k1v-exists", ...
               // ERROR_INVALID_PARAMETER: A drive path with a long path prefix   : GetFileAttributesTransacted("\\?\C:\", ...


               dataInitialised = FillAttributeInfoCore(transaction, pathRp, ref attrs, false, true);
            }


            var attrIsFolder = IsDirectory(attrs.dwFileAttributes);

            return dataInitialised == Win32Errors.ERROR_SUCCESS && (isFolder ? attrIsFolder : !attrIsFolder);
         }
         catch
         {
            return false;
         }
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Globalization;

namespace AlphaFS.UnitTest
{
   /// <summary>Containts static variables, used by unit tests.</summary>
   public static partial class UnitTestConstants
   {
      /// <summary>The Computer system drive. For example "C:".</summary>
      public static readonly string SysDrive = Environment.GetEnvironmentVariable("SystemDrive");


      public const int OneMebibyte = 1048576;


      public static readonly string[] StreamArrayContent =
      {
         "(1) Nikolai Tesla: \"Today's scientists have substituted mathematics for experiments, and they wander off through equation after equation, and eventually build a structure which has no relation to reality.\"",
         "(2) The quick brown fox jumps over the lazy dog.",
         "(3) Computer: [" + Environment.MachineName + "]" + "\tHello there, " + Environment.UserName
      };


      public static readonly string[] InputPaths =
      {
         @".",
         @".zip",

         SysDrive + @"\\test.txt",
         SysDrive + @"\/test.txt",

         System.IO.Path.DirectorySeparatorChar.ToString(),
         System.IO.Path.DirectorySeparatorChar + @"Program Files\Microsoft Office",

         Alphaleonis.Win32.Filesystem.Path.GlobalRootDevicePrefix + @"harddisk0\partition1\",
         Alphaleonis.Win32.Filesystem.Path.VolumePrefix + @"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\Program Files\notepad.exe",

         "dir1/dir2/dir3/",

         @"Program Files\Microsoft Office",
         SysDrive[0].ToString(CultureInfo.InvariantCulture),
         SysDrive,
         SysDrive + @"\",
         SysDrive + @"\a",
         SysDrive + @"\a\",
         SysDrive + @"\a\b",
         SysDrive + @"\a\b\",
         SysDrive + @"\a\b\c",
         SysDrive + @"\a\b\c\",
         SysDrive + @"\a\b\c\z",
         SysDrive + @"\a\b\c\z.",
         SysDrive + @"\a\b\c\z.t",
         SysDrive + @"\a\b\c\z.tx",
         SysDrive + @"\a\b\c\z.txt",

         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + @"Program Files\Microsoft Office",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive[0].ToString(CultureInfo.InvariantCulture),
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive,
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\z",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\z.",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\z.t",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\z.tx",
         Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\z.txt",

         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\d",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\d2",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\d2\",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\d2\f",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\d2\fi",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\d2\fil",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\d2\file",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\d2\file.",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\d2\file.e",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\d2\file.ex",
         Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName + @"\Share\d1\d2\file.ext",

         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\d",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\d2",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\d2\",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\d2\f",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\d2\fi",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\d2\fil",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\d2\file",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\d2\file.",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\d2\file.e",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\d2\file.ex",
         Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + Environment.MachineName + @"\Share\d1\d2\file.ext"
      };
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveType.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_VolumeTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Volume_GetDriveType_LocalAndNetwork_Success()
      {
         AlphaFS_Volume_GetDriveType(false);
         AlphaFS_Volume_GetDriveType(true);
      }


      private void AlphaFS_Volume_GetDriveType(bool isNetwork)
      {
         UnitTestConstants.PrintUnitTestHeader(isNetwork);


         var logicalDriveCount = 0;

         foreach (var logicalDrive in System.IO.DriveInfo.GetDrives())
         {
            var driveName = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(logicalDrive.Name) : logicalDrive.Name;

            Console.Write("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveName);

            if (logicalDrive.DriveType == System.IO.DriveType.CDRom)
            {
               Console.WriteLine();
               continue;
            }


            var driveType = Alphaleonis.Win32.Filesystem.Volume.GetDriveType(driveName);

            Console.WriteLine("\t\tDrive Type: [{0}]", driveType);


            if (isNetwork)
            {
               // Some USB drives do not report drive type.
            }

            else
               Assert.AreEqual(logicalDrive.DriveType, driveType);

         }


         Assert.IsTrue(logicalDriveCount > 0, "No logical drives enumerated, but it is expected.");


         Console.WriteLine();
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/UnitTests/AlphaFS_ProcessContextTest.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Security.Principal;

namespace AlphaFS.UnitTest
{
   /// <summary>This is a test class for all ProcessContext class Unit Tests.</summary>
   [TestClass]
   public class AlphaFS_ProcessContextTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_ProcessContext()
      {
         UnitTestConstants.PrintUnitTestHeader(false);

         var isAdmin = Alphaleonis.Win32.Security.ProcessContext.IsAdministrator;

         var isElevated = Alphaleonis.Win32.Security.ProcessContext.IsElevatedProcess;

         var isUacEnabled = Alphaleonis.Win32.Security.ProcessContext.IsUacEnabled;

         var IsWindowsService = Alphaleonis.Win32.Security.ProcessContext.IsWindowsService;


         Console.WriteLine("IsAdmin         : [{0}]", isAdmin);

         Console.WriteLine("IsElevated      : [{0}]", isElevated);

         Console.WriteLine("IsUacEnabled    : [{0}]", isUacEnabled);

         Console.WriteLine("IsWindowsService: [{0}]", IsWindowsService);


         // TODO: Test code is the same as in AlphaFS.
         Assert.AreEqual(new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator), isAdmin);

         
         // Assumption.
         Assert.IsFalse(IsWindowsService);
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Retrieves a sorted list of all existing MS-DOS device names.</summary>
      /// <returns>An <see cref="IEnumerable{String}"/> sorted list of all existing MS-DOS device names.</returns>
      [SecurityCritical]
      public static IEnumerable<string> QueryAllDosDevices()
      {
         return QueryDosDeviceCore(null, true);
      }


      /// <summary>[AlphaFS] Retrieves the current mapping for a particular MS-DOS device name.</summary>
      /// <returns>The current mapping for a particular MS-DOS device name.</returns>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <param name="deviceName">An MS-DOS device name string specifying the target of the query, such as: "C:", "D:" or "\\?\Volume{GUID}".</param>
      [SecurityCritical]
      public static string QueryDosDevice(string deviceName)
      {
         if (Utils.IsNullOrWhiteSpace(deviceName))
            throw new ArgumentNullException("deviceName");


         var devName = QueryDosDeviceCore(deviceName, false).ToArray()[0];

         return !Utils.IsNullOrWhiteSpace(devName) ? devName : null;
      }




      /// <summary>[AlphaFS] Retrieves the current mapping for a particular MS-DOS device name. The function can also obtain a list of all existing MS-DOS device names.</summary>
      /// <returns>An <see cref="IEnumerable{String}"/> sorted list of all existing MS-DOS device names or the .</returns>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <param name="deviceName">An MS-DOS device name string specifying the target of the query, such as: "C:", "D:" or "\\?\Volume{GUID}".</param>
      /// <param name="sort"><c>true</c> to sort the list with MS-DOS device names.</param>
      [SecurityCritical]
      internal static IEnumerable<string> QueryDosDeviceCore(string deviceName, bool sort)
      {
         // deviceName is allowed to be null: Retrieve a list of all existing MS-DOS device names.
         // The deviceName cannot have a trailing backslash.

         if (!Utils.IsNullOrWhiteSpace(deviceName))
         {
            if (deviceName.StartsWith(Path.GlobalRootPrefix, StringComparison.OrdinalIgnoreCase))
            {
               yield return deviceName.Substring(Path.GlobalRootPrefix.Length);

               yield break;
            }

            
            if (deviceName.StartsWith(Path.VolumePrefix, StringComparison.OrdinalIgnoreCase))

               deviceName = deviceName.Substring(Path.LongPathPrefix.Length);


            deviceName = Path.RemoveTrailingDirectorySeparator(deviceName);
         }




         uint returnedBufferSize = 0;

         var bufferSize = (uint) (sort ? NativeMethods.DefaultFileBufferSize : 64);

         var sortedList = new List<string>(sort ? 256 : 0);


         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
            while (returnedBufferSize == 0)
            {
               var cBuffer = new char[bufferSize];

               returnedBufferSize = NativeMethods.QueryDosDevice(deviceName, cBuffer, bufferSize);

               var lastError = Marshal.GetLastWin32Error();

               if (returnedBufferSize == 0)
                  switch ((uint) lastError)
                  {
                     case Win32Errors.ERROR_MORE_DATA:
                     case Win32Errors.ERROR_INSUFFICIENT_BUFFER:
                        bufferSize *= 2;
                        continue;

                     default:
                        NativeError.ThrowException(lastError, deviceName);
                        break;
                  }


               var buffer = new StringBuilder((int) returnedBufferSize);


               for (var i = 0; i < returnedBufferSize; i++)
               {
                  if (cBuffer[i] != Path.StringTerminatorChar)

                     buffer.Append(cBuffer[i]);


                  else if (buffer.Length > 0)
                  {
                     var assembledPath = buffer.ToString();

                     assembledPath = !Utils.IsNullOrWhiteSpace(assembledPath) ? assembledPath : null;


                     if (sort)
                        sortedList.Add(assembledPath);

                     else
                        yield return assembledPath;


                     buffer.Length = 0;
                  }
               }
            }


         if (sort)
         {
            foreach (var devName in sortedList.OrderBy(devName => devName))

               yield return devName;
         }
      }
   }
}


<|start_filename|>build/common.cake<|end_filename|>
/// <summary>
/// Deletes the specified directory if it exists.
/// </summary>
/// <param name="path">The directory to delete.</param>
void DeleteDirectoryIfExists(DirectoryPath path, bool force = true)
{
    if (DirectoryExists(path))
    {
        DeleteDirectory(path, new DeleteDirectorySettings { Force = force, Recursive = true });
    }
}

/// <summary>
/// Deletes all contents of the specified directory, optionally also removing read-only files.
/// </summary>
/// <param name="path">The directory to delete all contents of.</param>
/// <param name="force">If true even read-only files will be deleted.</param>
void CleanDirectory(DirectoryPath path, bool force)
{
    if (force && DirectoryExists(path))
    {
        Verbose("Removing ReadOnly attributes on all files in directory {0}", path);                
        foreach (var file in System.IO.Directory.GetFiles(MakeAbsolute(path).FullPath, "*", SearchOption.AllDirectories))
        {
            System.IO.File.SetAttributes(file, System.IO.File.GetAttributes(file) & ~FileAttributes.ReadOnly);            
        }
    }

    CleanDirectory(path);
}

<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

#if !NET35
using System.Threading;
#endif

namespace AlphaFS.UnitTest
{
   public partial class EnumerationTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters(false);
         AlphaFS_Directory_EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters(true);
      }


      private void AlphaFS_Directory_EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters(bool isNetwork)
      {
         UnitTestConstants.PrintUnitTestHeader(isNetwork);
         
         var inputPath = Environment.SystemDirectory;
         if (isNetwork)
            inputPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(inputPath);

         Console.WriteLine("Input Directory Path: [{0}]\n", inputPath);
         
         Test_DirectoryEnumerationFilters(inputPath);
         
         Console.WriteLine();
      }




      private void Test_DirectoryEnumerationFilters(string inputPath)
      {
         bool gotException;

         var findExtensions = new[] {".txt", ".ini", ".exe"};
         var skipFolders = new[] {"assembly", "WinSxS"};

         Console.WriteLine("Extensions to search for: {0}", string.Join(" | ", findExtensions));
         Console.WriteLine("Root directories to skip: {0}\\{1}, {0}\\{2}", inputPath, skipFolders[0], skipFolders[1]);
         Console.WriteLine();


         var exceptionCount = 0;
         var foundExt1 = 0;
         var foundExt2 = 0;
         var foundExt3 = 0;
         var foundExt1Done = false;
         var foundExt2Done = false;
         var foundExt3Done = false;


#if NET35
         var abortEnumeration = false;


         var filters = new Alphaleonis.Win32.Filesystem.DirectoryEnumerationFilters
         {
            // Filter to decide whether to recurse into subdirectories.
            RecursionFilter = fsei =>
            {
               if (abortEnumeration)
                  return false;


               // Return true to continue recursion, false to skip.
               return !skipFolders.Any(found => found.Equals(fsei.FileName, StringComparison.OrdinalIgnoreCase));
            },


            // Filter to process Exception handling.
            ErrorFilter = delegate(int errorCode, string errorMessage, string pathProcessed)
            {
               if (abortEnumeration)
                  return true;


               gotException = errorCode == Alphaleonis.Win32.Win32Errors.ERROR_ACCESS_DENIED;

               Console.WriteLine("\t#{0:N0}\t\t({1}) {2}: [{3}]", ++exceptionCount, errorCode, errorMessage, pathProcessed);


               // Return true to continue, false to throw the Exception.
               return gotException;
            },


            // Filter to in-/exclude file system entries during the enumeration.
            InclusionFilter = fsei =>
            {
               if (abortEnumeration)
                  return false;


               var fileExtension = fsei.Extension;

               var gotMatch = findExtensions.Any(found => found.Equals(fileExtension, StringComparison.OrdinalIgnoreCase));
               if (gotMatch)
               {
                  if (!foundExt1Done && fileExtension == findExtensions[0])
                  {
                     foundExt1++;
                     foundExt1Done = foundExt1 == 3;
                     Console.WriteLine("\t#{0:N0}\t\t[{1}]", foundExt1, fsei.FullPath);
                  }

                  else if (!foundExt2Done && fileExtension == findExtensions[1])
                  {
                     foundExt2++;
                     foundExt2Done = foundExt2 == 3;
                     Console.WriteLine("\t#{0:N0}\t\t[{1}]", foundExt2, fsei.FullPath);
                  }

                  else if (!foundExt3Done && fileExtension == findExtensions[2])
                  {
                     foundExt3++;
                     foundExt3Done = foundExt3 == 3;
                     Console.WriteLine("\t#{0:N0}\t\t[{1}]", foundExt3, fsei.FullPath);
                  }
               }


               // Abort the enumeration.
               if (foundExt1Done && foundExt2Done && foundExt3Done)
                  abortEnumeration = true;


               return gotMatch;
            }
         };
#else
         var cancelSource = new CancellationTokenSource();


         var filters = new Alphaleonis.Win32.Filesystem.DirectoryEnumerationFilters
         {
            // Used to abort the enumeration.
            CancellationToken = cancelSource.Token,


            // Filter to decide whether to recurse into subdirectories.
            RecursionFilter = fsei =>
            {
               // Return true to continue recursion, false to skip.
               return !skipFolders.Any(found => found.Equals(fsei.FileName, StringComparison.OrdinalIgnoreCase));
            },


            // Filter to process Exception handling.
            ErrorFilter = delegate(int errorCode, string errorMessage, string pathProcessed)
            {
               gotException = errorCode == Alphaleonis.Win32.Win32Errors.ERROR_ACCESS_DENIED;

               Console.WriteLine("\t#{0:N0}\t\t({1}) {2}: [{3}]", ++exceptionCount, errorCode, errorMessage, pathProcessed);


               // Return true to continue, false to throw the Exception.
               return gotException;
            },


            // Filter to in-/exclude file system entries during the enumeration.
            InclusionFilter = fsei =>
            {
               var fileExtension = fsei.Extension;

               var gotMatch = findExtensions.Any(found => found.Equals(fileExtension, StringComparison.OrdinalIgnoreCase));
               if (gotMatch)
               {
                  if (!foundExt1Done && fileExtension == findExtensions[0])
                  {
                     foundExt1++;
                     foundExt1Done = foundExt1 == 3;
                     Console.WriteLine("\t#{0:N0}\t\t[{1}]", foundExt1, fsei.FullPath);
                  }

                  else if (!foundExt2Done && fileExtension == findExtensions[1])
                  {
                     foundExt2++;
                     foundExt2Done = foundExt2 == 3;
                     Console.WriteLine("\t#{0:N0}\t\t[{1}]", foundExt2, fsei.FullPath);
                  }

                  else if (!foundExt3Done && fileExtension == findExtensions[2])
                  {
                     foundExt3++;
                     foundExt3Done = foundExt3 == 3;
                     Console.WriteLine("\t#{0:N0}\t\t[{1}]", foundExt3, fsei.FullPath);
                  }
               }


               // Abort the enumeration.
               if (foundExt1Done && foundExt2Done && foundExt3Done)
                  cancelSource.Cancel();


               return gotMatch;
            }
         };
#endif


         const Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions dirEnumOptions = Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Files | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive;

         var fsoCount = Alphaleonis.Win32.Filesystem.Directory.EnumerateFileSystemEntryInfos<string>(inputPath, dirEnumOptions, filters).Count();
         
         
         Console.WriteLine("\n\tFile system objects counted: {0:N0}", fsoCount);


         Assert.IsTrue(fsoCount > 0, "No files enumerated, but it is expected.");

         Assert.IsTrue(foundExt1 > 0, "No " + findExtensions[0] + " files enumerated, but it is expected.");
         Assert.IsTrue(foundExt2 > 0, "No " + findExtensions[1] + " files enumerated, but it is expected.");
         Assert.IsTrue(foundExt3 > 0, "No " + findExtensions[2] + " files enumerated, but it is expected.");


         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Other/FILE_ID_BOTH_DIR_INFO.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      /// <summary>Contains information about files in the specified directory. Used for directory handles. Use only when calling GetFileInformationByHandleEx.</summary>
      /// <remarks>
      /// The number of files that are returned for each call to GetFileInformationByHandleEx depends on the size of the buffer that is passed to the function.
      /// Any subsequent calls to GetFileInformationByHandleEx on the same handle will resume the enumeration operation after the last file is returned.
      /// </remarks>
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      internal struct FILE_ID_BOTH_DIR_INFO
      {
         /// <summary>The offset for the next FILE_ID_BOTH_DIR_INFO structure that is returned. Contains zero (0) if no other entries follow this one.</summary>
         [MarshalAs(UnmanagedType.U4)]
         public readonly int NextEntryOffset;

         /// <summary>The byte offset of the file within the parent directory. This member is undefined for file systems, such as NTFS,
         /// in which the position of a file within the parent directory is not fixed and can be changed at any time to maintain sort order.
         /// </summary>
         [MarshalAs(UnmanagedType.U4)]
         public readonly uint FileIndex;

         /// <summary>The time that the file was created.</summary>
         public FILETIME CreationTime;

         /// <summary>The time that the file was last accessed.</summary>
         public FILETIME LastAccessTime;

         /// <summary>The time that the file was last written to.</summary>
         public FILETIME LastWriteTime;

         /// <summary>The time that the file was last changed.</summary>
         public FILETIME ChangeTime;

         /// <summary>The absolute new end-of-file position as a byte offset from the start of the file to the end of the file.
         /// Because this value is zero-based, it actually refers to the first free byte in the file.
         /// In other words, EndOfFile is the offset to the byte that immediately follows the last valid byte in the file.
         /// </summary>
         public readonly long EndOfFile;

         /// <summary>The number of bytes that are allocated for the file. This value is usually a multiple of the sector or cluster size of the underlying physical device.</summary>
         public readonly long AllocationSize;

         /// <summary>The file attributes.</summary>
         public readonly FileAttributes FileAttributes;

         /// <summary>The length of the file name.</summary>
         [MarshalAs(UnmanagedType.U4)]
         public readonly uint FileNameLength;

         /// <summary>The size of the extended attributes for the file.</summary>
         [MarshalAs(UnmanagedType.U4)]
         public readonly int EaSize;

         /// <summary>The length of ShortName.</summary>
         [MarshalAs(UnmanagedType.U1)]
         public readonly byte ShortNameLength;

         /// <summary>The short 8.3 file naming convention (for example, "FILENAME.TXT") name of the file.</summary>
         [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12, ArraySubType = UnmanagedType.U2)]
         public readonly char[] ShortName;

         /// <summary>The file ID.</summary>
         public readonly long FileId;

         /// <summary>The first character of the file name string. This is followed in memory by the remainder of the string.</summary>
         public IntPtr FileName;
      }
   }
}

<|start_filename|>src/AlphaFS/Filesystem/Native Other/STREAM_ID.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      /// <summary>The type of the data contained in the backup stream.</summary>
      internal enum STREAM_ID
      {
         /// <summary>This indicates an error.</summary>
         NONE = 0,

         /// <summary>Standard data. This corresponds to the NTFS $DATA stream type on the default (unnamed) data stream.</summary>
         BACKUP_DATA = 1,

         /// <summary>Extended attribute data. This corresponds to the NTFS $EA stream type.</summary>
         BACKUP_EA_DATA = 2,

         /// <summary>Security descriptor data.</summary>
         BACKUP_SECURITY_DATA = 3,

         /// <summary>Alternative data streams. This corresponds to the NTFS $DATA stream type on a named data stream.</summary>
         BACKUP_ALTERNATE_DATA = 4,

         /// <summary>Hard link information. This corresponds to the NTFS $FILE_NAME stream type.</summary>
         BACKUP_LINK = 5,

         /// <summary>Property data.</summary>
         BACKUP_PROPERTY_DATA = 6,

         /// <summary>Objects identifiers. This corresponds to the NTFS $OBJECT_ID stream type.</summary>
         BACKUP_OBJECT_ID = 7,

         /// <summary>Reparse points. This corresponds to the NTFS $REPARSE_POINT stream type.</summary>
         BACKUP_REPARSE_DATA = 8,

         /// <summary>Sparse file. This corresponds to the NTFS $DATA stream type for a sparse file.</summary>
         BACKUP_SPARSE_BLOCK = 9,

         /// <summary>Transactional NTFS (TxF) data stream.</summary>
         /// <remarks>Windows Server 2003 and Windows XP:  This value is not supported.</remarks>
         BACKUP_TXFS_DATA = 10
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetLongShort83PathCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>Retrieves the short path form, or the regular long form of the specified <paramref name="path"/>.</summary>
      /// <returns>If <paramref name="getShort"/> is <c>true</c>, a path of the 8.3 form otherwise the regular long form.</returns>
      /// <remarks>
      ///   <para>Will fail on NTFS volumes with disabled 8.3 name generation.</para>
      ///   <para>The path must actually exist to be able to get the short- or long path name.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">An existing path to a folder or file.</param>
      /// <param name="getShort"><c>true</c> to retrieve the short path form, <c>false</c> to retrieve the regular long form from the 8.3 <paramref name="path"/>.</param>
      [SecurityCritical]
      private static string GetLongShort83PathCore(KernelTransaction transaction, string path, bool getShort)
      {
         var pathLp = GetFullPathCore(transaction, false, path, GetFullPathOptions.AsLongPath | GetFullPathOptions.FullCheck);

         var buffer = new StringBuilder();
         var actualLength = getShort ? NativeMethods.GetShortPathName(pathLp, null, 0) : (uint) path.Length;

         while (actualLength > buffer.Capacity)
         {
            buffer = new StringBuilder((int) actualLength);
            actualLength = getShort

               // GetShortPathName() / GetLongPathName()
               // 2014-01-29: MSDN confirms LongPath usage.

               ? NativeMethods.GetShortPathName(pathLp, buffer, (uint) buffer.Capacity) : transaction == null || !NativeMethods.IsAtLeastWindowsVista

                  ? NativeMethods.GetLongPathName(pathLp, buffer, (uint) buffer.Capacity)

                  : NativeMethods.GetLongPathNameTransacted(pathLp, buffer, (uint) buffer.Capacity, transaction.SafeHandle);


            var lastError = Marshal.GetLastWin32Error();

            if (actualLength == 0)
               NativeError.ThrowException(lastError, pathLp);
         }

         return GetRegularPathCore(buffer.ToString(), GetFullPathOptions.None, false);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory_GetFileSystemEntries_LongPathPrefix_ShouldReturnCorrectEntries.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;

namespace AlphaFS.UnitTest
{
   public partial class DirectoryTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void Directory_GetFileSystemEntries_LongPathWithPrefix_ShouldReturnCorrectEntries_LocalAndNetwork_Success()
      {
         Directory_GetFileSystemEntries_LongPath_ShouldReturnCorrectEntries(false, true);
         Directory_GetFileSystemEntries_LongPath_ShouldReturnCorrectEntries(true, true);
      }


      [TestMethod]
      public void Directory_GetFileSystemEntries_LongPathWithoutPrefix_ShouldReturnCorrectEntries_Network_Success()
      {
         Directory_GetFileSystemEntries_LongPath_ShouldReturnCorrectEntries(false, false);
         Directory_GetFileSystemEntries_LongPath_ShouldReturnCorrectEntries(true, false);
      }


      private void Directory_GetFileSystemEntries_LongPath_ShouldReturnCorrectEntries(bool isNetwork, bool withPrefix)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.RandomDirectoryFullPath;

            Console.WriteLine("Input Directory Path: [{0}]", folder);


            var longDir = System.IO.Path.Combine(folder, new string('x', 128), new string('x', 128), new string('x', 128), new string('x', 128));

            Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(longDir);

            Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(System.IO.Path.Combine(longDir, "A"));

            Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(System.IO.Path.Combine(longDir, "B"));

            Alphaleonis.Win32.Filesystem.File.WriteAllText(System.IO.Path.Combine(longDir, "C"), "C");


            var prefix = withPrefix ? isNetwork ? Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix : Alphaleonis.Win32.Filesystem.Path.LongPathPrefix : string.Empty;

            var entries = Alphaleonis.Win32.Filesystem.Directory.GetFileSystemEntries(prefix + longDir).ToArray();


            Assert.AreEqual(3, entries.Length);
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path.LocalToUnc.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Net.NetworkInformation;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      #region Obsolete

      /// <summary>[AlphaFS] Converts a local path to a network share path, optionally returning it as a long path format and the ability to add or remove a trailing backslash.
      ///   <para>A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows".</para>
      ///   <para>If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing <see cref="DirectorySeparator"/> character.</para>
      /// </summary>
      /// <returns>On successful conversion a UNC path is returned.
      ///   <para>If the conversion fails, <paramref name="localPath"/> is returned.</para>
      ///   <para>If <paramref name="localPath"/> is an empty string or <c>null</c>, <c>null</c> is returned.</para>
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="PathTooLongException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="localPath">A local path, e.g.: "C:\Windows".</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      /// <param name="fullPathOptions">Options for controlling the full path retrieval.</param>
      [Obsolete]
      [SecurityCritical]
      public static string LocalToUnc(string localPath, PathFormat pathFormat, GetFullPathOptions fullPathOptions)
      {
         return LocalToUncCore(localPath, fullPathOptions, pathFormat);
      }

      #endregion // Obsolete


      /// <summary>[AlphaFS] Converts a local path to a network share path.  
      ///   <para>A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows".</para>
      ///   <para>If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing <see cref="DirectorySeparator"/> character.</para>
      /// </summary>
      /// <returns>On successful conversion a UNC path is returned.
      ///   <para>If the conversion fails, <paramref name="localPath"/> is returned.</para>
      ///   <para>If <paramref name="localPath"/> is an empty string or <c>null</c>, <c>null</c> is returned.</para>
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="PathTooLongException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="localPath">A local path, e.g.: "C:\Windows".</param>
      [SecurityCritical]
      public static string LocalToUnc(string localPath)
      {
         return LocalToUncCore(localPath, GetFullPathOptions.None, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Converts a local path to a network share path.  
      ///   <para>A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows".</para>
      ///   <para>If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing <see cref="DirectorySeparator"/> character.</para>
      /// </summary>
      /// <returns>On successful conversion a UNC path is returned.
      ///   <para>If the conversion fails, <paramref name="localPath"/> is returned.</para>
      ///   <para>If <paramref name="localPath"/> is an empty string or <c>null</c>, <c>null</c> is returned.</para>
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="PathTooLongException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="localPath">A local path, e.g.: "C:\Windows".</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      [SecurityCritical]
      public static string LocalToUnc(string localPath, PathFormat pathFormat)
      {
         return LocalToUncCore(localPath, GetFullPathOptions.None, pathFormat);
      }
      

      /// <summary>[AlphaFS] Converts a local path to a network share path, optionally returning it as a long path format and the ability to add or remove a trailing backslash.
      ///   <para>A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows".</para>
      ///   <para>If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing <see cref="DirectorySeparator"/> character.</para>
      /// </summary>
      /// <returns>On successful conversion a UNC path is returned.
      ///   <para>If the conversion fails, <paramref name="localPath"/> is returned.</para>
      ///   <para>If <paramref name="localPath"/> is an empty string or <c>null</c>, <c>null</c> is returned.</para>
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="PathTooLongException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="localPath">A local path, e.g.: "C:\Windows".</param>
      /// <param name="fullPathOptions">Options for controlling the full path retrieval.</param>
      [SecurityCritical]
      public static string LocalToUnc(string localPath, GetFullPathOptions fullPathOptions)
      {
         return LocalToUncCore(localPath, fullPathOptions, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Converts a local path to a network share path, optionally returning it as a long path format and the ability to add or remove a trailing backslash.
      ///   <para>A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows".</para>
      ///   <para>If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing <see cref="DirectorySeparator"/> character.</para>
      /// </summary>
      /// <returns>On successful conversion a UNC path is returned.
      ///   <para>If the conversion fails, <paramref name="localPath"/> is returned.</para>
      ///   <para>If <paramref name="localPath"/> is an empty string or <c>null</c>, <c>null</c> is returned.</para>
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="PathTooLongException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="localPath">A local path, e.g.: "C:\Windows".</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      /// <param name="fullPathOptions">Options for controlling the full path retrieval.</param>
      [SecurityCritical]
      public static string LocalToUnc(string localPath, GetFullPathOptions fullPathOptions, PathFormat pathFormat)
      {
         return LocalToUncCore(localPath, fullPathOptions, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File.FindFirstStreamNative.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "lastError")]
      [SecurityCritical]
      internal static SafeFindFileHandle FindFirstStreamNative(KernelTransaction transaction, string pathLp, SafeGlobalMemoryBufferHandle buffer)
      {
         var safeFindFileHandle = null == transaction

            // FindFirstStreamW() / FindFirstStreamTransactedW()
            // 2018-01-15: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

            ? NativeMethods.FindFirstStreamW(pathLp, NativeMethods.STREAM_INFO_LEVELS.FindStreamInfoStandard, buffer, 0)
            : NativeMethods.FindFirstStreamTransactedW(pathLp, NativeMethods.STREAM_INFO_LEVELS.FindStreamInfoStandard, buffer, 0, transaction.SafeHandle);

         var lastError = Marshal.GetLastWin32Error();

         return NativeMethods.IsValidHandle(safeFindFileHandle, false) ? safeFindFileHandle : null;
      }
   }
}


<|start_filename|>src/AlphaFS/Security/CRC/HashType.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Security
{
   /// <summary>Enum containing the supported hash types.</summary>
   public enum HashType
   {
      /// <summary>CRC-32 (Cyclic Redundancy Check)</summary>
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CRC")]
      CRC32,

      /// <summary>CRC-64 ISO-3309 compliant.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CRC")]
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ISO")]
      CRC64ISO3309,

      /// <summary>MD5 (Message digest)</summary>
      MD5,

      /// <summary>RIPEMD-160 is a 160-bit cryptographic hash function. It is intended for use as a replacement for the 128-bit hash functions MD4, MD5, and RIPEMD.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "RIPEMD")]
      RIPEMD160,

      /// <summary>SHA-1 (Secure Hash Algorithm)</summary>
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SHA")]
      SHA1,

      /// <summary>SHA-256 (Secure Hash Algorithm)</summary>
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SHA")]
      SHA256,

      /// <summary>SHA-384 (Secure Hash Algorithm)</summary>
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SHA")]
      SHA384,

      /// <summary>SHA-512 (Secure Hash Algorithm)</summary>
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SHA")]
      SHA512
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.ImportExportEncryptedFileDirectoryRawCore.cs<|end_filename|>
﻿/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      internal static void ImportExportEncryptedFileDirectoryRawCore(bool isExport, bool isFolder, Stream stream, string destinationPath, bool overwriteHidden, PathFormat pathFormat)
      {
         var destinationPathLp = Path.GetExtendedLengthPathCore(null, destinationPath, pathFormat, GetFullPathOptions.FullCheck | GetFullPathOptions.TrimEnd);

         var mode = isExport ? NativeMethods.EncryptedFileRawMode.CreateForExport : NativeMethods.EncryptedFileRawMode.CreateForImport;

         if (isFolder)
            mode = mode | NativeMethods.EncryptedFileRawMode.CreateForDir;

         if (overwriteHidden)
            mode = mode | NativeMethods.EncryptedFileRawMode.OverwriteHidden;


         // OpenEncryptedFileRaw()
         // 2015-08-02: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

         SafeEncryptedFileRawHandle context;
         var lastError = NativeMethods.OpenEncryptedFileRaw(destinationPathLp, mode, out context);

         try
         {
            if (lastError != Win32Errors.NO_ERROR)
               NativeError.ThrowException((int) lastError, isFolder, destinationPathLp);


            lastError = isExport
               ? NativeMethods.ReadEncryptedFileRaw((pbData, pvCallbackContext, length) =>
               {
                  try
                  {
                     var data = new byte[length];

                     Marshal.Copy(pbData, data, 0, (int) length);

                     stream.Write(data, 0, (int) length);
                  }
                  catch (Exception ex)
                  {
                     return Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift;
                  }

                  return (int) Win32Errors.NO_ERROR;

               }, IntPtr.Zero, context)


               : NativeMethods.WriteEncryptedFileRaw((IntPtr pbData, IntPtr pvCallbackContext, ref uint length) =>
               {
                  try
                  {
                     var data = new byte[length];

                     length = (uint) stream.Read(data, 0, (int) length);

                     if (length == 0)
                        return (int) Win32Errors.NO_ERROR;

                     Marshal.Copy(data, 0, pbData, (int) length);
                  }
                  catch (Exception ex)
                  {
                     return Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift;
                  }

                  return (int) Win32Errors.NO_ERROR;

               }, IntPtr.Zero, context);


            if (lastError != Win32Errors.NO_ERROR)
               NativeError.ThrowException((int) lastError, isFolder, destinationPathLp);
         }
         finally
         {
            if (null != context && !context.IsClosed)
               context.Dispose();
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Gets the shortest display name for the specified <paramref name="volumeName"/>.</summary>
      /// <remarks>This method basically returns the shortest string returned by <see cref="EnumerateVolumePathNames"/></remarks>
      /// <param name="volumeName">A volume <see cref="Guid"/> path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\.</param>
      /// <returns>
      ///   The shortest display name for the specified volume found, or <c>null</c> if no display names were found.
      /// </returns>
      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      [SecurityCritical]
      public static string GetVolumeDisplayName(string volumeName)
      {
         string[] smallestMountPoint = { new string(Path.WildcardStarMatchAllChar, NativeMethods.MaxPathUnicode) };

         try
         {
            foreach (var m in EnumerateVolumePathNames(volumeName).Where(m => !Utils.IsNullOrWhiteSpace(m) && m.Length < smallestMountPoint[0].Length))
               smallestMountPoint[0] = m;
         }
         catch
         {
         }

         var result = smallestMountPoint[0][0] == Path.WildcardStarMatchAllChar ? null : smallestMountPoint[0];
         return Utils.IsNullOrWhiteSpace(result) ? null : result;
      }
   }
}


<|start_filename|>src/AlphaFS/Network/ShareInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Filesystem;
using System;
using System.Globalization;

namespace Alphaleonis.Win32.Network
{
   /// <summary>Contains information about Server Message Block (SMB) shares. This class cannot be inherited.</summary>
   [Serializable]
   public sealed class ShareInfo
   {
      #region Constructor

      /// <summary>Creates a <see cref="ShareInfo"/> instance.</summary>
      /// <param name="host">A host to retrieve shares from.</param>
      /// <param name="shareLevel">One of the <see cref="ShareInfoLevel"/> options.</param>
      /// <param name="shareInfo">A <see cref="NativeMethods.SHARE_INFO_2"/> or <see cref="NativeMethods.SHARE_INFO_503"/> instance.</param>
      internal ShareInfo(string host, ShareInfoLevel shareLevel, object shareInfo)
      {
         host = host ?? Environment.MachineName;


         switch (shareLevel)
         {
            case ShareInfoLevel.Info1005:
               var s1005 = (NativeMethods.SHARE_INFO_1005) shareInfo;
               ServerName = host;
               ResourceType = s1005.shi1005_flags;
               break;


            case ShareInfoLevel.Info503:
               var s503 = (NativeMethods.SHARE_INFO_503) shareInfo;
               CurrentUses = s503.shi503_current_uses;
               MaxUses = s503.shi503_max_uses;
               NetName = s503.shi503_netname;
               Password = <PASSWORD>;
               Path = Utils.IsNullOrWhiteSpace(s503.shi503_path) ? null : s503.shi503_path;
               Permissions = s503.shi503_permissions;
               Remark = s503.shi503_remark;
               ServerName = s503.shi503_servername == "*" ? host : s503.shi503_servername;
               ShareType = s503.shi503_type;
               SecurityDescriptor = s503.shi503_security_descriptor;
               break;


            case ShareInfoLevel.Info502:
               var s502 = (NativeMethods.SHARE_INFO_502) shareInfo;
               CurrentUses = s502.shi502_current_uses;
               MaxUses = s502.shi502_max_uses;
               NetName = s502.shi502_netname;
               Password = <PASSWORD>;
               Path = Utils.IsNullOrWhiteSpace(s502.shi502_path) ? null : s502.shi502_path;
               Permissions = s502.shi502_permissions;
               Remark = s502.shi502_remark;
               ServerName = host;
               ShareType = s502.shi502_type;
               SecurityDescriptor = s502.shi502_security_descriptor;
               break;


            case ShareInfoLevel.Info2:
               var s2 = (NativeMethods.SHARE_INFO_2) shareInfo;
               CurrentUses = s2.shi2_current_uses;
               MaxUses = s2.shi2_max_uses;
               NetName = s2.shi2_netname;
               Password = <PASSWORD>;
               Path = Utils.IsNullOrWhiteSpace(s2.shi2_path) ? null : s2.shi2_path;
               Permissions = s2.shi2_permissions;
               Remark = s2.shi2_remark;
               ServerName = host;
               ShareType = s2.shi2_type;
               break;


            case ShareInfoLevel.Info1:
               var s1 = (NativeMethods.SHARE_INFO_1) shareInfo;
               CurrentUses = 0;
               MaxUses = 0;
               NetName = s1.shi1_netname;
               Password = <PASSWORD>;
               Path = null;
               Permissions = AccessPermissions.None;
               Remark = s1.shi1_remark;
               ServerName = host;
               ShareType = s1.shi1_type;
               break;
         }


         NetFullPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", Filesystem.Path.UncPrefix, ServerName, Filesystem.Path.DirectorySeparatorChar, NetName);

         ShareLevel = shareLevel;
      }

      #endregion // Constructor


      #region Methods

      /// <summary>Returns the full path to the share.</summary>
      /// <returns>A string that represents this instance.</returns>
      public override string ToString()
      {
         return NetFullPath;
      }

      #endregion // Methods


      #region Properties

      /// <summary>The number of current connections to the resource.</summary>
      public long CurrentUses { get; private set; }


      private DirectoryInfo _directoryInfo;

      /// <summary>The <see cref="DirectoryInfo"/> instance associated with this share.</summary>
      public DirectoryInfo DirectoryInfo
      {
         get { return _directoryInfo ?? (_directoryInfo = new DirectoryInfo(null, NetFullPath, PathFormat.FullPath)); }
      }


      /// <summary>Returns the full UNC path to the share.</summary>
      public string NetFullPath { get; internal set; }


      /// <summary>The maximum number of concurrent connections that the shared resource can accommodate.</summary>
      /// <remarks>The number of connections is unlimited if the value specified in this member is –1.</remarks>
      public long MaxUses { get; private set; }


      /// <summary>The name of the shared resource.</summary>
      public string NetName { get; private set; }


      /// <summary>The share's password (when the server is running with share-level security).</summary>
      public string Password { get; private set; }


      /// <summary>The local path for the shared resource.</summary>
      /// <remarks>For disks, this member is the path being shared. For print queues, this member is the name of the print queue being shared.</remarks>
      public string Path { get; private set; }


      /// <summary>The shared resource's permissions for servers running with share-level security.</summary>
      /// <remarks>Note that Windows does not support share-level security. This member is ignored on a server running user-level security.</remarks>
      public AccessPermissions Permissions { get; private set; }


      /// <summary>An optional comment about the shared resource.</summary>
      public string Remark { get; private set; }


      /// <summary>Specifies the SECURITY_DESCRIPTOR associated with this share.</summary>
      public IntPtr SecurityDescriptor { get; private set; }


      /// <summary>A pointer to a string that specifies the DNS or NetBIOS name of the remote server on which the shared resource resides.</summary>
      /// <remarks>A value of "*" indicates no configured server name.</remarks>
      public string ServerName { get; private set; }


      /// <summary>The type of share.</summary>
      public ShareType ShareType { get; private set; }


      private ShareResourceTypes _shareResourceType;

      /// <summary>The type of share resource.</summary>
      public ShareResourceTypes ResourceType
      {
         get
         {
            if (_shareResourceType == ShareResourceTypes.None && !Utils.IsNullOrWhiteSpace(NetName))
               _shareResourceType = Host.GetShareInfoCore(ShareInfoLevel.Info1005, ServerName, NetName, true).ResourceType;

            return _shareResourceType;
         }

         private set { _shareResourceType = value; }
      }


      /// <summary>The structure level for the <see cref="ShareInfo"/> instance.</summary>
      public ShareInfoLevel ShareLevel { get; private set; }

      #endregion // Properties
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_WithDirectorySecurity.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class Directory_CreateDirectoryTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void Directory_CreateDirectory_WithDirectorySecurity_LocalAndNetwork_Success()
      {
         UnitTestAssert.IsElevatedProcess();

         Directory_CreateDirectory_WithDirectorySecurity(false);
         Directory_CreateDirectory_WithDirectorySecurity(true);
      }


      private void Directory_CreateDirectory_WithDirectorySecurity(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.RandomDirectoryFullPath;

            Console.WriteLine("Input Directory Path: [{0}]\n", folder);


            var pathExpected = tempRoot.RandomDirectoryFullPath;
            var pathActual = tempRoot.RandomDirectoryFullPath;
            

            var sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            var expectedDirectorySecurity = new System.Security.AccessControl.DirectorySecurity();
            expectedDirectorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(sid, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
            expectedDirectorySecurity.AddAuditRule(new System.Security.AccessControl.FileSystemAuditRule(sid, System.Security.AccessControl.FileSystemRights.Read, System.Security.AccessControl.AuditFlags.Success));


            using (new Alphaleonis.Win32.Security.PrivilegeEnabler(Alphaleonis.Win32.Security.Privilege.Security))
            {
               var s1 = System.IO.Directory.CreateDirectory(pathExpected, expectedDirectorySecurity);
               var s2 = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(pathActual, expectedDirectorySecurity);


               var expected = s1.GetAccessControl().GetSecurityDescriptorSddlForm(System.Security.AccessControl.AccessControlSections.All);
               var actual = s2.GetAccessControl().GetSecurityDescriptorSddlForm(System.Security.AccessControl.AccessControlSections.All);


               Console.WriteLine("\tSystem.IO: {0}", expected);
               Console.WriteLine("\tAlphaFS  : {0}", actual);


               Assert.AreEqual(expected, actual);
            }
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Structures, Enumerations/StreamId.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>The type of the data contained in the backup stream. This member can be one of the following values.</summary>
   public enum StreamId
   {
      /// <summary>This indicates an error.</summary>
      None = NativeMethods.STREAM_ID.NONE,


      /// <summary>Standard data. This corresponds to the NTFS $DATA stream type on the default (unnamed) data stream.</summary>
      BackupData = NativeMethods.STREAM_ID.BACKUP_DATA,


      /// <summary>Extended attribute data. This corresponds to the NTFS $EA stream type.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ea")]
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ea")]
      BackupEaData = NativeMethods.STREAM_ID.BACKUP_EA_DATA,


      /// <summary>Security descriptor data.</summary>
      BackupSecurityData = NativeMethods.STREAM_ID.BACKUP_SECURITY_DATA,


      /// <summary>Alternative data streams. This corresponds to the NTFS $DATA stream type on a named data stream.</summary>
      BackupAlternateData = NativeMethods.STREAM_ID.BACKUP_ALTERNATE_DATA,


      /// <summary>Hard link information. This corresponds to the NTFS $FILE_NAME stream type.</summary>
      BackupLink = NativeMethods.STREAM_ID.BACKUP_LINK,


      /// <summary>Property data.</summary>
      BackupPropertyData = NativeMethods.STREAM_ID.BACKUP_PROPERTY_DATA,


      /// <summary>Objects identifiers. This corresponds to the NTFS $OBJECT_ID stream type.</summary>
      BackupObjectId = NativeMethods.STREAM_ID.BACKUP_OBJECT_ID,


      /// <summary>Reparse points. This corresponds to the NTFS $REPARSE_POINT stream type.</summary>
      BackupReparseData = NativeMethods.STREAM_ID.BACKUP_REPARSE_DATA,


      /// <summary>Sparse file. This corresponds to the NTFS $DATA stream type for a sparse file.</summary>
      BackupSparseBlock = NativeMethods.STREAM_ID.BACKUP_SPARSE_BLOCK,


      /// <summary>Transactional NTFS (TxF) data stream.</summary>
      /// <remarks>Windows Server 2003 and Windows XP:  This value is not supported.</remarks>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Txfs")]
      BackupTxfsData = NativeMethods.STREAM_ID.BACKUP_TXFS_DATA
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_Overwrite_DestinationFileAlreadyExists.cs<|end_filename|>
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class CopyTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_File_Copy_Overwrite_DestinationFileAlreadyExists_LocalAndNetwork_Success()
      {
         AlphaFS_File_Copy_Overwrite_DestinationFileAlreadyExists(false);
         AlphaFS_File_Copy_Overwrite_DestinationFileAlreadyExists(true);
      }

      
      private void AlphaFS_File_Copy_Overwrite_DestinationFileAlreadyExists(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var srcFile = tempRoot.CreateFile();
            var dstFile = tempRoot.CreateFile();

            Console.WriteLine("Src File Path: [{0}]", srcFile.FullName);
            Console.WriteLine("Dst File Path: [{0}]", dstFile.FullName);


            UnitTestAssert.ThrowsException<System.IO.IOException>(() => System.IO.File.Copy(srcFile.FullName, dstFile.FullName));
            
            UnitTestAssert.ThrowsException<Alphaleonis.Win32.Filesystem.AlreadyExistsException>(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFile.FullName, dstFile.FullName));
            

            Alphaleonis.Win32.Filesystem.File.Copy(srcFile.FullName, dstFile.FullName, true);


            Assert.IsTrue(System.IO.File.Exists(srcFile.FullName), "The file does not exists, but is expected to.");

            Assert.IsTrue(System.IO.File.Exists(dstFile.FullName), "The file does not exists, but is expected to.");
         }
         
         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.SMB.EnumerateOpenResources.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Security;
using Alphaleonis.Win32.Filesystem;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>Enumerates open resources from the local host.</summary>
      /// <returns><see cref="IEnumerable{OpenResourceInfo}"/> open resources from the local host.</returns>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="NetworkInformationException"/>
      [SecurityCritical]
      public static IEnumerable<OpenResourceInfo> EnumerateOpenResources()
      {
         return EnumerateOpenResourcesCore(null, null, null, false);
      }

      
      /// <summary>Enumerates open resources from the specified host.</summary>
      /// <returns><see cref="IEnumerable{String}"/> open resources from the specified <paramref name="host"/>.</returns>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="host">The DNS or NetBIOS name of the remote server. <c>null</c> refers to the local host.</param>
      /// <param name="basePath">
      ///   This parameter may be <c>null</c>. Enumerates only resources that have the value of the basepath parameter as a prefix.
      ///   (A prefix is the portion of a path that comes before a backslash.)
      /// </param>
      /// <param name="typeName">
      ///   This parameter may be <c>null</c>. The name of the user or the name of the connection; If <paramref name="typeName"/>
      ///   does not begin with two backslashes ("\\") it indicates the name of the user. If <paramref name="typeName"/> begins with two
      ///   backslashes ("\\") it indicates the name of the connection.
      /// </param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public static IEnumerable<OpenResourceInfo> EnumerateOpenResources(string host, string basePath, string typeName, bool continueOnException)
      {
         return EnumerateOpenResourcesCore(host, basePath, typeName, continueOnException);
      }




      /// <summary>>Enumerates open resources from the specified host.</summary>
      /// <returns><see cref="IEnumerable{String}"/> open resources from the specified <paramref name="host"/>.</returns>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="host">The DNS or NetBIOS name of the remote server. <c>null</c> refers to the local host.</param>
      /// <param name="basePath">
      ///   This parameter may be <c>null</c>. Enumerates only resources that have the value of the basepath parameter as a prefix.
      ///   (A prefix is the portion of a path that comes before a backslash.)
      /// </param>
      /// <param name="typeName">
      ///   This parameter may be <c>null</c>. The name of the user or the name of the connection; If <paramref name="typeName"/>
      ///   does not begin with two backslashes ("\\") it indicates the name of the user. If <paramref name="typeName"/> begins with two
      ///   backslashes ("\\") it indicates the name of the connection.
      /// </param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      internal static IEnumerable<OpenResourceInfo> EnumerateOpenResourcesCore(string host, string basePath, string typeName, bool continueOnException)
      {
         basePath = Utils.IsNullOrWhiteSpace(basePath) ? null : Path.GetRegularPathCore(basePath, GetFullPathOptions.CheckInvalidPathChars, false);
         typeName = Utils.IsNullOrWhiteSpace(typeName) ? null : typeName;


         var fd = new FunctionData {ExtraData1 = basePath, ExtraData2 = typeName};

         return EnumerateNetworkObjectCore(fd, (NativeMethods.FILE_INFO_3 structure, SafeGlobalMemoryBufferHandle buffer) => new OpenResourceInfo(host, structure),

            (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>
            {
               // When host == null, the local computer is used.
               // However, the resulting Host property will be empty.
               // So, explicitly state Environment.MachineName to prevent this.
               // Furthermore, the UNC prefix: \\ is not required and always removed.
               var stripUnc = Utils.IsNullOrWhiteSpace(host) ? Environment.MachineName : Path.GetRegularPathCore(host, GetFullPathOptions.CheckInvalidPathChars, false).Replace(Path.UncPrefix, string.Empty);

               return NativeMethods.NetFileEnum(stripUnc, fd.ExtraData1, fd.ExtraData2, 3, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle);

            }, continueOnException);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class TimestampsTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_File_GetChangeTime_LocalAndNetwork_Success()
      {
         AlphaFS_File_GetChangeTime(false);
         AlphaFS_File_GetChangeTime(true);
      }


      private void AlphaFS_File_GetChangeTime(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var notepadFile = System.IO.Path.Combine(Environment.SystemDirectory, "notepad.exe");

            Console.WriteLine("Input File Path: [{0}]", notepadFile);


            Assert.AreEqual(System.IO.File.GetCreationTime(notepadFile), Alphaleonis.Win32.Filesystem.File.GetCreationTime(notepadFile));
            Assert.AreEqual(System.IO.File.GetCreationTimeUtc(notepadFile), Alphaleonis.Win32.Filesystem.File.GetCreationTimeUtc(notepadFile));

            Assert.AreEqual(System.IO.File.GetLastAccessTime(notepadFile), Alphaleonis.Win32.Filesystem.File.GetLastAccessTime(notepadFile));
            Assert.AreEqual(System.IO.File.GetLastAccessTimeUtc(notepadFile), Alphaleonis.Win32.Filesystem.File.GetLastAccessTimeUtc(notepadFile));

            Assert.AreEqual(System.IO.File.GetLastWriteTime(notepadFile), Alphaleonis.Win32.Filesystem.File.GetLastWriteTime(notepadFile));
            Assert.AreEqual(System.IO.File.GetLastWriteTimeUtc(notepadFile), Alphaleonis.Win32.Filesystem.File.GetLastWriteTimeUtc(notepadFile));


            // We can not compare ChangeTime against .NET because it does not exist.
            // Creating a file and renaming it triggers ChangeTime, so test for that.

            var file = tempRoot.CreateFile();
            Console.WriteLine("Input File Path: [{0}]\n", file.FullName);


            var fileName = file.Name;


            var changeTimeActual = Alphaleonis.Win32.Filesystem.File.GetChangeTime(file.FullName);

            var changeTimeUtcActual = Alphaleonis.Win32.Filesystem.File.GetChangeTimeUtc(file.FullName);


            // Sleep for three seconds.
            var delay = 3;

            file.MoveTo(file.FullName.Replace(fileName, fileName + "-Renamed"));
            Thread.Sleep(delay * 1000);
            file.MoveTo(file.FullName.Replace(fileName + "-Renamed", fileName));


            var newChangeTime = changeTimeActual.AddSeconds(3);
            Assert.AreEqual(changeTimeActual.AddSeconds(3), newChangeTime);

            newChangeTime = changeTimeUtcActual.AddSeconds(3);
            Assert.AreEqual(changeTimeUtcActual.AddSeconds(3), newChangeTime);
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.EncryptDecryptDirectoryCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Decrypts/encrypts a directory recursively so that only the account used to encrypt the directory can decrypt it.</summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryReadOnlyException"/>
      /// <exception cref="FileReadOnlyException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="path">A path that describes a directory to encrypt.</param>
      /// <param name="encrypt"><c>true</c> encrypt, <c>false</c> decrypt.</param>
      /// <param name="recursive"><c>true</c> to decrypt the directory recursively. <c>false</c> only decrypt files and directories in the root of <paramref name="path"/>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void EncryptDecryptDirectoryCore(string path, bool encrypt, bool recursive, PathFormat pathFormat)
      {
         if (pathFormat != PathFormat.LongFullPath)
         {
            path = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

            pathFormat = PathFormat.LongFullPath;
         }


         // Process folders and files when recursive. 

         if (recursive)
         {
            foreach (var fsei in EnumerateFileSystemEntryInfosCore<string>(null, null, path, Path.WildcardStarMatchAll, SearchOption.AllDirectories, DirectoryEnumerationOptions.AsLongPath, null, pathFormat))

               File.EncryptDecryptFileCore(true, fsei, encrypt, pathFormat);
         }

         // Process the root folder, the given path.

         File.EncryptDecryptFileCore(true, path, encrypt, pathFormat);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.DeleteEmptySubdirectories/AlphaFS_Directory.DeleteEmptySubdirectories.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_Directory_DeleteEmptySubdirectoriesTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_DeleteEmptySubdirectories_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_DeleteEmptySubdirectories(false);
         AlphaFS_Directory_DeleteEmptySubdirectories(true);
      }

      
      private void AlphaFS_Directory_DeleteEmptySubdirectories(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            const int maxDepth = 10;
            const int totalDirectories = maxDepth * maxDepth + maxDepth;            // maxDepth = 10: 110 directories and 110 files.
            const int emptyDirectories = maxDepth * maxDepth / 2;                   // 50 empty directories.
            const int remainingDirectories = totalDirectories - emptyDirectories;   // 60 remaining directories.
            
            var folder = tempRoot.CreateRecursiveTree(maxDepth);

            Console.WriteLine("Input Directory Path: [{0}]", folder.FullName);
            

            var searchPattern = Alphaleonis.Win32.Filesystem.Path.WildcardStarMatchAll;
            const Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions enumOptionsFolder = Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Folders | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.ContinueOnException;
            const Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions enumOptionsFile = Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Files | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.ContinueOnException;
            

            var dirs0 = Alphaleonis.Win32.Filesystem.Directory.CountFileSystemObjects(folder.FullName, searchPattern, enumOptionsFolder);
            var files0 = Alphaleonis.Win32.Filesystem.Directory.CountFileSystemObjects(folder.FullName, searchPattern, enumOptionsFile);
            Console.WriteLine("\n\tCounted Directories: [{0}]  Empty Directories: [{1}]", dirs0, emptyDirectories);
            Console.WriteLine("\tCounted Files      : [{0}]", files0);


            Alphaleonis.Win32.Filesystem.Directory.DeleteEmptySubdirectories(folder.FullName, true);


            Assert.IsTrue(System.IO.Directory.Exists(folder.FullName), "The root directory does not exist, but is expected to.");

            var dirs1 = Alphaleonis.Win32.Filesystem.Directory.CountFileSystemObjects(folder.FullName, searchPattern, enumOptionsFolder);
            var files1 = Alphaleonis.Win32.Filesystem.Directory.CountFileSystemObjects(folder.FullName, searchPattern, enumOptionsFile);
            Console.WriteLine("\n\tCounted Directories: [{0}]", dirs1);
            Console.WriteLine("\tCounted Files      : [{0}]", files1);

            Assert.AreNotEqual(dirs0, dirs1, "The number of directories are equal, but are expected not to.");
            Assert.AreEqual(remainingDirectories, dirs1, "The number of directories are not equal, but are expected to be.");
            Assert.AreEqual(files0, files1, "The number of files are not equal, but are expected to be.");
            Assert.AreEqual(totalDirectories, emptyDirectories + remainingDirectories, "The number of directories are not equal, but are expected to be.");
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileIdBothDirectoryInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>[AlphaFS] Retrieves information about files in the directory specified by <paramref name="path"/> in <see cref="FileShare.ReadWrite"/> mode.</summary>
      /// <returns>An enumeration of <see cref="FileIdBothDirectoryInfo"/> records for each file system entry in the specified diretory.</returns>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">A path to a directory from which to retrieve information.</param>
      [SecurityCritical]
      public static IEnumerable<FileIdBothDirectoryInfo> EnumerateFileIdBothDirectoryInfo(string path)
      {
         return EnumerateFileIdBothDirectoryInfoCore(null, null, path, FileShare.ReadWrite, false, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Retrieves information about files in the directory specified by <paramref name="path"/> in <see cref="FileShare.ReadWrite"/> mode.</summary>
      /// <returns>An enumeration of <see cref="FileIdBothDirectoryInfo"/> records for each file system entry in the specified diretory.</returns>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">A path to a directory from which to retrieve information.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static IEnumerable<FileIdBothDirectoryInfo> EnumerateFileIdBothDirectoryInfo(string path, PathFormat pathFormat)
      {
         return EnumerateFileIdBothDirectoryInfoCore(null, null, path, FileShare.ReadWrite, false, pathFormat);
      }


      /// <summary>[AlphaFS] Retrieves information about files in the directory specified by <paramref name="path"/> in specified <see cref="FileShare"/> mode.</summary>
      /// <returns>An enumeration of <see cref="FileIdBothDirectoryInfo"/> records for each file system entry in the specified diretory.</returns>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">A path to a directory from which to retrieve information.</param>
      /// <param name="shareMode">The <see cref="FileShare"/> mode with which to open a handle to the directory.</param>
      [SecurityCritical]
      public static IEnumerable<FileIdBothDirectoryInfo> EnumerateFileIdBothDirectoryInfo(string path, FileShare shareMode)
      {
         return EnumerateFileIdBothDirectoryInfoCore(null, null, path, shareMode, false, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Retrieves information about files in the directory specified by <paramref name="path"/> in specified <see cref="FileShare"/> mode.</summary>
      /// <returns>An enumeration of <see cref="FileIdBothDirectoryInfo"/> records for each file system entry in the specified diretory.</returns>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">A path to a directory from which to retrieve information.</param>
      /// <param name="shareMode">The <see cref="FileShare"/> mode with which to open a handle to the directory.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static IEnumerable<FileIdBothDirectoryInfo> EnumerateFileIdBothDirectoryInfo(string path, FileShare shareMode, PathFormat pathFormat)
      {
         return EnumerateFileIdBothDirectoryInfoCore(null, null, path, shareMode, false, pathFormat);
      }


      /// <summary>[AlphaFS] Retrieves information about files in the directory handle specified.</summary>
      /// <returns>An IEnumerable of <see cref="FileIdBothDirectoryInfo"/> records for each file system entry in the specified diretory.</returns>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="handle">An open handle to the directory from which to retrieve information.</param>
      [SecurityCritical]
      public static IEnumerable<FileIdBothDirectoryInfo> EnumerateFileIdBothDirectoryInfo(SafeFileHandle handle)
      {
         // FileShare has no effect since a handle is already opened.
         return EnumerateFileIdBothDirectoryInfoCore(null, handle, null, FileShare.ReadWrite, false, PathFormat.RelativePath);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_DirectoryInfo.CreateJunction_And_ExistsJunction_And_DeleteJunction.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_JunctionsLinksTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_DirectoryInfo_CreateJunction_And_ExistsJunction_And_DeleteJunction_Local_Success()
      {
         using (var tempRoot = new TemporaryDirectory())
         {
            var toDelete = tempRoot.Directory.CreateSubdirectory("ToDelete");
            var junction = System.IO.Path.Combine(toDelete.FullName, "MyJunctionPoint");
            var target = tempRoot.Directory.CreateSubdirectory("JunctionTarget");

            Console.WriteLine("Input Directory JunctionPoint  Path: [{0}]", junction);
            Console.WriteLine("Input Directory JunctionTarget Path: [{0}]", target);


            #region CreateJunction

            var dirInfo = new Alphaleonis.Win32.Filesystem.DirectoryInfo(target.FullName);


            // On success, dirInfo.FullName now points to the directory junction.
            // The DirectoryInfo instance is updated.
            dirInfo.CreateJunction(junction);

            Assert.AreEqual(dirInfo.FullName, junction, "It is expected that the DirectoryInfo points to the directory junction, but it is not.");




            var dirInfoSysIO = new System.IO.DirectoryInfo(junction);
            UnitTestConstants.Dump(dirInfoSysIO);

            Assert.IsTrue((dirInfoSysIO.Attributes & System.IO.FileAttributes.ReparsePoint) != 0);


            

            var lvi = Alphaleonis.Win32.Filesystem.Directory.GetLinkTargetInfo(dirInfo.FullName);
            UnitTestConstants.Dump(lvi);
            UnitTestConstants.Dump(dirInfo.EntryInfo);

            Assert.AreEqual(System.IO.Directory.Exists(dirInfo.FullName), Alphaleonis.Win32.Filesystem.Directory.Exists(dirInfo.FullName));
            Assert.AreEqual(junction, dirInfo.FullName);




            Assert.IsTrue(dirInfo.EntryInfo.IsDirectory);
            Assert.IsTrue(dirInfo.EntryInfo.IsMountPoint);
            Assert.IsTrue(dirInfo.EntryInfo.IsReparsePoint);
            Assert.IsFalse(dirInfo.EntryInfo.IsSymbolicLink);
            Assert.AreEqual(dirInfo.EntryInfo.ReparsePointTag, Alphaleonis.Win32.Filesystem.ReparsePointTag.MountPoint);




            // Create a folder in the junction and test the target.
            const string subFolder = "Test folder";
            dirInfo.CreateSubdirectory(subFolder);

            Assert.IsTrue(System.IO.Directory.Exists(System.IO.Path.Combine(target.FullName, subFolder)));

            #endregion // CreateJunction


            // ExistsJunction

            Assert.IsTrue(Alphaleonis.Win32.Filesystem.Directory.ExistsJunction(dirInfo.FullName), "It is expected that the directory junction exists, but is does not.");

            Assert.IsTrue(System.IO.Directory.Exists(dirInfo.FullName), "It is expected that the directory exists, but is does not.");


            #region DeleteJunction

            // Remove directory junction, target directory should remain.
            dirInfo.DeleteJunction();


            Assert.IsTrue(System.IO.Directory.Exists(dirInfo.FullName));
            Assert.IsTrue(System.IO.Directory.Exists(dirInfo.Parent.FullName));

            Assert.IsTrue(dirInfo.EntryInfo.IsDirectory);
            Assert.IsFalse(dirInfo.EntryInfo.IsMountPoint);
            Assert.IsFalse(dirInfo.EntryInfo.IsReparsePoint);
            Assert.IsFalse(dirInfo.EntryInfo.IsSymbolicLink);
            Assert.AreNotEqual(dirInfo.EntryInfo.ReparsePointTag, Alphaleonis.Win32.Filesystem.ReparsePointTag.MountPoint);

            #endregion // DeleteJunction


            // ExistsJunction

            Assert.IsFalse(Alphaleonis.Win32.Filesystem.Directory.ExistsJunction(dirInfo.FullName), "It is expected that the directory junction does not exist, but is does.");

            Assert.IsTrue(System.IO.Directory.Exists(dirInfo.FullName), "It is expected that the directory exists, but is does not.");
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Compression/File.GetCompressedSizeTransacted.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>
      ///   [AlphaFS] Retrieves the actual number of bytes of disk storage used to store a specified file as part of a transaction. If the file
      ///   is located on a volume that supports compression and the file is compressed, the value obtained is the compressed size of the
      ///   specified file. If the file is located on a volume that supports sparse files and the file is a sparse file, the value obtained is
      ///   the sparse size of the specified file.
      /// </summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path"><para>The name of the file.</para></param>
      /// <returns>The actual number of bytes of disk storage used to store the specified file.</returns>
      [SecurityCritical]
      public static long GetCompressedSizeTransacted(KernelTransaction transaction, string path)
      {
         return GetCompressedSizeCore(transaction, path, PathFormat.RelativePath);
      }


      /// <summary>
      ///   [AlphaFS] Retrieves the actual number of bytes of disk storage used to store a specified file as part of a transaction. If the file
      ///   is located on a volume that supports compression and the file is compressed, the value obtained is the compressed size of the
      ///   specified file. If the file is located on a volume that supports sparse files and the file is a sparse file, the value obtained is
      ///   the sparse size of the specified file.
      /// </summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path"><para>The name of the file.</para></param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>The actual number of bytes of disk storage used to store the specified file.</returns>
      [SecurityCritical]
      public static long GetCompressedSizeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
      {
         return GetCompressedSizeCore(transaction, path, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/FileInfo Class/FileInfo CopyToMoveTo/FileInfo.MoveTo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   partial class FileInfo
   {
      #region .NET

      /// <summary>Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with details of the Move action.</returns>
      /// <remarks>
      ///   <para>Use this method to prevent overwriting of an existing file by default.</para>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param>
      [SecurityCritical]
      public void MoveTo(string destinationPath)
      {
         string destinationPathLp;

         CopyToMoveToCore(destinationPath, null, MoveOptions.CopyAllowed, false, null, null, out destinationPathLp, PathFormat.RelativePath);

         UpdateDestinationPath(destinationPath, destinationPathLp);
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>Returns a new <see cref="FileInfo"/> instance with a fully qualified path when successfully moved.</returns>
      /// <remarks>
      ///   <para>Use this method to prevent overwriting of an existing file by default.</para>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public FileInfo MoveTo(string destinationPath, PathFormat pathFormat)
      {
         string destinationPathLp;

         CopyToMoveToCore(destinationPath, null, MoveOptions.CopyAllowed, false, null, null, out destinationPathLp, pathFormat);

         UpdateDestinationPath(destinationPath, destinationPathLp);

         return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath);
      }
      

      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, <see cref="MoveOptions"/> can be specified.</summary>
      /// <returns>Returns a new <see cref="FileInfo"/> instance with a fully qualified path when successfully moved.</returns>
      /// <remarks>
      ///   <para>Use this method to allow or prevent overwriting of an existing file.</para>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public FileInfo MoveTo(string destinationPath, MoveOptions moveOptions)
      {
         string destinationPathLp;

         CopyToMoveToCore(destinationPath, null, moveOptions, false, null, null, out destinationPathLp, PathFormat.RelativePath);

         UpdateDestinationPath(destinationPath, destinationPathLp);

         return null != destinationPathLp ? new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath) : null;
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, <see cref="MoveOptions"/> can be specified.</summary>
      /// <returns>Returns a new <see cref="FileInfo"/> instance with a fully qualified path when successfully moved.</returns>
      /// <remarks>
      ///   <para>Use this method to allow or prevent overwriting of an existing file.</para>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public FileInfo MoveTo(string destinationPath, MoveOptions moveOptions, PathFormat pathFormat)
      {
         string destinationPathLp;

         CopyToMoveToCore(destinationPath, null, moveOptions, false, null, null, out destinationPathLp, pathFormat);

         UpdateDestinationPath(destinationPath, destinationPathLp);

         return null != destinationPathLp ? new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath) : null;
      }
      

      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, <see cref="MoveOptions"/> can be specified,
      /// and the possibility of notifying the application of its progress through a callback function.
      /// </summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>Use this method to allow or prevent overwriting of an existing file.</para>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the directory has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         // Reject DelayUntilReboot.

         if ((moveOptions & MoveOptions.DelayUntilReboot) != 0)

            throw new ArgumentException("The DelayUntilReboot flag is invalid for this method.", "moveOptions");


         string destinationPathLp;

         var cmr = CopyToMoveToCore(destinationPath, null, moveOptions, false, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath);

         UpdateDestinationPath(destinationPath, destinationPathLp);

         return cmr;
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, <see cref="MoveOptions"/> can be specified.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>Use this method to allow or prevent overwriting of an existing file.</para>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the directory has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         // Reject DelayUntilReboot.

         if ((moveOptions & MoveOptions.DelayUntilReboot) != 0)

            throw new ArgumentException("The DelayUntilReboot flag is invalid for this method.", "moveOptions");


         string destinationPathLp;

         var cmr = CopyToMoveToCore(destinationPath, null, moveOptions, false, progressHandler, userProgressData, out destinationPathLp, pathFormat);

         UpdateDestinationPath(destinationPath, destinationPathLp);

         return cmr;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File.SetAttributesTransacted.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>[AlphaFS] Sets the specified <see cref="FileAttributes"/> of the file on the specified path.</summary>
      /// <remarks>
      ///   Certain file attributes, such as <see cref="FileAttributes.Hidden"/> and <see cref="FileAttributes.ReadOnly"/>, can be combined.
      ///   Other attributes, such as <see cref="FileAttributes.Normal"/>, must be used alone.
      /// </remarks>
      /// <remarks>
      ///   It is not possible to change the <see cref="FileAttributes.Compressed"/> status of a File object using this method.
      /// </remarks>
      /// <exception cref="ArgumentException">path is empty, contains only white spaces, contains invalid characters, or the file attribute is invalid.</exception>
      /// <exception cref="DirectoryNotFoundException">The specified path is invalid, (for example, it is on an unmapped drive).</exception>
      /// <exception cref="FileNotFoundException">The file cannot be found.</exception>
      /// <exception cref="NotSupportedException">path is in an invalid format.</exception>
      /// <exception cref="UnauthorizedAccessException">path specified a file that is read-only. -or- This operation is not supported on the current platform. -or- path specified a directory. -or- The caller does not have the required permission.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The path to the file.</param>
      /// <param name="fileAttributes">A bitwise combination of the enumeration values.</param>      
      [SecurityCritical]
      public static void SetAttributesTransacted(KernelTransaction transaction, string path, FileAttributes fileAttributes)
      {
         SetAttributesCore(transaction, false, path, fileAttributes, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Sets the specified <see cref="FileAttributes"/> of the file on the specified path.</summary>
      /// <remarks>
      ///   Certain file attributes, such as <see cref="FileAttributes.Hidden"/> and <see cref="FileAttributes.ReadOnly"/>, can be combined.
      ///   Other attributes, such as <see cref="FileAttributes.Normal"/>, must be used alone.
      /// </remarks>
      /// <remarks>
      ///   It is not possible to change the <see cref="FileAttributes.Compressed"/> status of a File object using this method.
      /// </remarks>
      /// <exception cref="ArgumentException">path is empty, contains only white spaces, contains invalid characters, or the file attribute is invalid.</exception>
      /// <exception cref="DirectoryNotFoundException">The specified path is invalid, (for example, it is on an unmapped drive).</exception>
      /// <exception cref="FileNotFoundException">The file cannot be found.</exception>
      /// <exception cref="NotSupportedException">path is in an invalid format.</exception>
      /// <exception cref="UnauthorizedAccessException">path specified a file that is read-only. -or- This operation is not supported on the current platform. -or- path specified a directory. -or- The caller does not have the required permission.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The path to the file.</param>
      /// <param name="fileAttributes">A bitwise combination of the enumeration values.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>      
      [SecurityCritical]
      public static void SetAttributesTransacted(KernelTransaction transaction, string path, FileAttributes fileAttributes, PathFormat pathFormat)
      {
         SetAttributesCore(transaction, false, path, fileAttributes, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Native Methods/NativeMethods.INetworkConnection.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>The INetworkConnection interface represents a single network connection.</summary>
      [ComImport, Guid("DCB00005-570F-4A9B-8D69-199FDBA5723B")]
      internal interface INetworkConnection
      {
         // Do not change the order of these interface members.


         /// <summary>The GetNetwork method returns the network associated with the connection.</summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         [return: MarshalAs(UnmanagedType.Interface)]
         INetwork GetNetwork();


         /// <summary>The IsConnected property specifies if the associated network connection has network connectivity.</summary>
         /// <returns>If TRUE, this network connection has connectivity; if FALSE, it does not.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         bool IsConnected
         {
            [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            get;
         }


         /// <summary>The IsConnectedToInternet property specifies if the associated network connection has internet connectivity.</summary>
         /// <returns>If TRUE, this network connection has connectivity to the Internet; if FALSE, it does not.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         bool IsConnectedToInternet
         {
            [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            get;
         }


         /// <summary>The GetConnectivity method returns the connectivity state of the network connection.</summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         ConnectivityStates GetConnectivity();


         /// <summary>The GetConnectionId method returns the Connection ID associated with this network connection.</summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         Guid GetConnectionId();


         /// <summary>The GetAdapterId method returns the ID of the network adapter used by this connection. </summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         Guid GetAdapterId();


         /// <summary>The GetDomainType method returns the domain type of the network connection.</summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         DomainType GetDomainType();
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Native Other/DFS_INFO_9.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>Contains the name, status, GUID, time-out, property flags, metadata size, DFS target information, link reparse point security descriptor, and a list of DFS targets for a root or link.</summary>
      /// <remarks>Minimum supported client: Windows Vista with SP1</remarks>
      /// <remarks>Minimum supported server: Windows Server 2008</remarks>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")]
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      internal struct DFS_INFO_9
      {
         /// <summary>The Universal Naming Convention (UNC) path of a DFS root or link.</summary>
         [MarshalAs(UnmanagedType.LPWStr)] public readonly string EntryPath;

         /// <summary>The comment associated with the DFS root or link.</summary>
         [MarshalAs(UnmanagedType.LPWStr)] public readonly string Comment;

         /// <summary>A <see cref="DfsVolumeStates"/> that specifies a set of bit flags that describe the DFS root or link.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly DfsVolumeStates State;

         /// <summary>Specifies the time-out, in seconds, of the DFS root or link.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint Timeout;

         /// <summary>Specifies the GUID of the DFS root or link.</summary>
         public readonly Guid Guid;

         /// <summary>Specifies a set of flags that describe specific properties of a DFS namespace, root, or link.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly DfsPropertyFlags PropertyFlags;

         /// <summary>For domain-based DFS namespaces, this member specifies the size of the corresponding Active Directory data blob, in bytes.
         /// For stand-alone DFS namespaces, this field specifies the size of the metadata stored in the registry,
         /// including the key names and value names, in addition to the specific data items associated with them.
         /// This field is valid for DFS roots only.
         /// </summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint MetadataSize;

         /// <summary>This member is reserved for system use.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint SdLengthReserved;

         /// <summary>Pointer to a SECURITY_DESCRIPTOR structure that specifies a self-relative security descriptor to be associated with the DFS link's reparse point.
         /// This field is valid for DFS links only.
         /// </summary>
         public IntPtr pSecurityDescriptor;
         
         /// <summary>Specifies the number of DFS targets.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint NumberOfStorages;

         /// <summary>An array of <see cref="DFS_STORAGE_INFO_1"/> structures.</summary>
         public readonly IntPtr Storage;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Other/VOLUME_INFO_FLAGS.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      /// <summary>Volume Attributes used by the GetVolumeInfo() function.</summary>
      [Flags]
      internal enum VOLUME_INFO_FLAGS
      {
         /// <summary>The specified volume supports case-sensitive file names.</summary>
         FILE_CASE_SENSITIVE_SEARCH = 1,


         /// <summary>The specified volume supports preserved case of file names when it places a name on disk.</summary>
         FILE_CASE_PRESERVED_NAMES = 2,


         /// <summary>The specified volume supports Unicode in file names as they appear on disk.</summary>
         FILE_UNICODE_ON_DISK = 4,


         /// <summary>The specified volume preserves and enforces access control lists (ACL). For example, the NTFS file system preserves and enforces ACLs, and the FAT file system does not.</summary>
         FILE_PERSISTENT_ACLS = 8,


         /// <summary>The specified volume supports file-based compression.</summary>
         FILE_FILE_COMPRESSION = 16,


         /// <summary>The specified volume supports disk quotas.</summary>
         FILE_VOLUME_QUOTAS = 32,


         /// <summary>The specified volume supports sparse files.</summary>
         FILE_SUPPORTS_SPARSE_FILES = 64,


         /// <summary>The specified volume supports re-parse points.</summary>
         FILE_SUPPORTS_REPARSE_POINTS = 128,


         /// <summary>(does not appear on MSDN)</summary>
         FILE_SUPPORTS_REMOTE_STORAGE = 256,


         /// <summary>The specified volume is a compressed volume, for example, a DoubleSpace volume.</summary>
         FILE_VOLUME_IS_COMPRESSED = 32768,


         /// <summary>The specified volume supports object identifiers.</summary>
         FILE_SUPPORTS_OBJECT_IDS = 65536,


         /// <summary>The specified volume supports the Encrypted File System (EFS). For more information, see File Encryption.</summary>
         FILE_SUPPORTS_ENCRYPTION = 131072,


         /// <summary>The specified volume supports named streams.</summary>
         FILE_NAMED_STREAMS = 262144,


         /// <summary>The specified volume is read-only.</summary>
         FILE_READ_ONLY_VOLUME = 524288,


         /// <summary>The specified volume is read-only.</summary>
         FILE_SEQUENTIAL_WRITE_ONCE = 1048576,


         /// <summary>The specified volume supports transactions.For more information, see About KTM.</summary>
         FILE_SUPPORTS_TRANSACTIONS = 2097152,


         /// <summary>The specified volume supports hard links. For more information, see Hard Links and Junctions.</summary>
         /// <remarks>Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported until Windows Server 2008 R2 and Windows 7.</remarks>
         FILE_SUPPORTS_HARD_LINKS = 4194304,


         /// <summary>The specified volume supports extended attributes. An extended attribute is a piece of application-specific metadata that an application can associate with a file and is not part of the file's data.</summary>
         /// <remarks>Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported until Windows Server 2008 R2 and Windows 7.</remarks>
         FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 8388608,


         /// <summary>The file system supports open by FileID. For more information, see FILE_ID_BOTH_DIR_INFO.</summary>
         /// <remarks>Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported until Windows Server 2008 R2 and Windows 7.</remarks>
         FILE_SUPPORTS_OPEN_BY_FILE_ID = 16777216,


         /// <summary>The specified volume supports update sequence number (USN) journals. For more information, see Change Journal Records.</summary>
         /// <remarks>Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported until Windows Server 2008 R2 and Windows 7.</remarks>
         FILE_SUPPORTS_USN_JOURNAL = 33554432,


         /// <summary>The specified volume is a direct access (DAX) volume.</summary>
         /// <remarks>This flag was introduced in Windows 10, version 1607.</remarks>
         FILE_DAX_VOLUME = 536870912
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Native Methods/NativeMethods.INetworkListManager.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>The INetworkListManager interface provides a set of methods to perform network list management functions.</summary>
      [ComImport, Guid("DCB00000-570F-4A9B-8D69-199FDBA5723B")]
      internal interface INetworkListManager
      {
         // Do not change the order of these interface members.


         /// <summary>Retrieves networks based on the supplied Network IDs.</summary>
         /// <returns>Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values:
         /// E_POINTER: The pointer passed is NULL.
         /// E_UNEXPECTED: The specified GUID is invalid.
         /// </returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         [return: MarshalAs(UnmanagedType.Interface)]
         IEnumerable GetNetworks([In] NetworkConnectivityLevels flags);


         /// <summary>Retrieves a network based on a supplied Network ID.</summary>
         /// <returns>Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values:
         /// E_POINTER: The pointer passed is NULL.
         /// E_UNEXPECTED: The specified GUID is invalid.
         /// </returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         [return: MarshalAs(UnmanagedType.Interface)]
         INetwork GetNetwork([In] Guid gdNetworkId);


         /// <summary>Gets an enumerator that contains a complete list of the network connections that have been made.</summary>
         /// <returns>Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         [return: MarshalAs(UnmanagedType.Interface)]
         IEnumerable GetNetworkConnections();


         /// <summary>Retrieves a network based on a supplied Network Connection ID.</summary>
         /// <returns>Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values:
         /// S_FALSE: The network associated with the specified network connection ID was not found.
         /// E_POINTER: The pointer passed is NULL.
         /// E_UNEXPECTED: The specified GUID is invalid.
         /// </returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         [return: MarshalAs(UnmanagedType.Interface)]
         INetworkConnection GetNetworkConnection([In] Guid gdNetworkConnectionId);


         /// <summary>Specifies if the machine has network connectivity.</summary>
         /// <returns>
         /// If TRUE , the network has at least local connectivity via IPv4 or IPv6 or both. The network may also have Internet connectivity. Thus, the network is connected.
         /// If FALSE, the network does not have local or Internet connectivity. The network is not connected.
         /// </returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         bool IsConnected
         {
            [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            get;
         }


         /// <summary>Specifies if the machine has Internet connectivity.</summary>
         /// <returns>If TRUE, the local machine is connected to the internet; if FALSE, it is not.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         bool IsConnectedToInternet
         {
            [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            get;
         }


         /// <summary>Returns the connectivity state of all the networks on a machine.</summary>
         /// <returns>Returns S_OK if the method succeeds.</returns>
         /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
         [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
         ConnectivityStates GetConnectivity();
      }
   }
}


<|start_filename|>src/AlphaFS/Security/CRC/Crc64.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 *
 * 
 * Copyright (c) <NAME>.  All rights reserved.
 * AlphaFS has written permission from the author to include the CRC code.
 */

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;

namespace Alphaleonis.Win32.Security
{
   /// <summary>Implements an ISO-3309 compliant 64-bit CRC hash algorithm.</summary>
   [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Crc")]
   internal class Crc64 : HashAlgorithm
   {
      private const ulong Iso3309Polynomial = 0xD800000000000000;
      private const ulong DefaultSeed = 0x0;


      private ulong m_hash;
      private readonly ulong m_seed;
      private readonly ulong[] m_table;
      private static ulong[] s_defaultTable;


      /// <summary>Initializes a new instance of <see cref="Crc64"/> </summary>
      public Crc64() : this(Iso3309Polynomial, DefaultSeed)
      {
      }


      /// <summary>Initializes a new instance of <see cref="Crc64"/>.</summary>
      /// <param name="polynomial">The polynomial.</param>
      /// <param name="seed">The seed.</param>
      private Crc64(ulong polynomial, ulong seed)
      {
         m_table = InitializeTable(polynomial);
         m_seed = seed;
         m_hash = seed;
      }


      /// <summary>Initializes an implementation of the <see cref="T:System.Security.Cryptography.HashAlgorithm"/> class.</summary>
      public override void Initialize()
      {
         m_hash = m_seed;
      }


      /// <summary>When overridden in a derived class, routes data written to the object into the hash algorithm for computing the hash.</summary>
      /// <param name="array">The input to compute the hash code for..</param>
      /// <param name="ibStart">The offset into the byte array from which to begin using data.</param>
      /// <param name="cbSize">The number of bytes in the byte array to use as data.</param>
      protected override void HashCore(byte[] array, int ibStart, int cbSize)
      {
         m_hash = CalculateHash(m_hash, m_table, array, ibStart, cbSize);
      }


      /// <summary>Finalizes the hash computation after the last data is processed by the cryptographic stream object.</summary>
      /// <returns>This method finalizes any partial computation and returns the correct hash value for the data stream.</returns>
      protected override byte[] HashFinal()
      {
         var hashBuffer = UInt64ToBigEndianBytes(m_hash);
         HashValue = hashBuffer;
         return hashBuffer;
      }

      /// <summary>Gets the size, in bits, of the computed hash code.</summary>
      /// <value>The size, in bits, of the computed hash code.</value>
      public override int HashSize
      {
         get { return 64; }
      }


      /// <summary>Initializes the table.</summary>
      /// <returns>The table.</returns>
      /// <param name="polynomial">The polynomial.</param>
      private static ulong[] InitializeTable(ulong polynomial)
      {
         if (polynomial == Iso3309Polynomial && s_defaultTable != null)
            return s_defaultTable;

         var createTable = CreateTable(polynomial);

         if (polynomial == Iso3309Polynomial)
            s_defaultTable = createTable;

         return createTable;
      }


      /// <summary>Creates a table.</summary>
      /// <returns>A new array of ulong.</returns>
      /// <param name="polynomial">The polynomial.</param>
      private static ulong[] CreateTable(ulong polynomial)
      {
         var createTable = new ulong[256];

         for (var i = 0; i < 256; ++i)
         {
            var entry = (ulong)i;

            for (var j = 0; j < 8; ++j)
               entry = (entry & 1) == 1 ? (entry >> 1) ^ polynomial : entry >> 1;

            createTable[i] = entry;
         }

         return createTable;
      }


      /// <summary>Calculates the hash.</summary>
      /// <returns>The calculated hash.</returns>
      /// <param name="seed">The seed.</param>
      /// <param name="table">The table.</param>
      /// <param name="buffer">The buffer.</param>
      /// <param name="start">The start.</param>
      /// <param name="size">The size.</param>
      private static ulong CalculateHash(ulong seed, ulong[] table, IList<byte> buffer, int start, int size)
      {
         var hash = seed;

         for (var i = start; i < start + size; i++)
            unchecked
            {
               hash = (hash >> 8) ^ table[(buffer[i] ^ hash) & 0xff];
            }

         return hash;
      }


      /// <summary>Int 64 to big endian bytes.</summary>
      /// <returns>A byte[].</returns>
      /// <param name="value">The value.</param>
      private static byte[] UInt64ToBigEndianBytes(ulong value)
      {
         var result = BitConverter.GetBytes(value);

         if (BitConverter.IsLittleEndian)
            Array.Reverse(result);

         return result;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.WriteAppendAllLinesCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Security;
using System.Security.AccessControl;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Creates/appends a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The lines to write to the file.</param>
      /// <param name="encoding">The character <see cref="Encoding"/> to use.</param>
      /// <param name="isAppend"><c>true</c> for file Append, <c>false</c> for file Write.</param>
      /// <param name="addNewLine"><c>true</c> to add a line terminator, <c>false</c> to ommit the line terminator.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Disposing is controlled.")]
      [SecurityCritical]
      internal static void WriteAppendAllLinesCore(KernelTransaction transaction, string path, IEnumerable<string> contents, Encoding encoding, bool isAppend, bool addNewLine, PathFormat pathFormat)
      {
         if (null == contents)
            throw new ArgumentNullException("contents");

         if (null == encoding)
            throw new ArgumentNullException("encoding");


         using (var stream = OpenCore(transaction, path, isAppend ? FileMode.OpenOrCreate : FileMode.Create, FileSystemRights.AppendData, FileShare.ReadWrite, ExtendedFileAttributes.Normal, null, null, pathFormat))
         {
            if (isAppend)
               stream.Seek(0, SeekOrigin.End);

            using (var writer = new StreamWriter(stream, encoding))
            {
               if (addNewLine)
                  foreach (var line in contents)
                     writer.WriteLine(line);

               else
                  foreach (var line in contents)
                     writer.Write(line);
            }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path.Constants.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>[AlphaFS] Characters to trim from the SearchPattern.</summary>
      internal static readonly char[] TrimEndChars = {(char) 0x9, (char) 0xA, (char) 0xB, (char) 0xC, (char) 0xD, (char) 0x20, (char) 0x85, (char) 0xA0};

      /// <summary>AltDirectorySeparatorChar = '/' Provides a platform-specific alternate character used to separate directory levels in a path string that reflects a hierarchical file system organization.</summary>
      public static readonly char AltDirectorySeparatorChar = System.IO.Path.AltDirectorySeparatorChar;

      /// <summary>[AlphaFS] AltDirectorySeparatorChar = "/" Provides a platform-specific alternate string used to separate directory levels in a path string that reflects a hierarchical file system organization.</summary>
      public static readonly string AltDirectorySeparator = AltDirectorySeparatorChar.ToString(CultureInfo.InvariantCulture);


      /// <summary>DirectorySeparatorChar = '\' Provides a platform-specific character used to separate directory levels in a path string that reflects a hierarchical file system organization.</summary>
      public static readonly char DirectorySeparatorChar = System.IO.Path.DirectorySeparatorChar;

      /// <summary>[AlphaFS] DirectorySeparator = "\" Provides a platform-specific string used to separate directory levels in a path string that reflects a hierarchical file system organization.</summary>
      public static readonly string DirectorySeparator = DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture);


      /// <summary>[AlphaFS] NetworkDriveSeparator = '$' Provides a platform-specific network drive separator character.</summary>
      public const char NetworkDriveSeparatorChar = '$';

      /// <summary>[AlphaFS] NetworkDriveSeparator = "$" Provides a platform-specific network drive separator string.</summary>
      public static readonly string NetworkDriveSeparator = NetworkDriveSeparatorChar.ToString(CultureInfo.InvariantCulture);


      /// <summary>PathSeparator = ';' A platform-specific separator character used to separate path strings in environment variables.</summary>
      public static readonly char PathSeparator = System.IO.Path.PathSeparator;


      /// <summary>VolumeSeparatorChar = ':' Provides a platform-specific Volume Separator character.</summary>
      public static readonly char VolumeSeparatorChar = System.IO.Path.VolumeSeparatorChar;

      /// <summary>[AlphaFS] VolumeSeparator = ":" Provides a platform-specific Volume Separator string.</summary>
      public static readonly string VolumeSeparator = VolumeSeparatorChar.ToString(CultureInfo.InvariantCulture);


      /// <summary>[AlphaFS] StreamSeparator = ':' Provides a platform-specific Stream-name character.</summary>
      public const char StreamSeparatorChar = ':';

      /// <summary>[AlphaFS] StreamSeparator = ':' Provides a platform-specific Stream-name string.</summary>
      public static readonly string StreamSeparator = StreamSeparatorChar.ToString(CultureInfo.InvariantCulture);


      /// <summary>[AlphaFS] StreamDataLabel = ':$DATA' Provides a platform-specific Stream :$DATA label.</summary>
      public static readonly string StreamDataLabel = StreamSeparator + "$DATA";

      /// <summary>[AlphaFS] StringTerminatorChar = '\0' String Terminator Suffix.</summary>
      public const char StringTerminatorChar = '\0';
      
      
      /// <summary>[AlphaFS] CurrentDirectoryPrefix = '.' Provides a current directory character.</summary>
      public const char CurrentDirectoryPrefixChar = '.';

      /// <summary>[AlphaFS] CurrentDirectoryPrefix = "." Provides a current directory string.</summary>
      public static readonly string CurrentDirectoryPrefix = CurrentDirectoryPrefixChar.ToString(CultureInfo.InvariantCulture);
      
      /// <summary>[AlphaFS] ExtensionSeparatorChar = '.' Provides an Extension Separator character.</summary>
      public const char ExtensionSeparatorChar = '.';

      /// <summary>[AlphaFS] ParentDirectoryPrefix = ".." Provides a parent directory string.</summary>
      public const string ParentDirectoryPrefix = "..";
      
      /// <summary>[AlphaFS] WildcardStarMatchAll = '*' Provides a match-all-items character.</summary>
      public const char WildcardStarMatchAllChar = '*';
      
      /// <summary>[AlphaFS] WildcardStarMatchAll = "*" Provides a match-all-items string.</summary>
      public static readonly string WildcardStarMatchAll = WildcardStarMatchAllChar.ToString(CultureInfo.InvariantCulture);
      
      /// <summary>[AlphaFS] WildcardQuestion = '?' Provides a replace-item string.</summary>
      public const char WildcardQuestionChar = '?';

      /// <summary>[AlphaFS] WildcardQuestion = "?" Provides a replace-item string.</summary>
      public static readonly string WildcardQuestion = WildcardQuestionChar.ToString(CultureInfo.InvariantCulture);


      /// <summary>[AlphaFS] Win32 File Namespace. The "\\?\" prefix to a path string tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system.</summary>
      public static readonly string LongPathPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{0}{1}{0}", DirectorySeparatorChar, WildcardQuestion);

      /// <summary>[AlphaFS] Win32 Device Namespace. The "\\.\"prefix is how to access physical disks and volumes, without going through the file system, if the API supports this type of access.</summary>
      public static readonly string LogicalDrivePrefix = string.Format(CultureInfo.InvariantCulture, "{0}{0}.{0}", DirectorySeparatorChar);

      /// <summary>[AlphaFS] PhysicalDrivePrefix = "\\.\PhysicalDrive" Provides standard physical drive prefix.</summary>
      public static readonly string PhysicalDrivePrefix = string.Format(CultureInfo.InvariantCulture, "{0}PhysicalDrive", LogicalDrivePrefix);


      /// <summary>[AlphaFS] GlobalRootPrefix = "\\?\GlobalRoot\" Provides standard Windows Volume prefix.</summary>
      public static readonly string GlobalRootPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", LongPathPrefix, "GlobalRoot", DirectorySeparatorChar);

      /// <summary>[AlphaFS] GlobalRootDevicePrefix = "\\?\GlobalRoot\Device\" Provides standard Windows Volume prefix.</summary>
      public static readonly string GlobalRootDevicePrefix = string.Format(CultureInfo.InvariantCulture, "{0}{2}{1}{3}{1}", LongPathPrefix, DirectorySeparatorChar, "GlobalRoot", "Device");

      /// <summary>[AlphaFS] NonInterpretedPathPrefix = "\??\" Provides a non-interpreted path prefix.</summary>
      public static readonly string NonInterpretedPathPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{0}", DirectorySeparatorChar, WildcardQuestion);

      /// <summary>[AlphaFS] VolumePrefix = "\\?\Volume" Provides standard Windows Volume prefix.</summary>
      public static readonly string VolumePrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}", LongPathPrefix, "Volume");

      /// <summary>[AlphaFS] DevicePrefix = "\Device\" Provides standard Windows Device prefix.</summary>
      public static readonly string DevicePrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{0}", DirectorySeparatorChar, "Device");

      /// <summary>[AlphaFS] DosDeviceLanmanPrefix = "\Device\LanmanRedirector\" Provides a MS-Dos Lanman Redirector Path UNC prefix to a network share.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lanman")]
      [Obsolete("Unused")]
      public static readonly string DosDeviceLanmanPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", DevicePrefix, "LanmanRedirector", DirectorySeparatorChar);

      /// <summary>[AlphaFS] DosDeviceMupPrefix = "\Device\Mup\" Provides a MS-Dos Mup Redirector Path UNC prefix to a network share.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mup")]
      [Obsolete("Unused")]
      public static readonly string DosDeviceMupPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", DevicePrefix, "Mup", DirectorySeparatorChar);


      /// <summary>[AlphaFS] UncPrefix = "\\" Provides standard Windows Path UNC prefix.</summary>
      public static readonly string UncPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{0}", DirectorySeparatorChar);

      /// <summary>[AlphaFS] DosDeviceUncPrefix = "\??\UNC\" Provides a SUBST.EXE Path UNC prefix to a network share.</summary>
      public static readonly string DosDeviceUncPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", NonInterpretedPathPrefix, "UNC", DirectorySeparatorChar);

      /// <summary>[AlphaFS] LongPathUncPrefix = "\\?\UNC\" Provides standard Windows Long Path UNC prefix.</summary>
      public static readonly string LongPathUncPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", LongPathPrefix, "UNC", DirectorySeparatorChar);
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteJunctionCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Globalization;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Deletes an NTFS directory junction.</summary>
      /// <remarks>Only the directory junction is removed, not the target.</remarks>
      /// <returns>A <see cref="DirectoryInfo"/> instance referencing the junction point.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotAReparsePointException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="fsEntryInfo">A FileSystemEntryInfo instance. Use either <paramref name="fsEntryInfo"/> or <paramref name="junctionPath"/>, not both.</param>
      /// <param name="junctionPath">The path of the junction point to remove.</param>
      /// <param name="removeDirectory">When <c>true</c>, also removes the directory and all its contents.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void DeleteJunctionCore(KernelTransaction transaction, FileSystemEntryInfo fsEntryInfo, string junctionPath, bool removeDirectory, PathFormat pathFormat)
      {
         if (null == fsEntryInfo)
         {
            if (pathFormat != PathFormat.LongFullPath)
            {
               Path.CheckSupportedPathFormat(junctionPath, true, true);

               junctionPath = Path.GetExtendedLengthPathCore(transaction, junctionPath, pathFormat, GetFullPathOptions.CheckInvalidPathChars | GetFullPathOptions.RemoveTrailingDirectorySeparator);

               pathFormat = PathFormat.LongFullPath;
            }


            fsEntryInfo = File.GetFileSystemEntryInfoCore(transaction, true, junctionPath, false, pathFormat);

            if (!fsEntryInfo.IsMountPoint)
               throw new NotAReparsePointException(string.Format(CultureInfo.InvariantCulture, Resources.Directory_Is_Not_A_MountPoint, fsEntryInfo.LongFullPath), (int) Win32Errors.ERROR_NOT_A_REPARSE_POINT);
         }
         

         pathFormat = PathFormat.LongFullPath;


         // Remove the directory junction.

         using (var safeHandle = OpenDirectoryJunction(transaction, fsEntryInfo.LongFullPath, pathFormat))

            Device.DeleteDirectoryJunction(safeHandle);


         // Optionally the folder itself, which should and must be empty.

         if (removeDirectory)

            DeleteDirectoryCore(transaction, fsEntryInfo, null, false, false, true, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Win32Errors.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

namespace Alphaleonis.Win32
{
   internal static class Win32Errors
   {
      /// <summary>Use this to translate error codes into HRESULTs like 0x80070006 for ERROR_INVALID_HANDLE.</summary>
      public static int GetHrFromWin32Error(uint errorCode)
      {
         return (int) unchecked((int) 0x80070000 | errorCode);
      }

      // System Error Codes.
      // http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381%28v=vs.85%29.aspx

      // Win32 Error Codes.
      // https://infosys.beckhoff.com/content/1033/tcdiagnostics/html/tcdiagnostics_win32_errorcodes.htm


      public const uint ERROR_INVALID_FILE_SIZE = 0xFFFFFFFF;

      /// <summary>(0) The operation completed successfully.</summary>
      public const uint ERROR_SUCCESS = 0;

      /// <summary>(0) The operation completed successfully.</summary>
      public const uint NO_ERROR = 0;

      /// <summary>(1) Incorrect function.</summary>
      public const uint ERROR_INVALID_FUNCTION = 1;

      /// <summary>(2) The system cannot find the file specified.</summary>
      public const uint ERROR_FILE_NOT_FOUND = 2;

      /// <summary>(3) The system cannot find the path specified.</summary>
      public const uint ERROR_PATH_NOT_FOUND = 3;
      //public const uint ERROR_TOO_MANY_OPEN_FILES = 4;

      /// <summary>(5) Access is denied.</summary>
      public const uint ERROR_ACCESS_DENIED = 5;

      //public const uint ERROR_INVALID_HANDLE = 6;
      //public const uint ERROR_ARENA_TRASHED = 7;
      //public const uint ERROR_NOT_ENOUGH_MEMORY = 8;   
      //public const uint ERROR_INVALID_BLOCK = 9;
      //public const uint ERROR_BAD_ENVIRONMENT = 10;
      //public const uint ERROR_BAD_FORMAT = 11;
      //public const uint ERROR_INVALID_ACCESS = 12;

      /// <summary>(13) The data is invalid.</summary>
      public const uint ERROR_INVALID_DATA = 13;

      //public const uint ERROR_OUTOFMEMORY = 14;

      /// <summary>(15) The system cannot find the drive specified.</summary>
      public const uint ERROR_INVALID_DRIVE = 15;

      //public const uint ERROR_CURRENT_DIRECTORY = 16;

      /// <summary>(17) The system cannot move the file to a different disk drive.</summary>
      public const uint ERROR_NOT_SAME_DEVICE = 17;

      /// <summary>(18) There are no more files.</summary>
      public const uint ERROR_NO_MORE_FILES = 18;
      //public const uint ERROR_WRITE_PROTECT = 19;
      //public const uint ERROR_BAD_UNIT = 20;

      /// <summary>(21) The device is not ready.</summary>
      public const uint ERROR_NOT_READY = 21;

      //public const uint ERROR_BAD_COMMAND = 22;
      //public const uint ERROR_CRC = 23;
      //public const uint ERROR_BAD_LENGTH = 24;

      /// <summary>(25) The drive cannot locate a specific area or track on the disk.</summary>
      public const uint ERROR_SEEK = 25;

      //public const uint ERROR_NOT_DOS_DISK = 26;
      //public const uint ERROR_SECTOR_NOT_FOUND = 27;
      //public const uint ERROR_OUT_OF_PAPER = 28;
      //public const uint ERROR_WRITE_FAULT = 29;
      //public const uint ERROR_READ_FAULT = 30;
      //public const uint ERROR_GEN_FAILURE = 31;

      /// <summary>(32) The process cannot access the file because it is being used by another process.</summary>
      public const uint ERROR_SHARING_VIOLATION = 32;

      /// <summary>(33) The process cannot access the file because another process has locked a portion of the file.</summary>
      public const uint ERROR_LOCK_VIOLATION = 33;

      //public const uint ERROR_WRONG_DISK = 34;
      //public const uint ERROR_SHARING_BUFFER_EXCEEDED = 36;

      /// <summary>(38) Reached the end of the file.</summary>
      public const uint ERROR_HANDLE_EOF = 38;

      //public const uint ERROR_HANDLE_DISK_FULL = 39;
      public const uint ERROR_NOT_SUPPORTED = 50;
      //public const uint ERROR_REM_NOT_LIST = 51;
      //public const uint ERROR_DUP_NAME = 52;

      /// <summary>(53) The network path was not found.</summary>
      public const uint ERROR_BAD_NETPATH = 53;

      //public const uint ERROR_NETWORK_BUSY = 54;
      //public const uint ERROR_DEV_NOT_EXIST = 55;   
      //public const uint ERROR_TOO_MANY_CMDS = 56;
      //public const uint ERROR_ADAP_HDW_ERR = 57;
      //public const uint ERROR_BAD_NET_RESP = 58;
      //public const uint ERROR_UNEXP_NET_ERR = 59;
      //public const uint ERROR_BAD_REM_ADAP = 60;
      //public const uint ERROR_PRINTQ_FULL = 61;
      //public const uint ERROR_NO_SPOOL_SPACE = 62;
      //public const uint ERROR_PRINT_CANCELLED = 63;
      //public const uint ERROR_NETNAME_DELETED = 64;

      /// <summary>(65) Network access is denied.</summary>
      public const uint ERROR_NETWORK_ACCESS_DENIED = 65;

      //public const uint ERROR_BAD_DEV_TYPE = 66;

      /// <summary>(67) The network name cannot be found.</summary>
      public const uint ERROR_BAD_NET_NAME = 67;

      //public const uint ERROR_TOO_MANY_NAMES = 68;
      //public const uint ERROR_TOO_MANY_SESS = 69;
      //public const uint ERROR_SHARING_PAUSED = 70;
      //public const uint ERROR_REQ_NOT_ACCEP = 71;
      //public const uint ERROR_REDIR_PAUSED = 72;

      /// <summary>(80) The file exists.</summary>
      public const uint ERROR_FILE_EXISTS = 80;

      //public const uint ERROR_CANNOT_MAKE = 82;
      //public const uint ERROR_FAIL_I24 = 83;
      //public const uint ERROR_OUT_OF_STRUCTURES = 84;
      //public const uint ERROR_ALREADY_ASSIGNED = 85;
      //public const uint ERROR_INVALID_PASSWORD = 86;

      /// <summary>(87) The parameter is incorrect.</summary>
      public const uint ERROR_INVALID_PARAMETER = 87;

      //public const uint ERROR_NET_WRITE_FAULT = 88;
      //public const uint ERROR_NO_PROC_SLOTS = 89;
      //public const uint ERROR_TOO_MANY_SEMAPHORES = 100;
      //public const uint ERROR_EXCL_SEM_ALREADY_OWNED = 101;
      //public const uint ERROR_SEM_IS_SET = 102;
      //public const uint ERROR_TOO_MANY_SEM_REQUESTS = 103;
      //public const uint ERROR_INVALID_AT_INTERRUPT_TIME = 104;
      //public const uint ERROR_SEM_OWNER_DIED = 105;
      //public const uint ERROR_SEM_USER_LIMIT = 106;
      //public const uint ERROR_DISK_CHANGE = 107;
      //public const uint ERROR_DRIVE_LOCKED = 108;
      //public const uint ERROR_BROKEN_PIPE = 109;
      //public const uint ERROR_OPEN_FAILED = 110;
      //public const uint ERROR_BUFFER_OVERFLOW = 111;
      //public const uint ERROR_DISK_FULL = 112;
      //public const uint ERROR_NO_MORE_SEARCH_HANDLES = 113;
      //public const uint ERROR_INVALID_TARGET_HANDLE = 114;
      //public const uint ERROR_INVALID_CATEGORY = 117;
      //public const uint ERROR_INVALID_VERIFY_SWITCH = 118;
      //public const uint ERROR_BAD_DRIVER_LEVEL = 119;
      //public const uint ERROR_CALL_NOT_IMPLEMENTED = 120;
      //public const uint ERROR_SEM_TIMEOUT = 121;

      /// <summary>(122) The data area passed to a system call is too small.</summary>
      public const uint ERROR_INSUFFICIENT_BUFFER = 122;

      /// <summary>(123) The filename, directory name, or volume label syntax is incorrect.</summary>
      public const uint ERROR_INVALID_NAME = 123;

      //public const uint ERROR_INVALID_LEVEL = 124;
      //public const uint ERROR_NO_VOLUME_LABEL = 125;
      //public const uint ERROR_INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF;
      //public const uint ERROR_MOD_NOT_FOUND = 126;
      //public const uint ERROR_PROC_NOT_FOUND = 127;
      //public const uint ERROR_WAIT_NO_CHILDREN = 128;
      //public const uint ERROR_CHILD_NOT_COMPLETE = 129;
      //public const uint ERROR_DIRECT_ACCESS_HANDLE = 130;

      /// <summary>(131) An attempt was made to move the file pointer before the beginning of the file.</summary>
      public const uint ERROR_NEGATIVE_SEEK = 131;

      //public const uint ERROR_SEEK_ON_DEVICE = 132;
      //public const uint ERROR_IS_JOIN_TARGET = 133;
      //public const uint ERROR_IS_JOINED = 134;
      //public const uint ERROR_IS_SUBSTED = 135;
      //public const uint ERROR_NOT_JOINED = 136;
      //public const uint ERROR_NOT_SUBSTED = 137;
      //public const uint ERROR_JOIN_TO_JOIN = 138;
      //public const uint ERROR_SUBST_TO_SUBST = 139;
      //public const uint ERROR_JOIN_TO_SUBST = 140;
      //public const uint ERROR_SUBST_TO_JOIN = 141;
      //public const uint ERROR_BUSY_DRIVE = 142;

      /// <summary>(143) The system cannot join or substitute a drive to or for a directory on the same drive.</summary>
      public const uint ERROR_SAME_DRIVE = 143;

      //public const uint ERROR_DIR_NOT_ROOT = 144;

      /// <summary>(145) The directory is not empty.</summary>
      public const uint ERROR_DIR_NOT_EMPTY = 145;

      //public const uint ERROR_IS_SUBST_PATH = 146;
      //public const uint ERROR_IS_JOIN_PATH = 147;
      //public const uint ERROR_PATH_BUSY = 148;
      //public const uint ERROR_IS_SUBST_TARGET = 149;
      //public const uint ERROR_SYSTEM_TRACE = 150;
      //public const uint ERROR_INVALID_EVENT_COUNT = 151;
      //public const uint ERROR_TOO_MANY_MUXWAITERS = 152;
      //public const uint ERROR_INVALID_LIST_FORMAT = 153;
      //public const uint ERROR_LABEL_TOO_LONG = 154;
      //public const uint ERROR_TOO_MANY_TCBS = 155;
      //public const uint ERROR_SIGNAL_REFUSED = 156;
      //public const uint ERROR_DISCARDED = 157;

      //// <summary>(158) The segment is already unlocked.</summary>
      //public const uint ERROR_NOT_LOCKED = 158;

      //public const uint ERROR_BAD_THREADID_ADDR = 159;
      //public const uint ERROR_BAD_ARGUMENTS = 160;
      //public const uint ERROR_BAD_PATHNAME = 161;
      //public const uint ERROR_SIGNAL_PENDING = 162;
      //public const uint ERROR_MAX_THRDS_REACHED = 164;
      //public const uint ERROR_LOCK_FAILED = 167;
      //public const uint ERROR_BUSY = 170;   
      //public const uint ERROR_CANCEL_VIOLATION = 173;
      //public const uint ERROR_ATOMIC_LOCKS_NOT_SUPPORTED = 174;
      //public const uint ERROR_INVALID_SEGMENT_NUMBER = 180;
      //public const uint ERROR_INVALID_ORDINAL = 182;

      /// <summary>(183) Cannot create a file when that file already exists.</summary>
      public const uint ERROR_ALREADY_EXISTS = 183;

      //public const uint ERROR_INVALID_FLAG_NUMBER = 186;
      //public const uint ERROR_SEM_NOT_FOUND = 187;
      //public const uint ERROR_INVALID_STARTING_CODESEG = 188;
      //public const uint ERROR_INVALID_STACKSEG = 189;
      //public const uint ERROR_INVALID_MODULETYPE = 190;
      //public const uint ERROR_INVALID_EXE_SIGNATURE = 191;
      //public const uint ERROR_EXE_MARKED_INVALID = 192;
      //public const uint ERROR_BAD_EXE_FORMAT = 193;
      //public const uint ERROR_ITERATED_DATA_EXCEEDS_64k = 194;
      //public const uint ERROR_INVALID_MINALLOCSIZE = 195;
      //public const uint ERROR_DYNLINK_FROM_INVALID_RING = 196;
      //public const uint ERROR_IOPL_NOT_ENABLED = 197;
      //public const uint ERROR_INVALID_SEGDPL = 198;
      //public const uint ERROR_AUTODATASEG_EXCEEDS_64k = 199;
      //public const uint ERROR_RING2SEG_MUST_BE_MOVABLE = 200;
      //public const uint ERROR_RELOC_CHAIN_XEEDS_SEGLIM = 201;
      //public const uint ERROR_INFLOOP_IN_RELOC_CHAIN = 202;

      //// <summary>(203) The system could not find the environment option that was entered.</summary>
      //public const uint ERROR_ENVVAR_NOT_FOUND = 203;

      //public const uint ERROR_NO_SIGNAL_SENT = 205;
      //public const uint ERROR_FILENAME_EXCED_RANGE = 206;
      //public const uint ERROR_RING2_STACK_IN_USE = 207;
      //public const uint ERROR_META_EXPANSION_TOO_LONG = 208;
      //public const uint ERROR_INVALID_SIGNAL_NUMBER = 209;
      //public const uint ERROR_THREAD_1_INACTIVE = 210;
      //public const uint ERROR_LOCKED = 212;
      //public const uint ERROR_TOO_MANY_MODULES = 214;
      //public const uint ERROR_NESTING_NOT_ALLOWED = 215;
      //public const uint ERROR_EXE_MACHINE_TYPE_MISMATCH = 216;
      //public const uint ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY = 217;
      //public const uint ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY = 218;
      //public const uint ERROR_BAD_PIPE = 230;
      //public const uint ERROR_PIPE_BUSY = 231;
      //public const uint ERROR_NO_DATA = 232;
      //public const uint ERROR_PIPE_NOT_CONNECTED = 233;

      /// <summary>(234) More data is available.</summary>
      public const uint ERROR_MORE_DATA = 234;

      //public const uint ERROR_VC_DISCONNECTED = 240;
      //public const uint ERROR_INVALID_EA_NAME = 254;
      //public const uint ERROR_EA_LIST_INCONSISTENT = 255;
      //public const uint WAIT_TIMEOUT = 258;   

      ///// <summary>(259) No more data is available.</summary>
      public const uint ERROR_NO_MORE_ITEMS = 259;

      //public const uint ERROR_CANNOT_COPY = 266;

      /// <summary>(267) The directory name is invalid.</summary>
      public const uint ERROR_DIRECTORY = 267;

      //public const uint ERROR_EAS_DIDNT_FIT = 275;
      //public const uint ERROR_EA_FILE_CORRUPT = 276;
      //public const uint ERROR_EA_TABLE_FULL = 277;
      //public const uint ERROR_INVALID_EA_HANDLE = 278;
      //public const uint ERROR_EAS_NOT_SUPPORTED = 282;
      //public const uint ERROR_NOT_OWNER = 288;
      //public const uint ERROR_TOO_MANY_POSTS = 298;
      //public const uint ERROR_PARTIAL_COPY = 299;
      //public const uint ERROR_OPLOCK_NOT_GRANTED = 300;
      //public const uint ERROR_INVALID_OPLOCK_PROTOCOL = 301;
      //public const uint ERROR_DISK_TOO_FRAGMENTED = 302;
      //public const uint ERROR_DELETE_PENDING = 303;
      //public const uint ERROR_MR_MID_NOT_FOUND = 317;
      //public const uint ERROR_SCOPE_NOT_FOUND = 318;
      //public const uint ERROR_INVALID_ADDRESS = 487;
      //public const uint ERROR_ARITHMETIC_OVERFLOW = 534;
      //public const uint ERROR_PIPE_CONNECTED = 535;
      //public const uint ERROR_PIPE_LISTENING = 536;
      //public const uint ERROR_EA_ACCESS_DENIED = 994;

      /// <summary>(995) The I/O operation has been aborted because of either a thread exit or an application request.</summary>
      public const uint ERROR_OPERATION_ABORTED = 995;

      //public const uint ERROR_IO_INCOMPLETE = 996;

      //// <summary>(997) Overlapped I/O operation is in progress.</summary>
      //public const uint ERROR_IO_PENDING = 997;

      //public const uint ERROR_NOACCESS = 998;
      //public const uint ERROR_SWAPERROR = 999;
      //public const uint ERROR_STACK_OVERFLOW = 1001;
      //public const uint ERROR_INVALID_MESSAGE = 1002;
      //public const uint ERROR_CAN_NOT_COMPLETE = 1003;
      //public const uint ERROR_INVALID_FLAGS = 1004;
      //public const uint ERROR_UNRECOGNIZED_VOLUME = 1005;
      //public const uint ERROR_FILE_INVALID = 1006;
      //public const uint ERROR_FULLSCREEN_MODE = 1007;
      //public const uint ERROR_NO_TOKEN = 1008;
      //public const uint ERROR_BADDB = 1009;
      //public const uint ERROR_BADKEY = 1010;
      //public const uint ERROR_CANTOPEN = 1011;
      //public const uint ERROR_CANTREAD = 1012;
      //public const uint ERROR_CANTWRITE = 1013;
      //public const uint ERROR_REGISTRY_RECOVERED = 1014;
      //public const uint ERROR_REGISTRY_CORRUPT = 1015;
      //public const uint ERROR_REGISTRY_IO_FAILED = 1016;
      //public const uint ERROR_NOT_REGISTRY_FILE = 1017;
      //public const uint ERROR_KEY_DELETED = 1018;
      //public const uint ERROR_NO_LOG_SPACE = 1019;
      //public const uint ERROR_KEY_HAS_CHILDREN = 1020;
      //public const uint ERROR_CHILD_MUST_BE_VOLATILE = 1021;
      //public const uint ERROR_NOTIFY_ENUM_DIR = 1022;
      //public const uint ERROR_DEPENDENT_SERVICES_RUNNING = 1051;
      //public const uint ERROR_INVALID_SERVICE_CONTROL = 1052;
      //public const uint ERROR_SERVICE_REQUEST_TIMEOUT = 1053;
      //public const uint ERROR_SERVICE_NO_THREAD = 1054;
      //public const uint ERROR_SERVICE_DATABASE_LOCKED = 1055;
      //public const uint ERROR_SERVICE_ALREADY_RUNNING = 1056;
      //public const uint ERROR_INVALID_SERVICE_ACCOUNT = 1057;
      //public const uint ERROR_SERVICE_DISABLED = 1058;
      //public const uint ERROR_CIRCULAR_DEPENDENCY = 1059;
      //public const uint ERROR_SERVICE_DOES_NOT_EXIST = 1060;
      //public const uint ERROR_SERVICE_CANNOT_ACCEPT_CTRL = 1061;
      //public const uint ERROR_SERVICE_NOT_ACTIVE = 1062;
      //public const uint ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063;
      //public const uint ERROR_EXCEPTION_IN_SERVICE = 1064;
      //public const uint ERROR_DATABASE_DOES_NOT_EXIST = 1065;
      //public const uint ERROR_SERVICE_SPECIFIC_ERROR = 1066;
      //public const uint ERROR_PROCESS_ABORTED = 1067;
      //public const uint ERROR_SERVICE_DEPENDENCY_FAIL = 1068;
      //public const uint ERROR_SERVICE_LOGON_FAILED = 1069;
      //public const uint ERROR_SERVICE_START_HANG = 1070;
      //public const uint ERROR_INVALID_SERVICE_LOCK = 1071;
      //public const uint ERROR_SERVICE_MARKED_FOR_DELETE = 1072;
      //public const uint ERROR_SERVICE_EXISTS = 1073;
      //public const uint ERROR_ALREADY_RUNNING_LKG = 1074;
      //public const uint ERROR_SERVICE_DEPENDENCY_DELETED = 1075;
      //public const uint ERROR_BOOT_ALREADY_ACCEPTED = 1076;
      //public const uint ERROR_SERVICE_NEVER_STARTED = 1077;
      //public const uint ERROR_DUPLICATE_SERVICE_NAME = 1078;
      //public const uint ERROR_DIFFERENT_SERVICE_ACCOUNT = 1079;
      //public const uint ERROR_CANNOT_DETECT_DRIVER_FAILURE = 1080;
      //public const uint ERROR_CANNOT_DETECT_PROCESS_ABORT = 1081;
      //public const uint ERROR_NO_RECOVERY_PROGRAM = 1082;
      //public const uint ERROR_SERVICE_NOT_IN_EXE = 1083;
      //public const uint ERROR_NOT_SAFEBOOT_SERVICE = 1084;
      //public const uint ERROR_END_OF_MEDIA = 1100;
      //public const uint ERROR_FILEMARK_DETECTED = 1101;
      //public const uint ERROR_BEGINNING_OF_MEDIA = 1102;
      //public const uint ERROR_SETMARK_DETECTED = 1103;
      //public const uint ERROR_NO_DATA_DETECTED = 1104;
      //public const uint ERROR_PARTITION_FAILURE = 1105;
      //public const uint ERROR_INVALID_BLOCK_LENGTH = 1106;
      //public const uint ERROR_DEVICE_NOT_PARTITIONED = 1107;
      //public const uint ERROR_UNABLE_TO_LOCK_MEDIA = 1108;
      //public const uint ERROR_UNABLE_TO_UNLOAD_MEDIA = 1109;
      //public const uint ERROR_MEDIA_CHANGED = 1110;
      //public const uint ERROR_BUS_RESET = 1111;
      //public const uint ERROR_NO_MEDIA_IN_DRIVE = 1112;
      //public const uint ERROR_NO_UNICODE_TRANSLATION = 1113;
      //public const uint ERROR_DLL_INIT_FAILED = 1114;
      //public const uint ERROR_SHUTDOWN_IN_PROGRESS = 1115;
      //public const uint ERROR_NO_SHUTDOWN_IN_PROGRESS = 1116;
      //public const uint ERROR_IO_DEVICE = 1117;
      //public const uint ERROR_SERIAL_NO_DEVICE = 1118;
      //public const uint ERROR_IRQ_BUSY = 1119;
      //public const uint ERROR_MORE_WRITES = 1120;
      //public const uint ERROR_COUNTER_TIMEOUT = 1121;
      //public const uint ERROR_FLOPPY_ID_MARK_NOT_FOUND = 1122;
      //public const uint ERROR_FLOPPY_WRONG_CYLINDER = 1123;
      //public const uint ERROR_FLOPPY_UNKNOWN_ERROR = 1124;
      //public const uint ERROR_FLOPPY_BAD_REGISTERS = 1125;
      //public const uint ERROR_DISK_RECALIBRATE_FAILED = 1126;
      //public const uint ERROR_DISK_OPERATION_FAILED = 1127;
      //public const uint ERROR_DISK_RESET_FAILED = 1128;
      //public const uint ERROR_EOM_OVERFLOW = 1129;
      //public const uint ERROR_NOT_ENOUGH_SERVER_MEMORY = 1130;
      //public const uint ERROR_POSSIBLE_DEADLOCK = 1131;
      //public const uint ERROR_MAPPED_ALIGNMENT = 1132;
      //public const uint ERROR_SET_POWER_STATE_VETOED = 1140;
      //public const uint ERROR_SET_POWER_STATE_FAILED = 1141;
      //public const uint ERROR_TOO_MANY_LINKS = 1142;

      /// <summary>(1150) The specified program requires a newer version of Windows.</summary>
      public const uint ERROR_OLD_WIN_VERSION = 1150;

      //public const uint ERROR_APP_WRONG_OS = 1151;
      //public const uint ERROR_SINGLE_INSTANCE_APP = 1152;
      //public const uint ERROR_RMODE_APP = 1153;
      //public const uint ERROR_INVALID_DLL = 1154;
      //public const uint ERROR_NO_ASSOCIATION = 1155;
      //public const uint ERROR_DDE_FAIL = 1156;
      //public const uint ERROR_DLL_NOT_FOUND = 1157;
      //public const uint ERROR_NO_MORE_USER_HANDLES = 1158;
      //public const uint ERROR_MESSAGE_SYNC_ONLY = 1159;
      //public const uint ERROR_SOURCE_ELEMENT_EMPTY = 1160;
      //public const uint ERROR_DESTINATION_ELEMENT_FULL = 1161;
      //public const uint ERROR_ILLEGAL_ELEMENT_ADDRESS = 1162;
      //public const uint ERROR_MAGAZINE_NOT_PRESENT = 1163;
      //public const uint ERROR_DEVICE_REINITIALIZATION_NEEDED = 1164;   
      //public const uint ERROR_DEVICE_REQUIRES_CLEANING = 1165;
      //public const uint ERROR_DEVICE_DOOR_OPEN = 1166;
      //public const uint ERROR_DEVICE_NOT_CONNECTED = 1167;
      //public const uint ERROR_NOT_FOUND = 1168;
      //public const uint ERROR_NO_MATCH = 1169;
      //public const uint ERROR_SET_NOT_FOUND = 1170;
      //public const uint ERROR_POINT_NOT_FOUND = 1171;
      //public const uint ERROR_NO_TRACKING_SERVICE = 1172;
      //public const uint ERROR_NO_VOLUME_ID = 1173;
      //public const uint ERROR_UNABLE_TO_REMOVE_REPLACED = 1175;
      //public const uint ERROR_UNABLE_TO_MOVE_REPLACEMENT = 1176;
      //public const uint ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 = 1177;
      //public const uint ERROR_JOURNAL_DELETE_IN_PROGRESS = 1178;
      //public const uint ERROR_JOURNAL_NOT_ACTIVE = 1179;
      //public const uint ERROR_POTENTIAL_FILE_FOUND = 1180;
      //public const uint ERROR_JOURNAL_ENTRY_DELETED = 1181;

      //// <summary>(1200) The specified device name is invalid.</summary>
      //public const uint ERROR_BAD_DEVICE = 1200;

      //public const uint ERROR_CONNECTION_UNAVAIL = 1201;
      //public const uint ERROR_DEVICE_ALREADY_REMEMBERED = 1202;
      //public const uint ERROR_NO_NET_OR_BAD_PATH = 1203;
      //public const uint ERROR_BAD_PROVIDER = 1204;
      //public const uint ERROR_CANNOT_OPEN_PROFILE = 1205;
      //public const uint ERROR_BAD_PROFILE = 1206;
      //public const uint ERROR_NOT_CONTAINER = 1207;

      //// <summary>(1208) An extended error has occurred.</summary>
      //public const uint ERROR_EXTENDED_ERROR = 1208;

      //public const uint ERROR_INVALID_GROUPNAME = 1209;
      //public const uint ERROR_INVALID_COMPUTERNAME = 1210;
      //public const uint ERROR_INVALID_EVENTNAME = 1211;
      //public const uint ERROR_INVALID_DOMAINNAME = 1212;
      //public const uint ERROR_INVALID_SERVICENAME = 1213;
      //public const uint ERROR_INVALID_NETNAME = 1214;
      //public const uint ERROR_INVALID_SHARENAME = 1215;
      //public const uint ERROR_INVALID_PASSWORDNAME = <PASSWORD>;
      //public const uint ERROR_INVALID_MESSAGENAME = 1217;
      //public const uint ERROR_INVALID_MESSAGEDEST = 1218;
      //public const uint ERROR_SESSION_CREDENTIAL_CONFLICT = 1219;
      //public const uint ERROR_REMOTE_SESSION_LIMIT_EXCEEDED = 1220;
      //public const uint ERROR_DUP_DOMAINNAME = 1221;

      //// <summary>(1222) The network is not present or not started.</summary>
      //public const uint ERROR_NO_NETWORK = 1222;

      //public const uint ERROR_CANCELLED = 1223;
      //public const uint ERROR_USER_MAPPED_FILE = 1224;
      //public const uint ERROR_CONNECTION_REFUSED = 1225;
      //public const uint ERROR_GRACEFUL_DISCONNECT = 1226;
      //public const uint ERROR_ADDRESS_ALREADY_ASSOCIATED = 1227;
      //public const uint ERROR_ADDRESS_NOT_ASSOCIATED = 1228;
      //public const uint ERROR_CONNECTION_INVALID = 1229;
      //public const uint ERROR_CONNECTION_ACTIVE = 1230;
      //public const uint ERROR_NETWORK_UNREACHABLE = 1231;
      //public const uint ERROR_HOST_UNREACHABLE = 1232;
      //public const uint ERROR_PROTOCOL_UNREACHABLE = 1233;
      //public const uint ERROR_PORT_UNREACHABLE = 1234;

      /// <summary>(1235) The request was aborted.</summary>
      public const uint ERROR_REQUEST_ABORTED = 1235;

      //public const uint ERROR_CONNECTION_ABORTED = 1236;
      //public const uint ERROR_RETRY = 1237;
      //public const uint ERROR_CONNECTION_COUNT_LIMIT = 1238;
      //public const uint ERROR_LOGIN_TIME_RESTRICTION = 1239;
      //public const uint ERROR_LOGIN_WKSTA_RESTRICTION = 1240;
      //public const uint ERROR_INCORRECT_ADDRESS = 1241;
      //public const uint ERROR_ALREADY_REGISTERED = 1242;
      //public const uint ERROR_SERVICE_NOT_FOUND = 1243;
      //public const uint ERROR_NOT_AUTHENTICATED = 1244;
      //public const uint ERROR_NOT_LOGGED_ON = 1245;
      //public const uint ERROR_CONTINUE = 1246;   
      //public const uint ERROR_ALREADY_INITIALIZED = 1247;
      //public const uint ERROR_NO_MORE_DEVICES = 1248;   
      //public const uint ERROR_NO_SUCH_SITE = 1249;
      //public const uint ERROR_DOMAIN_CONTROLLER_EXISTS = 1250;
      //public const uint ERROR_ONLY_IF_CONNECTED = 1251;
      //public const uint ERROR_OVERRIDE_NOCHANGES = 1252;
      //public const uint ERROR_BAD_USER_PROFILE = 1253;
      //public const uint ERROR_NOT_SUPPORTED_ON_SBS = 1254;
      //public const uint ERROR_SERVER_SHUTDOWN_IN_PROGRESS = 1255;
      //public const uint ERROR_HOST_DOWN = 1256;
      //public const uint ERROR_NON_ACCOUNT_SID = 1257;
      //public const uint ERROR_NON_DOMAIN_SID = 1258;
      //public const uint ERROR_APPHELP_BLOCK = 1259;
      //public const uint ERROR_ACCESS_DISABLED_BY_POLICY = 1260;
      //public const uint ERROR_REG_NAT_CONSUMPTION = 1261;
      //public const uint ERROR_CSCSHARE_OFFLINE = 1262;
      //public const uint ERROR_PKINIT_FAILURE = 1263;
      //public const uint ERROR_SMARTCARD_SUBSYSTEM_FAILURE = 1264;
      //public const uint ERROR_DOWNGRADE_DETECTED = 1265;
      //public const uint ERROR_MACHINE_LOCKED = 1271;
      //public const uint ERROR_CALLBACK_SUPPLIED_INVALID_DATA = 1273;
      //public const uint ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED = 1274;
      //public const uint ERROR_DRIVER_BLOCKED = 1275;
      //public const uint ERROR_INVALID_IMPORT_OF_NON_DLL = 1276;
      //public const uint ERROR_ACCESS_DISABLED_WEBBLADE = 1277;
      //public const uint ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER = 1278;
      //public const uint ERROR_RECOVERY_FAILURE = 1279;
      //public const uint ERROR_ALREADY_FIBER = 1280;
      //public const uint ERROR_ALREADY_THREAD = 1281;
      //public const uint ERROR_STACK_BUFFER_OVERRUN = 1282;
      //public const uint ERROR_PARAMETER_QUOTA_EXCEEDED = 1283;
      //public const uint ERROR_DEBUGGER_INACTIVE = 1284;
      //public const uint ERROR_DELAY_LOAD_FAILED = 1285;
      //public const uint ERROR_VDM_DISALLOWED = 1286;
      //public const uint ERROR_UNIDENTIFIED_ERROR = 1287;
      //public const uint ERROR_NOT_ALL_ASSIGNED = 1300;
      //public const uint ERROR_SOME_NOT_MAPPED = 1301;
      //public const uint ERROR_NO_QUOTAS_FOR_ACCOUNT = 1302;
      //public const uint ERROR_LOCAL_USER_SESSION_KEY = 1303;
      //public const uint ERROR_NULL_LM_PASSWORD = <PASSWORD>;
      //public const uint ERROR_UNKNOWN_REVISION = 1305;
      //public const uint ERROR_REVISION_MISMATCH = 1306;
      //public const uint ERROR_INVALID_OWNER = 1307;
      //public const uint ERROR_INVALID_PRIMARY_GROUP = 1308;
      //public const uint ERROR_NO_IMPERSONATION_TOKEN = 1309;
      //public const uint ERROR_CANT_DISABLE_MANDATORY = 1310;
      //public const uint ERROR_NO_LOGON_SERVERS = 1311;
      //public const uint ERROR_NO_SUCH_LOGON_SESSION = 1312;
      //public const uint ERROR_NO_SUCH_PRIVILEGE = 1313;
      //public const uint ERROR_PRIVILEGE_NOT_HELD = 1314;
      //public const uint ERROR_INVALID_ACCOUNT_NAME = 1315;
      //public const uint ERROR_USER_EXISTS = 1316;
      //public const uint ERROR_NO_SUCH_USER = 1317;
      //public const uint ERROR_GROUP_EXISTS = 1318;
      //public const uint ERROR_NO_SUCH_GROUP = 1319;
      //public const uint ERROR_MEMBER_IN_GROUP = 1320;
      //public const uint ERROR_MEMBER_NOT_IN_GROUP = 1321;
      //public const uint ERROR_LAST_ADMIN = 1322;
      //public const uint ERROR_WRONG_PASSWORD = <PASSWORD>;
      //public const uint ERROR_ILL_FORMED_PASSWORD = 1324;
      //public const uint ERROR_PASSWORD_RESTRICTION = 1325;
      //public const uint ERROR_LOGON_FAILURE = 1326;
      //public const uint ERROR_ACCOUNT_RESTRICTION = 1327;
      //public const uint ERROR_INVALID_LOGON_HOURS = 1328;
      //public const uint ERROR_INVALID_WORKSTATION = 1329;
      //public const uint ERROR_PASSWORD_EXPIRED = 1330;
      //public const uint ERROR_ACCOUNT_DISABLED = 1331;
      //public const uint ERROR_NONE_MAPPED = 1332;
      //public const uint ERROR_TOO_MANY_LUIDS_REQUESTED = 1333;
      //public const uint ERROR_LUIDS_EXHAUSTED = 1334;
      //public const uint ERROR_INVALID_SUB_AUTHORITY = 1335;
      //public const uint ERROR_INVALID_ACL = 1336;
      //public const uint ERROR_INVALID_SID = 1337;

      /// <summary>(1338) The security descriptor structure is invalid.</summary>
      public const uint ERROR_INVALID_SECURITY_DESCR = 1338;

      //public const uint ERROR_BAD_INHERITANCE_ACL = 1340;
      //public const uint ERROR_SERVER_DISABLED = 1341;
      //public const uint ERROR_SERVER_NOT_DISABLED = 1342;
      //public const uint ERROR_INVALID_ID_AUTHORITY = 1343;
      //public const uint ERROR_ALLOTTED_SPACE_EXCEEDED = 1344;
      //public const uint ERROR_INVALID_GROUP_ATTRIBUTES = 1345;
      //public const uint ERROR_BAD_IMPERSONATION_LEVEL = 1346;
      //public const uint ERROR_CANT_OPEN_ANONYMOUS = 1347;
      //public const uint ERROR_BAD_VALIDATION_CLASS = 1348;
      //public const uint ERROR_BAD_TOKEN_TYPE = 1349;
      //public const uint ERROR_NO_SECURITY_ON_OBJECT = 1350;
      //public const uint ERROR_CANT_ACCESS_DOMAIN_INFO = 1351;
      //public const uint ERROR_INVALID_SERVER_STATE = 1352;
      //public const uint ERROR_INVALID_DOMAIN_STATE = 1353;
      //public const uint ERROR_INVALID_DOMAIN_ROLE = 1354;
      //public const uint ERROR_NO_SUCH_DOMAIN = 1355;
      //public const uint ERROR_DOMAIN_EXISTS = 1356;
      //public const uint ERROR_DOMAIN_LIMIT_EXCEEDED = 1357;
      //public const uint ERROR_INTERNAL_DB_CORRUPTION = 1358;
      //public const uint ERROR_INTERNAL_ERROR = 1359;
      //public const uint ERROR_GENERIC_NOT_MAPPED = 1360;
      //public const uint ERROR_BAD_DESCRIPTOR_FORMAT = 1361;
      //public const uint ERROR_NOT_LOGON_PROCESS = 1362;
      //public const uint ERROR_LOGON_SESSION_EXISTS = 1363;
      //public const uint ERROR_NO_SUCH_PACKAGE = 1364;
      //public const uint ERROR_BAD_LOGON_SESSION_STATE = 1365;
      //public const uint ERROR_LOGON_SESSION_COLLISION = 1366;
      //public const uint ERROR_INVALID_LOGON_TYPE = 1367;
      //public const uint ERROR_CANNOT_IMPERSONATE = 1368;
      //public const uint ERROR_RXACT_INVALID_STATE = 1369;
      //public const uint ERROR_RXACT_COMMIT_FAILURE = 1370;
      //public const uint ERROR_SPECIAL_ACCOUNT = 1371;
      //public const uint ERROR_SPECIAL_GROUP = 1372;
      //public const uint ERROR_SPECIAL_USER = 1373;
      //public const uint ERROR_MEMBERS_PRIMARY_GROUP = 1374;
      //public const uint ERROR_TOKEN_ALREADY_IN_USE = 1375;
      //public const uint ERROR_NO_SUCH_ALIAS = 1376;
      //public const uint ERROR_MEMBER_NOT_IN_ALIAS = 1377;
      //public const uint ERROR_MEMBER_IN_ALIAS = 1378;
      //public const uint ERROR_ALIAS_EXISTS = 1379;
      //public const uint ERROR_LOGON_NOT_GRANTED = 1380;
      //public const uint ERROR_TOO_MANY_SECRETS = 1381;
      //public const uint ERROR_SECRET_TOO_LONG = 1382;
      //public const uint ERROR_INTERNAL_DB_ERROR = 1383;
      //public const uint ERROR_TOO_MANY_CONTEXT_IDS = 1384;
      //public const uint ERROR_LOGON_TYPE_NOT_GRANTED = 1385;
      //public const uint ERROR_NT_CROSS_ENCRYPTION_REQUIRED = 1386;
      //public const uint ERROR_NO_SUCH_MEMBER = 1387;
      //public const uint ERROR_INVALID_MEMBER = 1388;
      //public const uint ERROR_TOO_MANY_SIDS = 1389;
      //public const uint ERROR_LM_CROSS_ENCRYPTION_REQUIRED = 1390;
      //public const uint ERROR_NO_INHERITANCE = 1391;
      //public const uint ERROR_FILE_CORRUPT = 1392;
      //public const uint ERROR_DISK_CORRUPT = 1393;
      //public const uint ERROR_NO_USER_SESSION_KEY = 1394;
      //public const uint ERROR_LICENSE_QUOTA_EXCEEDED = 1395;
      //public const uint ERROR_WRONG_TARGET_NAME = 1396;
      //public const uint ERROR_MUTUAL_AUTH_FAILED = 1397;
      //public const uint ERROR_TIME_SKEW = 1398;
      //public const uint ERROR_CURRENT_DOMAIN_NOT_ALLOWED = 1399;
      //public const uint ERROR_INVALID_WINDOW_HANDLE = 1400;
      //public const uint ERROR_INVALID_MENU_HANDLE = 1401;
      //public const uint ERROR_INVALID_CURSOR_HANDLE = 1402;
      //public const uint ERROR_INVALID_ACCEL_HANDLE = 1403;
      //public const uint ERROR_INVALID_HOOK_HANDLE = 1404;
      //public const uint ERROR_INVALID_DWP_HANDLE = 1405;
      //public const uint ERROR_TLW_WITH_WSCHILD = 1406;
      //public const uint ERROR_CANNOT_FIND_WND_CLASS = 1407;
      //public const uint ERROR_WINDOW_OF_OTHER_THREAD = 1408;
      //public const uint ERROR_HOTKEY_ALREADY_REGISTERED = 1409;
      //public const uint ERROR_CLASS_ALREADY_EXISTS = 1410;
      //public const uint ERROR_CLASS_DOES_NOT_EXIST = 1411;
      //public const uint ERROR_CLASS_HAS_WINDOWS = 1412;
      //public const uint ERROR_INVALID_INDEX = 1413;
      //public const uint ERROR_INVALID_ICON_HANDLE = 1414;
      //public const uint ERROR_PRIVATE_DIALOG_INDEX = 1415;
      //public const uint ERROR_LISTBOX_ID_NOT_FOUND = 1416;
      //public const uint ERROR_NO_WILDCARD_CHARACTERS = 1417;
      //public const uint ERROR_CLIPBOARD_NOT_OPEN = 1418;
      //public const uint ERROR_HOTKEY_NOT_REGISTERED = 1419;
      //public const uint ERROR_WINDOW_NOT_DIALOG = 1420;
      //public const uint ERROR_CONTROL_ID_NOT_FOUND = 1421;
      //public const uint ERROR_INVALID_COMBOBOX_MESSAGE = 1422;
      //public const uint ERROR_WINDOW_NOT_COMBOBOX = 1423;
      //public const uint ERROR_INVALID_EDIT_HEIGHT = 1424;
      //public const uint ERROR_DC_NOT_FOUND = 1425;
      //public const uint ERROR_INVALID_HOOK_FILTER = 1426;
      //public const uint ERROR_INVALID_FILTER_PROC = 1427;
      //public const uint ERROR_HOOK_NEEDS_HMOD = 1428;
      //public const uint ERROR_GLOBAL_ONLY_HOOK = 1429;
      //public const uint ERROR_JOURNAL_HOOK_SET = 1430;
      //public const uint ERROR_HOOK_NOT_INSTALLED = 1431;
      //public const uint ERROR_INVALID_LB_MESSAGE = 1432;
      //public const uint ERROR_SETCOUNT_ON_BAD_LB = 1433;
      //public const uint ERROR_LB_WITHOUT_TABSTOPS = 1434;
      //public const uint ERROR_DESTROY_OBJECT_OF_OTHER_THREAD = 1435;
      //public const uint ERROR_CHILD_WINDOW_MENU = 1436;
      //public const uint ERROR_NO_SYSTEM_MENU = 1437;
      //public const uint ERROR_INVALID_MSGBOX_STYLE = 1438;
      //public const uint ERROR_INVALID_SPI_VALUE = 1439;
      //public const uint ERROR_SCREEN_ALREADY_LOCKED = 1440;
      //public const uint ERROR_HWNDS_HAVE_DIFF_PARENT = 1441;
      //public const uint ERROR_NOT_CHILD_WINDOW = 1442;
      //public const uint ERROR_INVALID_GW_COMMAND = 1443;
      //public const uint ERROR_INVALID_THREAD_ID = 1444;
      //public const uint ERROR_NON_MDICHILD_WINDOW = 1445;
      //public const uint ERROR_POPUP_ALREADY_ACTIVE = 1446;
      //public const uint ERROR_NO_SCROLLBARS = 1447;
      //public const uint ERROR_INVALID_SCROLLBAR_RANGE = 1448;
      //public const uint ERROR_INVALID_SHOWWIN_COMMAND = 1449;
      //public const uint ERROR_NO_SYSTEM_RESOURCES = 1450;
      //public const uint ERROR_NONPAGED_SYSTEM_RESOURCES = 1451;
      //public const uint ERROR_PAGED_SYSTEM_RESOURCES = 1452;
      //public const uint ERROR_WORKING_SET_QUOTA = 1453;
      //public const uint ERROR_PAGEFILE_QUOTA = 1454;
      //public const uint ERROR_COMMITMENT_LIMIT = 1455;
      //public const uint ERROR_MENU_ITEM_NOT_FOUND = 1456;
      //public const uint ERROR_INVALID_KEYBOARD_HANDLE = 1457;
      //public const uint ERROR_HOOK_TYPE_NOT_ALLOWED = 1458;
      //public const uint ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION = 1459;
      //public const uint ERROR_TIMEOUT = 1460;
      //public const uint ERROR_INVALID_MONITOR_HANDLE = 1461;
      //public const uint ERROR_INCORRECT_SIZE = 1462;
      //public const uint ERROR_EVENTLOG_FILE_CORRUPT = 1500;
      //public const uint ERROR_EVENTLOG_CANT_START = 1501;
      //public const uint ERROR_LOG_FILE_FULL = 1502;
      //public const uint ERROR_EVENTLOG_FILE_CHANGED = 1503;
      //public const uint ERROR_INSTALL_SERVICE_FAILURE = 1601;
      //public const uint ERROR_INSTALL_USEREXIT = 1602;
      //public const uint ERROR_INSTALL_FAILURE = 1603;
      //public const uint ERROR_INSTALL_SUSPEND = 1604;
      //public const uint ERROR_UNKNOWN_PRODUCT = 1605;
      //public const uint ERROR_UNKNOWN_FEATURE = 1606;
      //public const uint ERROR_UNKNOWN_COMPONENT = 1607;
      //public const uint ERROR_UNKNOWN_PROPERTY = 1608;
      //public const uint ERROR_INVALID_HANDLE_STATE = 1609;
      //public const uint ERROR_BAD_CONFIGURATION = 1610;
      //public const uint ERROR_INDEX_ABSENT = 1611;
      //public const uint ERROR_INSTALL_SOURCE_ABSENT = 1612;
      //public const uint ERROR_INSTALL_PACKAGE_VERSION = 1613;
      //public const uint ERROR_PRODUCT_UNINSTALLED = 1614;
      //public const uint ERROR_BAD_QUERY_SYNTAX = 1615;
      //public const uint ERROR_INVALID_FIELD = 1616;
      //public const uint ERROR_DEVICE_REMOVED = 1617;
      //public const uint ERROR_INSTALL_ALREADY_RUNNING = 1618;
      //public const uint ERROR_INSTALL_PACKAGE_OPEN_FAILED = 1619;
      //public const uint ERROR_INSTALL_PACKAGE_INVALID = 1620;
      //public const uint ERROR_INSTALL_UI_FAILURE = 1621;
      //public const uint ERROR_INSTALL_LOG_FAILURE = 1622;
      //public const uint ERROR_INSTALL_LANGUAGE_UNSUPPORTED = 1623;
      //public const uint ERROR_INSTALL_TRANSFORM_FAILURE = 1624;
      //public const uint ERROR_INSTALL_PACKAGE_REJECTED = 1625;
      //public const uint ERROR_FUNCTION_NOT_CALLED = 1626;
      //public const uint ERROR_FUNCTION_FAILED = 1627;
      //public const uint ERROR_INVALID_TABLE = 1628;
      //public const uint ERROR_DATATYPE_MISMATCH = 1629;
      //public const uint ERROR_UNSUPPORTED_TYPE = 1630;
      //public const uint ERROR_CREATE_FAILED = 1631;
      //public const uint ERROR_INSTALL_TEMP_UNWRITABLE = 1632;
      //public const uint ERROR_INSTALL_PLATFORM_UNSUPPORTED = 1633;
      //public const uint ERROR_INSTALL_NOTUSED = 1634;
      //public const uint ERROR_PATCH_PACKAGE_OPEN_FAILED = 1635;
      //public const uint ERROR_PATCH_PACKAGE_INVALID = 1636;
      //public const uint ERROR_PATCH_PACKAGE_UNSUPPORTED = 1637;
      //public const uint ERROR_PRODUCT_VERSION = 1638;
      //public const uint ERROR_INVALID_COMMAND_LINE = 1639;
      //public const uint ERROR_INSTALL_REMOTE_DISALLOWED = 1640;

      /// <summary>(1641) The requested operation completed successfully.
      /// <para>The system will be restarted so the changes can take effect.</para>
      /// </summary>
      public const uint ERROR_SUCCESS_REBOOT_INITIATED = 1641;

      //public const uint ERROR_PATCH_TARGET_NOT_FOUND = 1642;
      //public const uint ERROR_PATCH_PACKAGE_REJECTED = 1643;
      //public const uint ERROR_INSTALL_TRANSFORM_REJECTED = 1644;
      //public const uint ERROR_INSTALL_REMOTE_PROHIBITED = 1645;
      //public const uint RPC_S_INVALID_STRING_BINDING = 1700;
      //public const uint RPC_S_WRONG_KIND_OF_BINDING = 1701;
      //public const uint RPC_S_INVALID_BINDING = 1702;
      //public const uint RPC_S_PROTSEQ_NOT_SUPPORTED = 1703;
      //public const uint RPC_S_INVALID_RPC_PROTSEQ = 1704;
      //public const uint RPC_S_INVALID_STRING_UUID = 1705;
      //public const uint RPC_S_INVALID_ENDPOINT_FORMAT = 1706;
      //public const uint RPC_S_INVALID_NET_ADDR = 1707;
      //public const uint RPC_S_NO_ENDPOINT_FOUND = 1708;
      //public const uint RPC_S_INVALID_TIMEOUT = 1709;
      //public const uint RPC_S_OBJECT_NOT_FOUND = 1710;
      //public const uint RPC_S_ALREADY_REGISTERED = 1711;
      //public const uint RPC_S_TYPE_ALREADY_REGISTERED = 1712;
      //public const uint RPC_S_ALREADY_LISTENING = 1713;
      //public const uint RPC_S_NO_PROTSEQS_REGISTERED = 1714;
      //public const uint RPC_S_NOT_LISTENING = 1715;
      //public const uint RPC_S_UNKNOWN_MGR_TYPE = 1716;
      //public const uint RPC_S_UNKNOWN_IF = 1717;
      //public const uint RPC_S_NO_BINDINGS = 1718;
      //public const uint RPC_S_NO_PROTSEQS = 1719;
      //public const uint RPC_S_CANT_CREATE_ENDPOINT = 1720;
      //public const uint RPC_S_OUT_OF_RESOURCES = 1721;
      //public const uint RPC_S_SERVER_UNAVAILABLE = 1722;
      //public const uint RPC_S_SERVER_TOO_BUSY = 1723;
      //public const uint RPC_S_INVALID_NETWORK_OPTIONS = 1724;
      //public const uint RPC_S_NO_CALL_ACTIVE = 1725;
      //public const uint RPC_S_CALL_FAILED = 1726;
      //public const uint RPC_S_CALL_FAILED_DNE = 1727;
      //public const uint RPC_S_PROTOCOL_ERROR = 1728;
      //public const uint RPC_S_UNSUPPORTED_TRANS_SYN = 1730;
      //public const uint RPC_S_UNSUPPORTED_TYPE = 1732;
      //public const uint RPC_S_INVALID_TAG = 1733;
      //public const uint RPC_S_INVALID_BOUND = 1734;
      //public const uint RPC_S_NO_ENTRY_NAME = 1735;
      //public const uint RPC_S_INVALID_NAME_SYNTAX = 1736;
      //public const uint RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737;
      //public const uint RPC_S_UUID_NO_ADDRESS = 1739;
      //public const uint RPC_S_DUPLICATE_ENDPOINT = 1740;
      //public const uint RPC_S_UNKNOWN_AUTHN_TYPE = 1741;
      //public const uint RPC_S_MAX_CALLS_TOO_SMALL = 1742;
      //public const uint RPC_S_STRING_TOO_LONG = 1743;
      //public const uint RPC_S_PROTSEQ_NOT_FOUND = 1744;
      //public const uint RPC_S_PROCNUM_OUT_OF_RANGE = 1745;
      //public const uint RPC_S_BINDING_HAS_NO_AUTH = 1746;
      //public const uint RPC_S_UNKNOWN_AUTHN_SERVICE = 1747;
      //public const uint RPC_S_UNKNOWN_AUTHN_LEVEL = 1748;
      //public const uint RPC_S_INVALID_AUTH_IDENTITY = 1749;
      //public const uint RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750;
      //public const uint EPT_S_INVALID_ENTRY = 1751;
      //public const uint EPT_S_CANT_PERFORM_OP = 1752;
      //public const uint EPT_S_NOT_REGISTERED = 1753;
      //public const uint RPC_S_NOTHING_TO_EXPORT = 1754;
      //public const uint RPC_S_INCOMPLETE_NAME = 1755;
      //public const uint RPC_S_INVALID_VERS_OPTION = 1756;
      //public const uint RPC_S_NO_MORE_MEMBERS = 1757;
      //public const uint RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758;
      //public const uint RPC_S_INTERFACE_NOT_FOUND = 1759;
      //public const uint RPC_S_ENTRY_ALREADY_EXISTS = 1760;
      //public const uint RPC_S_ENTRY_NOT_FOUND = 1761;
      //public const uint RPC_S_NAME_SERVICE_UNAVAILABLE = 1762;
      //public const uint RPC_S_INVALID_NAF_ID = 1763;
      //public const uint RPC_S_CANNOT_SUPPORT = 1764;
      //public const uint RPC_S_NO_CONTEXT_AVAILABLE = 1765;
      //public const uint RPC_S_INTERNAL_ERROR = 1766;
      //public const uint RPC_S_ZERO_DIVIDE = 1767;
      //public const uint RPC_S_ADDRESS_ERROR = 1768;
      //public const uint RPC_S_FP_DIV_ZERO = 1769;
      //public const uint RPC_S_FP_UNDERFLOW = 1770;
      //public const uint RPC_S_FP_OVERFLOW = 1771;
      //public const uint RPC_X_NO_MORE_ENTRIES = 1772;
      //public const uint RPC_X_SS_CHAR_TRANS_OPEN_FAIL = 1773;
      //public const uint RPC_X_SS_CHAR_TRANS_SHORT_FILE = 1774;
      //public const uint RPC_X_SS_IN_NULL_CONTEXT = 1775;
      //public const uint RPC_X_SS_CONTEXT_DAMAGED = 1777;
      //public const uint RPC_X_SS_HANDLES_MISMATCH = 1778;
      //public const uint RPC_X_SS_CANNOT_GET_CALL_HANDLE = 1779;
      //public const uint RPC_X_NULL_REF_POINTER = 1780;
      //public const uint RPC_X_ENUM_VALUE_OUT_OF_RANGE = 1781;
      //public const uint RPC_X_BYTE_COUNT_TOO_SMALL = 1782;

      /// <summary>(1783) The stub received bad data.</summary>
      public const uint RPC_X_BAD_STUB_DATA = 1783;

      //public const uint ERROR_INVALID_USER_BUFFER = 1784;
      //public const uint ERROR_UNRECOGNIZED_MEDIA = 1785;
      //public const uint ERROR_NO_TRUST_LSA_SECRET = 1786;
      //public const uint ERROR_NO_TRUST_SAM_ACCOUNT = 1787;
      //public const uint ERROR_TRUSTED_DOMAIN_FAILURE = 1788;
      //public const uint ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789;
      //public const uint ERROR_TRUST_FAILURE = 1790;
      //public const uint RPC_S_CALL_IN_PROGRESS = 1791;
      //public const uint ERROR_NETLOGON_NOT_STARTED = 1792;
      //public const uint ERROR_ACCOUNT_EXPIRED = 1793;
      //public const uint ERROR_REDIRECTOR_HAS_OPEN_HANDLES = 1794;
      //public const uint ERROR_PRINTER_DRIVER_ALREADY_INSTALLED = 1795;
      //public const uint ERROR_UNKNOWN_PORT = 1796;
      //public const uint ERROR_UNKNOWN_PRINTER_DRIVER = 1797;
      //public const uint ERROR_UNKNOWN_PRINTPROCESSOR = 1798;
      //public const uint ERROR_INVALID_SEPARATOR_FILE = 1799;
      //public const uint ERROR_INVALID_PRIORITY = 1800;
      //public const uint ERROR_INVALID_PRINTER_NAME = 1801;
      //public const uint ERROR_PRINTER_ALREADY_EXISTS = 1802;
      //public const uint ERROR_INVALID_PRINTER_COMMAND = 1803;
      //public const uint ERROR_INVALID_DATATYPE = 1804;
      //public const uint ERROR_INVALID_ENVIRONMENT = 1805;
      //public const uint RPC_S_NO_MORE_BINDINGS = 1806;
      //public const uint ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 1807;
      //public const uint ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT = 1808;
      //public const uint ERROR_NOLOGON_SERVER_TRUST_ACCOUNT = 1809;
      //public const uint ERROR_DOMAIN_TRUST_INCONSISTENT = 1810;
      //public const uint ERROR_SERVER_HAS_OPEN_HANDLES = 1811;
      //public const uint ERROR_RESOURCE_DATA_NOT_FOUND = 1812;
      //public const uint ERROR_RESOURCE_TYPE_NOT_FOUND = 1813;
      //public const uint ERROR_RESOURCE_NAME_NOT_FOUND = 1814;
      //public const uint ERROR_RESOURCE_LANG_NOT_FOUND = 1815;
      //public const uint ERROR_NOT_ENOUGH_QUOTA = 1816;
      //public const uint RPC_S_NO_INTERFACES = 1817;
      //public const uint RPC_S_CALL_CANCELLED = 1818;
      //public const uint RPC_S_BINDING_INCOMPLETE = 1819;
      //public const uint RPC_S_COMM_FAILURE = 1820;
      //public const uint RPC_S_UNSUPPORTED_AUTHN_LEVEL = 1821;
      //public const uint RPC_S_NO_PRINC_NAME = 1822;
      //public const uint RPC_S_NOT_RPC_ERROR = 1823;
      //public const uint RPC_S_UUID_LOCAL_ONLY = 1824;
      //public const uint RPC_S_SEC_PKG_ERROR = 1825;
      //public const uint RPC_S_NOT_CANCELLED = 1826;
      //public const uint RPC_X_INVALID_ES_ACTION = 1827;
      //public const uint RPC_X_WRONG_ES_VERSION = 1828;
      //public const uint RPC_X_WRONG_STUB_VERSION = 1829;
      //public const uint RPC_X_INVALID_PIPE_OBJECT = 1830;
      //public const uint RPC_X_WRONG_PIPE_ORDER = 1831;
      //public const uint RPC_X_WRONG_PIPE_VERSION = 1832;
      //public const uint RPC_S_GROUP_MEMBER_NOT_FOUND = 1898;
      //public const uint EPT_S_CANT_CREATE = 1899;
      //public const uint RPC_S_INVALID_OBJECT = 1900;
      //public const uint ERROR_INVALID_TIME = 1901;
      //public const uint ERROR_INVALID_FORM_NAME = 1902;
      //public const uint ERROR_INVALID_FORM_SIZE = 1903;
      //public const uint ERROR_ALREADY_WAITING = 1904;
      //public const uint ERROR_PRINTER_DELETED = 1905;
      //public const uint ERROR_INVALID_PRINTER_STATE = 1906;
      //public const uint ERROR_PASSWORD_MUST_CHANGE = 1907;
      //public const uint ERROR_DOMAIN_CONTROLLER_NOT_FOUND = 1908;
      //public const uint ERROR_ACCOUNT_LOCKED_OUT = 1909;
      //public const uint OR_INVALID_OXID = 1910;
      //public const uint OR_INVALID_OID = 1911;
      //public const uint OR_INVALID_SET = 1912;
      //public const uint RPC_S_SEND_INCOMPLETE = 1913;
      //public const uint RPC_S_INVALID_ASYNC_HANDLE = 1914;
      //public const uint RPC_S_INVALID_ASYNC_CALL = 1915;
      //public const uint RPC_X_PIPE_CLOSED = 1916;
      //public const uint RPC_X_PIPE_DISCIPLINE_ERROR = 1917;
      //public const uint RPC_X_PIPE_EMPTY = 1918;
      //public const uint ERROR_NO_SITENAME = 1919;
      //public const uint ERROR_CANT_ACCESS_FILE = 1920;
      //public const uint ERROR_CANT_RESOLVE_FILENAME = 1921;
      //public const uint RPC_S_ENTRY_TYPE_MISMATCH = 1922;
      //public const uint RPC_S_NOT_ALL_OBJS_EXPORTED = 1923;
      //public const uint RPC_S_INTERFACE_NOT_EXPORTED = 1924;
      //public const uint RPC_S_PROFILE_NOT_ADDED = 1925;
      //public const uint RPC_S_PRF_ELT_NOT_ADDED = 1926;
      //public const uint RPC_S_PRF_ELT_NOT_REMOVED = 1927;
      //public const uint RPC_S_GRP_ELT_NOT_ADDED = 1928;
      //public const uint RPC_S_GRP_ELT_NOT_REMOVED = 1929;
      //public const uint ERROR_KM_DRIVER_BLOCKED = 1930;
      //public const uint ERROR_CONTEXT_EXPIRED = 1931;
      //public const uint ERROR_PER_USER_TRUST_QUOTA_EXCEEDED = 1932;
      //public const uint ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED = 1933;
      //public const uint ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED = 1934;
      //public const uint ERROR_AUTHENTICATION_FIREWALL_FAILED = 1935;
      //public const uint ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED = 1936;
      //public const uint ERROR_INVALID_PIXEL_FORMAT = 2000;
      //public const uint ERROR_BAD_DRIVER = 2001;
      //public const uint ERROR_INVALID_WINDOW_STYLE = 2002;
      //public const uint ERROR_METAFILE_NOT_SUPPORTED = 2003;
      //public const uint ERROR_TRANSFORM_NOT_SUPPORTED = 2004;
      //public const uint ERROR_CLIPPING_NOT_SUPPORTED = 2005;
      //public const uint ERROR_INVALID_CMM = 2010;
      //public const uint ERROR_INVALID_PROFILE = 2011;
      //public const uint ERROR_TAG_NOT_FOUND = 2012;
      //public const uint ERROR_TAG_NOT_PRESENT = 2013;
      //public const uint ERROR_DUPLICATE_TAG = 2014;
      //public const uint ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015;
      //public const uint ERROR_PROFILE_NOT_FOUND = 2016;
      //public const uint ERROR_INVALID_COLORSPACE = 2017;
      //public const uint ERROR_ICM_NOT_ENABLED = 2018;
      //public const uint ERROR_DELETING_ICM_XFORM = 2019;
      //public const uint ERROR_INVALID_TRANSFORM = 2020;
      //public const uint ERROR_COLORSPACE_MISMATCH = 2021;
      //public const uint ERROR_INVALID_COLORINDEX = 2022;
      //public const uint ERROR_CONNECTED_OTHER_PASSWORD = <PASSWORD>;
      //public const uint ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT = 2109;
      //public const uint ERROR_UNKNOWN_PRINT_MONITOR = 3000;
      //public const uint ERROR_PRINTER_DRIVER_IN_USE = 3001;
      //public const uint ERROR_SPOOL_FILE_NOT_FOUND = 3002;
      //public const uint ERROR_SPL_NO_STARTDOC = 3003;
      //public const uint ERROR_SPL_NO_ADDJOB = 3004;
      //public const uint ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED = 3005;
      //public const uint ERROR_PRINT_MONITOR_ALREADY_INSTALLED = 3006;
      //public const uint ERROR_INVALID_PRINT_MONITOR = 3007;
      //public const uint ERROR_PRINT_MONITOR_IN_USE = 3008;
      //public const uint ERROR_PRINTER_HAS_JOBS_QUEUED = 3009;

      /// <summary>(3010) The requested operation is successful.
      /// <para>Changes will not be effective until the system is rebooted.</para>
      /// </summary>
      public const uint ERROR_SUCCESS_REBOOT_REQUIRED = 3010;

      /// <summary>(3011) The requested operation is successful.
      /// <para>Changes will not be effective until the service is restarted.</para>
      /// </summary>
      public const uint ERROR_SUCCESS_RESTART_REQUIRED = 3011;

      //public const uint ERROR_PRINTER_NOT_FOUND = 3012;
      //public const uint ERROR_PRINTER_DRIVER_WARNED = 3013;
      //public const uint ERROR_PRINTER_DRIVER_BLOCKED = 3014;
      //public const uint ERROR_WINS_INTERNAL = 4000;
      //public const uint ERROR_CAN_NOT_DEL_LOCAL_WINS = 4001;
      //public const uint ERROR_STATIC_INIT = 4002;
      //public const uint ERROR_INC_BACKUP = 4003;
      //public const uint ERROR_FULL_BACKUP = 4004;
      //public const uint ERROR_REC_NON_EXISTENT = 4005;
      //public const uint ERROR_RPL_NOT_ALLOWED = 4006;
      //public const uint ERROR_DHCP_ADDRESS_CONFLICT = 4100;
      //public const uint ERROR_WMI_GUID_NOT_FOUND = 4200;
      //public const uint ERROR_WMI_INSTANCE_NOT_FOUND = 4201;
      //public const uint ERROR_WMI_ITEMID_NOT_FOUND = 4202;
      //public const uint ERROR_WMI_TRY_AGAIN = 4203;
      //public const uint ERROR_WMI_DP_NOT_FOUND = 4204;
      //public const uint ERROR_WMI_UNRESOLVED_INSTANCE_REF = 4205;
      //public const uint ERROR_WMI_ALREADY_ENABLED = 4206;
      //public const uint ERROR_WMI_GUID_DISCONNECTED = 4207;
      //public const uint ERROR_WMI_SERVER_UNAVAILABLE = 4208;
      //public const uint ERROR_WMI_DP_FAILED = 4209;
      //public const uint ERROR_WMI_INVALID_MOF = 4210;
      //public const uint ERROR_WMI_INVALID_REGINFO = 4211;
      //public const uint ERROR_WMI_ALREADY_DISABLED = 4212;
      //public const uint ERROR_WMI_READ_ONLY = 4213;
      //public const uint ERROR_WMI_SET_FAILURE = 4214;
      //public const uint ERROR_INVALID_MEDIA = 4300;
      //public const uint ERROR_INVALID_LIBRARY = 4301;
      //public const uint ERROR_INVALID_MEDIA_POOL = 4302;
      //public const uint ERROR_DRIVE_MEDIA_MISMATCH = 4303;
      //public const uint ERROR_MEDIA_OFFLINE = 4304;
      //public const uint ERROR_LIBRARY_OFFLINE = 4305;
      //public const uint ERROR_EMPTY = 4306;
      //public const uint ERROR_NOT_EMPTY = 4307;
      //public const uint ERROR_MEDIA_UNAVAILABLE = 4308;
      //public const uint ERROR_RESOURCE_DISABLED = 4309;
      //public const uint ERROR_INVALID_CLEANER = 4310;
      //public const uint ERROR_UNABLE_TO_CLEAN = 4311;
      //public const uint ERROR_OBJECT_NOT_FOUND = 4312;
      //public const uint ERROR_DATABASE_FAILURE = 4313;
      //public const uint ERROR_DATABASE_FULL = 4314;
      //public const uint ERROR_MEDIA_INCOMPATIBLE = 4315;
      //public const uint ERROR_RESOURCE_NOT_PRESENT = 4316;
      //public const uint ERROR_INVALID_OPERATION = 4317;
      //public const uint ERROR_MEDIA_NOT_AVAILABLE = 4318;
      //public const uint ERROR_DEVICE_NOT_AVAILABLE = 4319;
      //public const uint ERROR_REQUEST_REFUSED = 4320;
      //public const uint ERROR_INVALID_DRIVE_OBJECT = 4321;
      //public const uint ERROR_LIBRARY_FULL = 4322;
      //public const uint ERROR_MEDIUM_NOT_ACCESSIBLE = 4323;
      //public const uint ERROR_UNABLE_TO_LOAD_MEDIUM = 4324;
      //public const uint ERROR_UNABLE_TO_INVENTORY_DRIVE = 4325;
      //public const uint ERROR_UNABLE_TO_INVENTORY_SLOT = 4326;
      //public const uint ERROR_UNABLE_TO_INVENTORY_TRANSPORT = 4327;
      //public const uint ERROR_TRANSPORT_FULL = 4328;
      //public const uint ERROR_CONTROLLING_IEPORT = 4329;
      //public const uint ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA = 4330;
      //public const uint ERROR_CLEANER_SLOT_SET = 4331;
      //public const uint ERROR_CLEANER_SLOT_NOT_SET = 4332;
      //public const uint ERROR_CLEANER_CARTRIDGE_SPENT = 4333;
      //public const uint ERROR_UNEXPECTED_OMID = 4334;
      //public const uint ERROR_CANT_DELETE_LAST_ITEM = 4335;
      //public const uint ERROR_MESSAGE_EXCEEDS_MAX_SIZE = 4336;
      //public const uint ERROR_VOLUME_CONTAINS_SYS_FILES = 4337;
      //public const uint ERROR_INDIGENOUS_TYPE = 4338;
      //public const uint ERROR_NO_SUPPORTING_DRIVES = 4339;
      //public const uint ERROR_CLEANER_CARTRIDGE_INSTALLED = 4340;
      //public const uint ERROR_IEPORT_FULL = 4341;
      //public const uint ERROR_FILE_OFFLINE = 4350;
      //public const uint ERROR_REMOTE_STORAGE_NOT_ACTIVE = 4351;
      //public const uint ERROR_REMOTE_STORAGE_MEDIA_ERROR = 4352;

      /// <summary>(4390) The file or directory is not a reparse point.</summary>
      public const uint ERROR_NOT_A_REPARSE_POINT = 4390;

      //public const uint ERROR_REPARSE_ATTRIBUTE_CONFLICT = 4391;

      /// <summary>The data present in the reparse point buffer is invalid.</summary>
      public const uint ERROR_INVALID_REPARSE_DATA = 4392;

      //public const uint ERROR_REPARSE_TAG_INVALID = 4393;
      //public const uint ERROR_REPARSE_TAG_MISMATCH = 4394;
      //public const uint ERROR_VOLUME_NOT_SIS_ENABLED = 4500;
      //public const uint ERROR_DEPENDENT_RESOURCE_EXISTS = 5001;
      //public const uint ERROR_DEPENDENCY_NOT_FOUND = 5002;
      //public const uint ERROR_DEPENDENCY_ALREADY_EXISTS = 5003;
      //public const uint ERROR_RESOURCE_NOT_ONLINE = 5004;
      //public const uint ERROR_HOST_NODE_NOT_AVAILABLE = 5005;
      //public const uint ERROR_RESOURCE_NOT_AVAILABLE = 5006;
      //public const uint ERROR_RESOURCE_NOT_FOUND = 5007;
      //public const uint ERROR_SHUTDOWN_CLUSTER = 5008;
      //public const uint ERROR_CANT_EVICT_ACTIVE_NODE = 5009;
      //public const uint ERROR_OBJECT_ALREADY_EXISTS = 5010;
      //public const uint ERROR_OBJECT_IN_LIST = 5011;
      //public const uint ERROR_GROUP_NOT_AVAILABLE = 5012;
      //public const uint ERROR_GROUP_NOT_FOUND = 5013;
      //public const uint ERROR_GROUP_NOT_ONLINE = 5014;
      //public const uint ERROR_HOST_NODE_NOT_RESOURCE_OWNER = 5015;
      //public const uint ERROR_HOST_NODE_NOT_GROUP_OWNER = 5016;
      //public const uint ERROR_RESMON_CREATE_FAILED = 5017;
      //public const uint ERROR_RESMON_ONLINE_FAILED = 5018;
      //public const uint ERROR_RESOURCE_ONLINE = 5019;
      //public const uint ERROR_QUORUM_RESOURCE = 5020;
      //public const uint ERROR_NOT_QUORUM_CAPABLE = 5021;
      //public const uint ERROR_CLUSTER_SHUTTING_DOWN = 5022;
      //public const uint ERROR_INVALID_STATE = 5023;
      //public const uint ERROR_RESOURCE_PROPERTIES_STORED = 5024;
      //public const uint ERROR_NOT_QUORUM_CLASS = 5025;
      //public const uint ERROR_CORE_RESOURCE = 5026;
      //public const uint ERROR_QUORUM_RESOURCE_ONLINE_FAILED = 5027;
      //public const uint ERROR_QUORUMLOG_OPEN_FAILED = 5028;
      //public const uint ERROR_CLUSTERLOG_CORRUPT = 5029;
      //public const uint ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE = 5030;
      //public const uint ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE = 5031;
      //public const uint ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND = 5032;
      //public const uint ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE = 5033;
      //public const uint ERROR_QUORUM_OWNER_ALIVE = 5034;
      //public const uint ERROR_NETWORK_NOT_AVAILABLE = 5035;
      //public const uint ERROR_NODE_NOT_AVAILABLE = 5036;
      //public const uint ERROR_ALL_NODES_NOT_AVAILABLE = 5037;
      //public const uint ERROR_RESOURCE_FAILED = 5038;
      //public const uint ERROR_CLUSTER_INVALID_NODE = 5039;
      //public const uint ERROR_CLUSTER_NODE_EXISTS = 5040;
      //public const uint ERROR_CLUSTER_JOIN_IN_PROGRESS = 5041;
      //public const uint ERROR_CLUSTER_NODE_NOT_FOUND = 5042;
      //public const uint ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND = 5043;
      //public const uint ERROR_CLUSTER_NETWORK_EXISTS = 5044;
      //public const uint ERROR_CLUSTER_NETWORK_NOT_FOUND = 5045;
      //public const uint ERROR_CLUSTER_NETINTERFACE_EXISTS = 5046;
      //public const uint ERROR_CLUSTER_NETINTERFACE_NOT_FOUND = 5047;
      //public const uint ERROR_CLUSTER_INVALID_REQUEST = 5048;
      //public const uint ERROR_CLUSTER_INVALID_NETWORK_PROVIDER = 5049;
      //public const uint ERROR_CLUSTER_NODE_DOWN = 5050;
      //public const uint ERROR_CLUSTER_NODE_UNREACHABLE = 5051;
      //public const uint ERROR_CLUSTER_NODE_NOT_MEMBER = 5052;
      //public const uint ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS = 5053;
      //public const uint ERROR_CLUSTER_INVALID_NETWORK = 5054;
      //public const uint ERROR_CLUSTER_NODE_UP = 5056;
      //public const uint ERROR_CLUSTER_IPADDR_IN_USE = 5057;
      //public const uint ERROR_CLUSTER_NODE_NOT_PAUSED = 5058;
      //public const uint ERROR_CLUSTER_NO_SECURITY_CONTEXT = 5059;
      //public const uint ERROR_CLUSTER_NETWORK_NOT_INTERNAL = 5060;
      //public const uint ERROR_CLUSTER_NODE_ALREADY_UP = 5061;
      //public const uint ERROR_CLUSTER_NODE_ALREADY_DOWN = 5062;
      //public const uint ERROR_CLUSTER_NETWORK_ALREADY_ONLINE = 5063;
      //public const uint ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE = 5064;
      //public const uint ERROR_CLUSTER_NODE_ALREADY_MEMBER = 5065;
      //public const uint ERROR_CLUSTER_LAST_INTERNAL_NETWORK = 5066;
      //public const uint ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS = 5067;
      //public const uint ERROR_INVALID_OPERATION_ON_QUORUM = 5068;
      //public const uint ERROR_DEPENDENCY_NOT_ALLOWED = 5069;
      //public const uint ERROR_CLUSTER_NODE_PAUSED = 5070;
      //public const uint ERROR_NODE_CANT_HOST_RESOURCE = 5071;
      //public const uint ERROR_CLUSTER_NODE_NOT_READY = 5072;
      //public const uint ERROR_CLUSTER_NODE_SHUTTING_DOWN = 5073;
      //public const uint ERROR_CLUSTER_JOIN_ABORTED = 5074;
      //public const uint ERROR_CLUSTER_INCOMPATIBLE_VERSIONS = 5075;
      //public const uint ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED = 5076;
      //public const uint ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED = 5077;
      //public const uint ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND = 5078;
      //public const uint ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED = 5079;
      //public const uint ERROR_CLUSTER_RESNAME_NOT_FOUND = 5080;
      //public const uint ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED = 5081;
      //public const uint ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST = 5082;
      //public const uint ERROR_CLUSTER_DATABASE_SEQMISMATCH = 5083;
      //public const uint ERROR_RESMON_INVALID_STATE = 5084;
      //public const uint ERROR_CLUSTER_GUM_NOT_LOCKER = 5085;
      //public const uint ERROR_QUORUM_DISK_NOT_FOUND = 5086;
      //public const uint ERROR_DATABASE_BACKUP_CORRUPT = 5087;
      //public const uint ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT = 5088;
      //public const uint ERROR_RESOURCE_PROPERTY_UNCHANGEABLE = 5089;
      //public const uint ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE = 5890;
      //public const uint ERROR_CLUSTER_QUORUMLOG_NOT_FOUND = 5891;
      //public const uint ERROR_CLUSTER_MEMBERSHIP_HALT = 5892;
      //public const uint ERROR_CLUSTER_INSTANCE_ID_MISMATCH = 5893;
      //public const uint ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP = 5894;
      //public const uint ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH = 5895;
      //public const uint ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP = 5896;
      //public const uint ERROR_CLUSTER_PARAMETER_MISMATCH = 5897;
      //public const uint ERROR_NODE_CANNOT_BE_CLUSTERED = 5898;
      //public const uint ERROR_CLUSTER_WRONG_OS_VERSION = 5899;
      //public const uint ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME = 5900;
      //public const uint ERROR_CLUSCFG_ALREADY_COMMITTED = 5901;
      //public const uint ERROR_CLUSCFG_ROLLBACK_FAILED = 5902;
      //public const uint ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT = 5903;
      //public const uint ERROR_CLUSTER_OLD_VERSION = 5904;
      //public const uint ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME = 5905;
      //public const uint ERROR_ENCRYPTION_FAILED = 6000;
      //public const uint ERROR_DECRYPTION_FAILED = 6001;
      //public const uint ERROR_FILE_ENCRYPTED = 6002;
      //public const uint ERROR_NO_RECOVERY_POLICY = 6003;
      //public const uint ERROR_NO_EFS = 6004;
      //public const uint ERROR_WRONG_EFS = 6005;
      //public const uint ERROR_NO_USER_KEYS = 6006;
      //public const uint ERROR_FILE_NOT_ENCRYPTED = 6007;
      //public const uint ERROR_NOT_EXPORT_FORMAT = 6008;

      /// <summary>(6009) The specified file is read only.</summary>
      public const uint ERROR_FILE_READ_ONLY = 6009;

      //public const uint ERROR_DIR_EFS_DISALLOWED = 6010;
      //public const uint ERROR_EFS_SERVER_NOT_TRUSTED = 6011;

      /// <summary>(6012) Recovery policy configured for this system contains invalid recovery certificate.</summary>
      public const uint ERROR_BAD_RECOVERY_POLICY = 6012;

      //public const uint ERROR_EFS_ALG_BLOB_TOO_BIG = 6013;
      //public const uint ERROR_VOLUME_NOT_SUPPORT_EFS = 6014;
      //public const uint ERROR_EFS_DISABLED = 6015;
      //public const uint ERROR_EFS_VERSION_NOT_SUPPORT = 6016;
      //public const uint ERROR_NO_BROWSER_SERVERS_FOUND = 6118;
      //public const uint SCHED_E_SERVICE_NOT_LOCALSYSTEM = 6200;

      /// <summary>(6700) The transaction handle associated with this operation is not valid.</summary>
      public const uint ERROR_INVALID_TRANSACTION = 6700;

      /// <summary>(6701) The requested operation was made in the context
      /// <para>of a transaction that is no longer active.</para>
      /// </summary>
      public const uint ERROR_TRANSACTION_NOT_ACTIVE = 6701;

      /// <summary>(6702) The requested operation is not valid
      /// <para>on the Transaction object in its current state.</para>
      /// </summary>
      public const uint ERROR_TRANSACTION_REQUEST_NOT_VALID = 6702;

      /// <summary>(6703) The caller has called a response API, but the response is not expected
      /// <para>because the TM did not issue the corresponding request to the caller.</para>
      /// </summary>
      public const uint ERROR_TRANSACTION_NOT_REQUESTED = 6703;

      /// <summary>(6704) It is too late to perform the requested operation,
      /// <para>since the Transaction has already been aborted.</para>
      /// </summary>
      public const uint ERROR_TRANSACTION_ALREADY_ABORTED = 6704;

      /// <summary>(6705) It is too late to perform the requested operation,
      /// <para>since the Transaction has already been committed.</para>
      /// </summary>
      public const uint ERROR_TRANSACTION_ALREADY_COMMITTED = 6705;

      /// <summary>(6800) The function attempted to use a name
      /// <para>that is reserved for use by another transaction.</para>
      /// </summary>
      public const uint ERROR_TRANSACTIONAL_CONFLICT = 6800;

      /// <summary>(6805) The remote server or share does not support transacted file operations.</summary>
      public const uint ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE = 6805;

      //public const uint ERROR_CTX_WINSTATION_NAME_INVALID = 7001;
      //public const uint ERROR_CTX_INVALID_PD = 7002;
      //public const uint ERROR_CTX_PD_NOT_FOUND = 7003;
      //public const uint ERROR_CTX_WD_NOT_FOUND = 7004;
      //public const uint ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY = 7005;
      //public const uint ERROR_CTX_SERVICE_NAME_COLLISION = 7006;
      //public const uint ERROR_CTX_CLOSE_PENDING = 7007;
      //public const uint ERROR_CTX_NO_OUTBUF = 7008;
      //public const uint ERROR_CTX_MODEM_INF_NOT_FOUND = 7009;
      //public const uint ERROR_CTX_INVALID_MODEMNAME = 7010;
      //public const uint ERROR_CTX_MODEM_RESPONSE_ERROR = 7011;
      //public const uint ERROR_CTX_MODEM_RESPONSE_TIMEOUT = 7012;
      //public const uint ERROR_CTX_MODEM_RESPONSE_NO_CARRIER = 7013;
      //public const uint ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE = 7014;
      //public const uint ERROR_CTX_MODEM_RESPONSE_BUSY = 7015;
      //public const uint ERROR_CTX_MODEM_RESPONSE_VOICE = 7016;
      //public const uint ERROR_CTX_TD_ERROR = 7017;
      //public const uint ERROR_CTX_WINSTATION_NOT_FOUND = 7022;
      //public const uint ERROR_CTX_WINSTATION_ALREADY_EXISTS = 7023;
      //public const uint ERROR_CTX_WINSTATION_BUSY = 7024;
      //public const uint ERROR_CTX_BAD_VIDEO_MODE = 7025;
      //public const uint ERROR_CTX_GRAPHICS_INVALID = 7035;
      //public const uint ERROR_CTX_LOGON_DISABLED = 7037;
      //public const uint ERROR_CTX_NOT_CONSOLE = 7038;
      //public const uint ERROR_CTX_CLIENT_QUERY_TIMEOUT = 7040;
      //public const uint ERROR_CTX_CONSOLE_DISCONNECT = 7041;
      //public const uint ERROR_CTX_CONSOLE_CONNECT = 7042;
      //public const uint ERROR_CTX_SHADOW_DENIED = 7044;
      //public const uint ERROR_CTX_WINSTATION_ACCESS_DENIED = 7045;
      //public const uint ERROR_CTX_INVALID_WD = 7049;
      //public const uint ERROR_CTX_SHADOW_INVALID = 7050;
      //public const uint ERROR_CTX_SHADOW_DISABLED = 7051;
      //public const uint ERROR_CTX_CLIENT_LICENSE_IN_USE = 7052;
      //public const uint ERROR_CTX_CLIENT_LICENSE_NOT_SET = 7053;
      //public const uint ERROR_CTX_LICENSE_NOT_AVAILABLE = 7054;
      //public const uint ERROR_CTX_LICENSE_CLIENT_INVALID = 7055;
      //public const uint ERROR_CTX_LICENSE_EXPIRED = 7056;
      //public const uint ERROR_CTX_SHADOW_NOT_RUNNING = 7057;
      //public const uint ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE = 7058;
      //public const uint ERROR_ACTIVATION_COUNT_EXCEEDED = 7059;
      //public const uint FRS_ERR_INVALID_API_SEQUENCE = 8001;
      //public const uint FRS_ERR_STARTING_SERVICE = 8002;
      //public const uint FRS_ERR_STOPPING_SERVICE = 8003;
      //public const uint FRS_ERR_INTERNAL_API = 8004;
      //public const uint FRS_ERR_INTERNAL = 8005;
      //public const uint FRS_ERR_SERVICE_COMM = 8006;
      //public const uint FRS_ERR_INSUFFICIENT_PRIV = 8007;
      //public const uint FRS_ERR_AUTHENTICATION = 8008;
      //public const uint FRS_ERR_PARENT_INSUFFICIENT_PRIV = 8009;
      //public const uint FRS_ERR_PARENT_AUTHENTICATION = 8010;
      //public const uint FRS_ERR_CHILD_TO_PARENT_COMM = 8011;
      //public const uint FRS_ERR_PARENT_TO_CHILD_COMM = 8012;
      //public const uint FRS_ERR_SYSVOL_POPULATE = 8013;
      //public const uint FRS_ERR_SYSVOL_POPULATE_TIMEOUT = 8014;
      //public const uint FRS_ERR_SYSVOL_IS_BUSY = 8015;
      //public const uint FRS_ERR_SYSVOL_DEMOTE = 8016;
      //public const uint FRS_ERR_INVALID_SERVICE_PARAMETER = 8017;
      //public const uint ERROR_DS_NOT_INSTALLED = 8200;
      //public const uint ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY = 8201;
      //public const uint ERROR_DS_NO_ATTRIBUTE_OR_VALUE = 8202;
      //public const uint ERROR_DS_INVALID_ATTRIBUTE_SYNTAX = 8203;
      //public const uint ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED = 8204;
      //public const uint ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS = 8205;
      //public const uint ERROR_DS_BUSY = 8206;
      //public const uint ERROR_DS_UNAVAILABLE = 8207;
      //public const uint ERROR_DS_NO_RIDS_ALLOCATED = 8208;
      //public const uint ERROR_DS_NO_MORE_RIDS = 8209;
      //public const uint ERROR_DS_INCORRECT_ROLE_OWNER = 8210;
      //public const uint ERROR_DS_RIDMGR_INIT_ERROR = 8211;
      //public const uint ERROR_DS_OBJ_CLASS_VIOLATION = 8212;
      //public const uint ERROR_DS_CANT_ON_NON_LEAF = 8213;
      //public const uint ERROR_DS_CANT_ON_RDN = 8214;
      //public const uint ERROR_DS_CANT_MOD_OBJ_CLASS = 8215;
      //public const uint ERROR_DS_CROSS_DOM_MOVE_ERROR = 8216;
      //public const uint ERROR_DS_GC_NOT_AVAILABLE = 8217;
      //public const uint ERROR_SHARED_POLICY = 8218;
      //public const uint ERROR_POLICY_OBJECT_NOT_FOUND = 8219;
      //public const uint ERROR_POLICY_ONLY_IN_DS = 8220;
      //public const uint ERROR_PROMOTION_ACTIVE = 8221;
      //public const uint ERROR_NO_PROMOTION_ACTIVE = 8222;
      //public const uint ERROR_DS_OPERATIONS_ERROR = 8224;
      //public const uint ERROR_DS_PROTOCOL_ERROR = 8225;
      //public const uint ERROR_DS_TIMELIMIT_EXCEEDED = 8226;
      //public const uint ERROR_DS_SIZELIMIT_EXCEEDED = 8227;
      //public const uint ERROR_DS_ADMIN_LIMIT_EXCEEDED = 8228;
      //public const uint ERROR_DS_COMPARE_FALSE = 8229;
      //public const uint ERROR_DS_COMPARE_TRUE = 8230;
      //public const uint ERROR_DS_AUTH_METHOD_NOT_SUPPORTED = 8231;
      //public const uint ERROR_DS_STRONG_AUTH_REQUIRED = 8232;
      //public const uint ERROR_DS_INAPPROPRIATE_AUTH = 8233;
      //public const uint ERROR_DS_AUTH_UNKNOWN = 8234;
      //public const uint ERROR_DS_REFERRAL = 8235;
      //public const uint ERROR_DS_UNAVAILABLE_CRIT_EXTENSION = 8236;
      //public const uint ERROR_DS_CONFIDENTIALITY_REQUIRED = 8237;
      //public const uint ERROR_DS_INAPPROPRIATE_MATCHING = 8238;
      //public const uint ERROR_DS_CONSTRAINT_VIOLATION = 8239;
      //public const uint ERROR_DS_NO_SUCH_OBJECT = 8240;
      //public const uint ERROR_DS_ALIAS_PROBLEM = 8241;
      //public const uint ERROR_DS_INVALID_DN_SYNTAX = 8242;
      //public const uint ERROR_DS_IS_LEAF = 8243;
      //public const uint ERROR_DS_ALIAS_DEREF_PROBLEM = 8244;
      //public const uint ERROR_DS_UNWILLING_TO_PERFORM = 8245;
      //public const uint ERROR_DS_LOOP_DETECT = 8246;
      //public const uint ERROR_DS_NAMING_VIOLATION = 8247;
      //public const uint ERROR_DS_OBJECT_RESULTS_TOO_LARGE = 8248;
      //public const uint ERROR_DS_AFFECTS_MULTIPLE_DSAS = 8249;
      //public const uint ERROR_DS_SERVER_DOWN = 8250;
      //public const uint ERROR_DS_LOCAL_ERROR = 8251;
      //public const uint ERROR_DS_ENCODING_ERROR = 8252;
      //public const uint ERROR_DS_DECODING_ERROR = 8253;
      //public const uint ERROR_DS_FILTER_UNKNOWN = 8254;
      //public const uint ERROR_DS_PARAM_ERROR = 8255;
      //public const uint ERROR_DS_NOT_SUPPORTED = 8256;
      //public const uint ERROR_DS_NO_RESULTS_RETURNED = 8257;
      //public const uint ERROR_DS_CONTROL_NOT_FOUND = 8258;
      //public const uint ERROR_DS_CLIENT_LOOP = 8259;
      //public const uint ERROR_DS_REFERRAL_LIMIT_EXCEEDED = 8260;
      //public const uint ERROR_DS_SORT_CONTROL_MISSING = 8261;
      //public const uint ERROR_DS_OFFSET_RANGE_ERROR = 8262;
      //public const uint ERROR_DS_ROOT_MUST_BE_NC = 8301;
      //public const uint ERROR_DS_ADD_REPLICA_INHIBITED = 8302;
      //public const uint ERROR_DS_ATT_NOT_DEF_IN_SCHEMA = 8303;
      //public const uint ERROR_DS_MAX_OBJ_SIZE_EXCEEDED = 8304;
      //public const uint ERROR_DS_OBJ_STRING_NAME_EXISTS = 8305;
      //public const uint ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA = 8306;
      //public const uint ERROR_DS_RDN_DOESNT_MATCH_SCHEMA = 8307;
      //public const uint ERROR_DS_NO_REQUESTED_ATTS_FOUND = 8308;
      //public const uint ERROR_DS_USER_BUFFER_TO_SMALL = 8309;
      //public const uint ERROR_DS_ATT_IS_NOT_ON_OBJ = 8310;
      //public const uint ERROR_DS_ILLEGAL_MOD_OPERATION = 8311;
      //public const uint ERROR_DS_OBJ_TOO_LARGE = 8312;
      //public const uint ERROR_DS_BAD_INSTANCE_TYPE = 8313;
      //public const uint ERROR_DS_MASTERDSA_REQUIRED = 8314;
      //public const uint ERROR_DS_OBJECT_CLASS_REQUIRED = 8315;
      //public const uint ERROR_DS_MISSING_REQUIRED_ATT = 8316;
      //public const uint ERROR_DS_ATT_NOT_DEF_FOR_CLASS = 8317;
      //public const uint ERROR_DS_ATT_ALREADY_EXISTS = 8318;
      //public const uint ERROR_DS_CANT_ADD_ATT_VALUES = 8320;
      //public const uint ERROR_DS_SINGLE_VALUE_CONSTRAINT = 8321;
      //public const uint ERROR_DS_RANGE_CONSTRAINT = 8322;
      //public const uint ERROR_DS_ATT_VAL_ALREADY_EXISTS = 8323;
      //public const uint ERROR_DS_CANT_REM_MISSING_ATT = 8324;
      //public const uint ERROR_DS_CANT_REM_MISSING_ATT_VAL = 8325;
      //public const uint ERROR_DS_ROOT_CANT_BE_SUBREF = 8326;
      //public const uint ERROR_DS_NO_CHAINING = 8327;
      //public const uint ERROR_DS_NO_CHAINED_EVAL = 8328;
      //public const uint ERROR_DS_NO_PARENT_OBJECT = 8329;
      //public const uint ERROR_DS_PARENT_IS_AN_ALIAS = 8330;
      //public const uint ERROR_DS_CANT_MIX_MASTER_AND_REPS = 8331;
      //public const uint ERROR_DS_CHILDREN_EXIST = 8332;
      //public const uint ERROR_DS_OBJ_NOT_FOUND = 8333;
      //public const uint ERROR_DS_ALIASED_OBJ_MISSING = 8334;
      //public const uint ERROR_DS_BAD_NAME_SYNTAX = 8335;
      //public const uint ERROR_DS_ALIAS_POINTS_TO_ALIAS = 8336;
      //public const uint ERROR_DS_CANT_DEREF_ALIAS = 8337;
      //public const uint ERROR_DS_OUT_OF_SCOPE = 8338;
      //public const uint ERROR_DS_OBJECT_BEING_REMOVED = 8339;
      //public const uint ERROR_DS_CANT_DELETE_DSA_OBJ = 8340;
      //public const uint ERROR_DS_GENERIC_ERROR = 8341;
      //public const uint ERROR_DS_DSA_MUST_BE_INT_MASTER = 8342;
      //public const uint ERROR_DS_CLASS_NOT_DSA = 8343;
      //public const uint ERROR_DS_INSUFF_ACCESS_RIGHTS = 8344;
      //public const uint ERROR_DS_ILLEGAL_SUPERIOR = 8345;
      //public const uint ERROR_DS_ATTRIBUTE_OWNED_BY_SAM = 8346;
      //public const uint ERROR_DS_NAME_TOO_MANY_PARTS = 8347;
      //public const uint ERROR_DS_NAME_TOO_LONG = 8348;
      //public const uint ERROR_DS_NAME_VALUE_TOO_LONG = 8349;
      //public const uint ERROR_DS_NAME_UNPARSEABLE = 8350;
      //public const uint ERROR_DS_NAME_TYPE_UNKNOWN = 8351;
      //public const uint ERROR_DS_NOT_AN_OBJECT = 8352;
      //public const uint ERROR_DS_SEC_DESC_TOO_SHORT = 8353;
      //public const uint ERROR_DS_SEC_DESC_INVALID = 8354;
      //public const uint ERROR_DS_NO_DELETED_NAME = 8355;
      //public const uint ERROR_DS_SUBREF_MUST_HAVE_PARENT = 8356;
      //public const uint ERROR_DS_NCNAME_MUST_BE_NC = 8357;
      //public const uint ERROR_DS_CANT_ADD_SYSTEM_ONLY = 8358;
      //public const uint ERROR_DS_CLASS_MUST_BE_CONCRETE = 8359;
      //public const uint ERROR_DS_INVALID_DMD = 8360;
      //public const uint ERROR_DS_OBJ_GUID_EXISTS = 8361;
      //public const uint ERROR_DS_NOT_ON_BACKLINK = 8362;
      //public const uint ERROR_DS_NO_CROSSREF_FOR_NC = 8363;
      //public const uint ERROR_DS_SHUTTING_DOWN = 8364;
      //public const uint ERROR_DS_UNKNOWN_OPERATION = 8365;
      //public const uint ERROR_DS_INVALID_ROLE_OWNER = 8366;
      //public const uint ERROR_DS_COULDNT_CONTACT_FSMO = 8367;
      //public const uint ERROR_DS_CROSS_NC_DN_RENAME = 8368;
      //public const uint ERROR_DS_CANT_MOD_SYSTEM_ONLY = 8369;
      //public const uint ERROR_DS_REPLICATOR_ONLY = 8370;
      //public const uint ERROR_DS_OBJ_CLASS_NOT_DEFINED = 8371;
      //public const uint ERROR_DS_OBJ_CLASS_NOT_SUBCLASS = 8372;
      //public const uint ERROR_DS_NAME_REFERENCE_INVALID = 8373;
      //public const uint ERROR_DS_CROSS_REF_EXISTS = 8374;
      //public const uint ERROR_DS_CANT_DEL_MASTER_CROSSREF = 8375;
      //public const uint ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD = 8376;
      //public const uint ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX = 8377;
      //public const uint ERROR_DS_DUP_RDN = 8378;
      //public const uint ERROR_DS_DUP_OID = 8379;
      //public const uint ERROR_DS_DUP_MAPI_ID = 8380;
      //public const uint ERROR_DS_DUP_SCHEMA_ID_GUID = 8381;
      //public const uint ERROR_DS_DUP_LDAP_DISPLAY_NAME = 8382;
      //public const uint ERROR_DS_SEMANTIC_ATT_TEST = 8383;
      //public const uint ERROR_DS_SYNTAX_MISMATCH = 8384;
      //public const uint ERROR_DS_EXISTS_IN_MUST_HAVE = 8385;
      //public const uint ERROR_DS_EXISTS_IN_MAY_HAVE = 8386;
      //public const uint ERROR_DS_NONEXISTENT_MAY_HAVE = 8387;
      //public const uint ERROR_DS_NONEXISTENT_MUST_HAVE = 8388;
      //public const uint ERROR_DS_AUX_CLS_TEST_FAIL = 8389;
      //public const uint ERROR_DS_NONEXISTENT_POSS_SUP = 8390;
      //public const uint ERROR_DS_SUB_CLS_TEST_FAIL = 8391;
      //public const uint ERROR_DS_BAD_RDN_ATT_ID_SYNTAX = 8392;
      //public const uint ERROR_DS_EXISTS_IN_AUX_CLS = 8393;
      //public const uint ERROR_DS_EXISTS_IN_SUB_CLS = 8394;
      //public const uint ERROR_DS_EXISTS_IN_POSS_SUP = 8395;
      //public const uint ERROR_DS_RECALCSCHEMA_FAILED = 8396;
      //public const uint ERROR_DS_TREE_DELETE_NOT_FINISHED = 8397;
      //public const uint ERROR_DS_CANT_DELETE = 8398;
      //public const uint ERROR_DS_ATT_SCHEMA_REQ_ID = 8399;
      //public const uint ERROR_DS_BAD_ATT_SCHEMA_SYNTAX = 8400;
      //public const uint ERROR_DS_CANT_CACHE_ATT = 8401;
      //public const uint ERROR_DS_CANT_CACHE_CLASS = 8402;
      //public const uint ERROR_DS_CANT_REMOVE_ATT_CACHE = 8403;
      //public const uint ERROR_DS_CANT_REMOVE_CLASS_CACHE = 8404;
      //public const uint ERROR_DS_CANT_RETRIEVE_DN = 8405;
      //public const uint ERROR_DS_MISSING_SUPREF = 8406;
      //public const uint ERROR_DS_CANT_RETRIEVE_INSTANCE = 8407;
      //public const uint ERROR_DS_CODE_INCONSISTENCY = 8408;
      //public const uint ERROR_DS_DATABASE_ERROR = 8409;
      //public const uint ERROR_DS_GOVERNSID_MISSING = 8410;
      //public const uint ERROR_DS_MISSING_EXPECTED_ATT = 8411;
      //public const uint ERROR_DS_NCNAME_MISSING_CR_REF = 8412;
      //public const uint ERROR_DS_SECURITY_CHECKING_ERROR = 8413;
      //public const uint ERROR_DS_SCHEMA_NOT_LOADED = 8414;
      //public const uint ERROR_DS_SCHEMA_ALLOC_FAILED = 8415;
      //public const uint ERROR_DS_ATT_SCHEMA_REQ_SYNTAX = 8416;
      //public const uint ERROR_DS_GCVERIFY_ERROR = 8417;
      //public const uint ERROR_DS_DRA_SCHEMA_MISMATCH = 8418;
      //public const uint ERROR_DS_CANT_FIND_DSA_OBJ = 8419;
      //public const uint ERROR_DS_CANT_FIND_EXPECTED_NC = 8420;
      //public const uint ERROR_DS_CANT_FIND_NC_IN_CACHE = 8421;
      //public const uint ERROR_DS_CANT_RETRIEVE_CHILD = 8422;
      //public const uint ERROR_DS_SECURITY_ILLEGAL_MODIFY = 8423;
      //public const uint ERROR_DS_CANT_REPLACE_HIDDEN_REC = 8424;
      //public const uint ERROR_DS_BAD_HIERARCHY_FILE = 8425;
      //public const uint ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED = 8426;
      //public const uint ERROR_DS_CONFIG_PARAM_MISSING = 8427;
      //public const uint ERROR_DS_COUNTING_AB_INDICES_FAILED = 8428;
      //public const uint ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED = 8429;
      //public const uint ERROR_DS_INTERNAL_FAILURE = 8430;
      //public const uint ERROR_DS_UNKNOWN_ERROR = 8431;
      //public const uint ERROR_DS_ROOT_REQUIRES_CLASS_TOP = 8432;
      //public const uint ERROR_DS_REFUSING_FSMO_ROLES = 8433;
      //public const uint ERROR_DS_MISSING_FSMO_SETTINGS = 8434;
      //public const uint ERROR_DS_UNABLE_TO_SURRENDER_ROLES = 8435;
      //public const uint ERROR_DS_DRA_GENERIC = 8436;
      //public const uint ERROR_DS_DRA_INVALID_PARAMETER = 8437;
      //public const uint ERROR_DS_DRA_BUSY = 8438;
      //public const uint ERROR_DS_DRA_BAD_DN = 8439;
      //public const uint ERROR_DS_DRA_BAD_NC = 8440;
      //public const uint ERROR_DS_DRA_DN_EXISTS = 8441;
      //public const uint ERROR_DS_DRA_INTERNAL_ERROR = 8442;
      //public const uint ERROR_DS_DRA_INCONSISTENT_DIT = 8443;
      //public const uint ERROR_DS_DRA_CONNECTION_FAILED = 8444;
      //public const uint ERROR_DS_DRA_BAD_INSTANCE_TYPE = 8445;
      //public const uint ERROR_DS_DRA_OUT_OF_MEM = 8446;
      //public const uint ERROR_DS_DRA_MAIL_PROBLEM = 8447;
      //public const uint ERROR_DS_DRA_REF_ALREADY_EXISTS = 8448;
      //public const uint ERROR_DS_DRA_REF_NOT_FOUND = 8449;
      //public const uint ERROR_DS_DRA_OBJ_IS_REP_SOURCE = 8450;
      //public const uint ERROR_DS_DRA_DB_ERROR = 8451;
      //public const uint ERROR_DS_DRA_NO_REPLICA = 8452;
      //public const uint ERROR_DS_DRA_ACCESS_DENIED = 8453;
      //public const uint ERROR_DS_DRA_NOT_SUPPORTED = 8454;
      //public const uint ERROR_DS_DRA_RPC_CANCELLED = 8455;
      //public const uint ERROR_DS_DRA_SOURCE_DISABLED = 8456;
      //public const uint ERROR_DS_DRA_SINK_DISABLED = 8457;
      //public const uint ERROR_DS_DRA_NAME_COLLISION = 8458;
      //public const uint ERROR_DS_DRA_SOURCE_REINSTALLED = 8459;
      //public const uint ERROR_DS_DRA_MISSING_PARENT = 8460;
      //public const uint ERROR_DS_DRA_PREEMPTED = 8461;
      //public const uint ERROR_DS_DRA_ABANDON_SYNC = 8462;
      //public const uint ERROR_DS_DRA_SHUTDOWN = 8463;
      //public const uint ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET = 8464;
      //public const uint ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA = 8465;
      //public const uint ERROR_DS_DRA_EXTN_CONNECTION_FAILED = 8466;
      //public const uint ERROR_DS_INSTALL_SCHEMA_MISMATCH = 8467;
      //public const uint ERROR_DS_DUP_LINK_ID = 8468;
      //public const uint ERROR_DS_NAME_ERROR_RESOLVING = 8469;
      //public const uint ERROR_DS_NAME_ERROR_NOT_FOUND = 8470;
      //public const uint ERROR_DS_NAME_ERROR_NOT_UNIQUE = 8471;
      //public const uint ERROR_DS_NAME_ERROR_NO_MAPPING = 8472;
      //public const uint ERROR_DS_NAME_ERROR_DOMAIN_ONLY = 8473;
      //public const uint ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = 8474;
      //public const uint ERROR_DS_CONSTRUCTED_ATT_MOD = 8475;
      //public const uint ERROR_DS_WRONG_OM_OBJ_CLASS = 8476;
      //public const uint ERROR_DS_DRA_REPL_PENDING = 8477;
      //public const uint ERROR_DS_DS_REQUIRED = 8478;
      //public const uint ERROR_DS_INVALID_LDAP_DISPLAY_NAME = 8479;
      //public const uint ERROR_DS_NON_BASE_SEARCH = 8480;
      //public const uint ERROR_DS_CANT_RETRIEVE_ATTS = 8481;
      //public const uint ERROR_DS_BACKLINK_WITHOUT_LINK = 8482;
      //public const uint ERROR_DS_EPOCH_MISMATCH = 8483;
      //public const uint ERROR_DS_SRC_NAME_MISMATCH = 8484;
      //public const uint ERROR_DS_SRC_AND_DST_NC_IDENTICAL = 8485;
      //public const uint ERROR_DS_DST_NC_MISMATCH = 8486;
      //public const uint ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC = 8487;
      //public const uint ERROR_DS_SRC_GUID_MISMATCH = 8488;
      //public const uint ERROR_DS_CANT_MOVE_DELETED_OBJECT = 8489;
      //public const uint ERROR_DS_PDC_OPERATION_IN_PROGRESS = 8490;
      //public const uint ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD = 8491;
      //public const uint ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION = 8492;
      //public const uint ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS = 8493;
      //public const uint ERROR_DS_NC_MUST_HAVE_NC_PARENT = 8494;
      //public const uint ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE = 8495;
      //public const uint ERROR_DS_DST_DOMAIN_NOT_NATIVE = 8496;
      //public const uint ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER = 8497;
      //public const uint ERROR_DS_CANT_MOVE_ACCOUNT_GROUP = 8498;
      //public const uint ERROR_DS_CANT_MOVE_RESOURCE_GROUP = 8499;
      //public const uint ERROR_DS_INVALID_SEARCH_FLAG = 8500;
      //public const uint ERROR_DS_NO_TREE_DELETE_ABOVE_NC = 8501;
      //public const uint ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE = 8502;
      //public const uint ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE = 8503;
      //public const uint ERROR_DS_SAM_INIT_FAILURE = 8504;
      //public const uint ERROR_DS_SENSITIVE_GROUP_VIOLATION = 8505;
      //public const uint ERROR_DS_CANT_MOD_PRIMARYGROUPID = 8506;
      //public const uint ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD = 8507;
      //public const uint ERROR_DS_NONSAFE_SCHEMA_CHANGE = 8508;
      //public const uint ERROR_DS_SCHEMA_UPDATE_DISALLOWED = 8509;
      //public const uint ERROR_DS_CANT_CREATE_UNDER_SCHEMA = 8510;
      //public const uint ERROR_DS_INSTALL_NO_SRC_SCH_VERSION = 8511;
      //public const uint ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE = 8512;
      //public const uint ERROR_DS_INVALID_GROUP_TYPE = 8513;
      //public const uint ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN = 8514;
      //public const uint ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN = 8515;
      //public const uint ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER = 8516;
      //public const uint ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER = 8517;
      //public const uint ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER = 8518;
      //public const uint ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER = 8519;
      //public const uint ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER = 8520;
      //public const uint ERROR_DS_HAVE_PRIMARY_MEMBERS = 8521;
      //public const uint ERROR_DS_STRING_SD_CONVERSION_FAILED = 8522;
      //public const uint ERROR_DS_NAMING_MASTER_GC = 8523;
      //public const uint ERROR_DS_DNS_LOOKUP_FAILURE = 8524;
      //public const uint ERROR_DS_COULDNT_UPDATE_SPNS = 8525;
      //public const uint ERROR_DS_CANT_RETRIEVE_SD = 8526;
      //public const uint ERROR_DS_KEY_NOT_UNIQUE = 8527;
      //public const uint ERROR_DS_WRONG_LINKED_ATT_SYNTAX = 8528;
      //public const uint ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD = <PASSWORD>;
      //public const uint ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY = 8530;
      //public const uint ERROR_DS_CANT_START = 8531;
      //public const uint ERROR_DS_INIT_FAILURE = 8532;
      //public const uint ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION = 8533;
      //public const uint ERROR_DS_SOURCE_DOMAIN_IN_FOREST = 8534;
      //public const uint ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST = 8535;
      //public const uint ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED = 8536;
      //public const uint ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN = 8537;
      //public const uint ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER = 8538;
      //public const uint ERROR_DS_SRC_SID_EXISTS_IN_FOREST = 8539;
      //public const uint ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH = 8540;
      //public const uint ERROR_SAM_INIT_FAILURE = 8541;
      //public const uint ERROR_DS_DRA_SCHEMA_INFO_SHIP = 8542;
      //public const uint ERROR_DS_DRA_SCHEMA_CONFLICT = 8543;
      //public const uint ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT = 8544;
      //public const uint ERROR_DS_DRA_OBJ_NC_MISMATCH = 8545;
      //public const uint ERROR_DS_NC_STILL_HAS_DSAS = 8546;
      //public const uint ERROR_DS_GC_REQUIRED = 8547;
      //public const uint ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY = 8548;
      //public const uint ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS = 8549;
      //public const uint ERROR_DS_CANT_ADD_TO_GC = 8550;
      //public const uint ERROR_DS_NO_CHECKPOINT_WITH_PDC = 8551;
      //public const uint ERROR_DS_SOURCE_AUDITING_NOT_ENABLED = 8552;
      //public const uint ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC = 8553;
      //public const uint ERROR_DS_INVALID_NAME_FOR_SPN = 8554;
      //public const uint ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS = 8555;
      //public const uint ERROR_DS_UNICODEPWD_NOT_IN_QUOTES = 8556;
      //public const uint ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED = 8557;
      //public const uint ERROR_DS_MUST_BE_RUN_ON_DST_DC = 8558;
      //public const uint ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER = 8559;
      //public const uint ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ = 8560;
      //public const uint ERROR_DS_INIT_FAILURE_CONSOLE = 8561;
      //public const uint ERROR_DS_SAM_INIT_FAILURE_CONSOLE = 8562;
      //public const uint ERROR_DS_FOREST_VERSION_TOO_HIGH = 8563;
      //public const uint ERROR_DS_DOMAIN_VERSION_TOO_HIGH = 8564;
      //public const uint ERROR_DS_FOREST_VERSION_TOO_LOW = 8565;
      //public const uint ERROR_DS_DOMAIN_VERSION_TOO_LOW = 8566;
      //public const uint ERROR_DS_INCOMPATIBLE_VERSION = 8567;
      //public const uint ERROR_DS_LOW_DSA_VERSION = 8568;
      //public const uint ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN = 8569;
      //public const uint ERROR_DS_NOT_SUPPORTED_SORT_ORDER = 8570;
      //public const uint ERROR_DS_NAME_NOT_UNIQUE = 8571;
      //public const uint ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4 = 8572;
      //public const uint ERROR_DS_OUT_OF_VERSION_STORE = 8573;
      //public const uint ERROR_DS_INCOMPATIBLE_CONTROLS_USED = 8574;
      //public const uint ERROR_DS_NO_REF_DOMAIN = 8575;
      //public const uint ERROR_DS_RESERVED_LINK_ID = 8576;
      //public const uint ERROR_DS_LINK_ID_NOT_AVAILABLE = 8577;
      //public const uint ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER = 8578;
      //public const uint ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE = 8579;
      //public const uint ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC = 8580;
      //public const uint ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG = 8581;
      //public const uint ERROR_DS_MODIFYDN_WRONG_GRANDPARENT = 8582;
      //public const uint ERROR_DS_NAME_ERROR_TRUST_REFERRAL = 8583;
      //public const uint ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER = 8584;
      //public const uint ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD = 8585;
      //public const uint ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2 = 8586;
      //public const uint ERROR_DS_THREAD_LIMIT_EXCEEDED = 8587;
      //public const uint ERROR_DS_NOT_CLOSEST = 8588;
      //public const uint ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF = 8589;
      //public const uint ERROR_DS_SINGLE_USER_MODE_FAILED = 8590;
      //public const uint ERROR_DS_NTDSCRIPT_SYNTAX_ERROR = 8591;
      //public const uint ERROR_DS_NTDSCRIPT_PROCESS_ERROR = 8592;
      //public const uint ERROR_DS_DIFFERENT_REPL_EPOCHS = 8593;
      //public const uint ERROR_DS_DRS_EXTENSIONS_CHANGED = 8594;
      //public const uint ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR = 8595;
      //public const uint ERROR_DS_NO_MSDS_INTID = 8596;
      //public const uint ERROR_DS_DUP_MSDS_INTID = 8597;
      //public const uint ERROR_DS_EXISTS_IN_RDNATTID = 8598;
      //public const uint ERROR_DS_AUTHORIZATION_FAILED = 8599;
      //public const uint ERROR_DS_INVALID_SCRIPT = 8600;
      //public const uint ERROR_DS_REMOTE_CROSSREF_OP_FAILED = 8601;
      //public const uint ERROR_DS_CROSS_REF_BUSY = 8602;
      //public const uint ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN = 8603;
      //public const uint ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC = 8604;
      //public const uint ERROR_DS_DUPLICATE_ID_FOUND = 8605;
      //public const uint ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT = 8606;
      //public const uint ERROR_DS_GROUP_CONVERSION_ERROR = 8607;
      //public const uint ERROR_DS_CANT_MOVE_APP_BASIC_GROUP = 8608;
      //public const uint ERROR_DS_CANT_MOVE_APP_QUERY_GROUP = 8609;
      //public const uint ERROR_DS_ROLE_NOT_VERIFIED = 8610;
      //public const uint ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL = 8611;
      //public const uint ERROR_DS_DOMAIN_RENAME_IN_PROGRESS = 8612;
      //public const uint ERROR_DS_EXISTING_AD_CHILD_NC = 8613;
      //public const uint ERROR_DS_REPL_LIFETIME_EXCEEDED = 8614;
      //public const uint ERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER = 8615;
      //public const uint ERROR_DS_LDAP_SEND_QUEUE_FULL = 8616;
      //public const uint ERROR_DS_DRA_OUT_SCHEDULE_WINDOW = 8617;
      //public const uint DNS_ERROR_RESPONSE_CODES_BASE = 9000;
      //public const uint DNS_ERROR_RCODE_NO_ERROR = NO_ERROR;
      //public const uint DNS_ERROR_MASK = 0x00002328;
      //public const uint DNS_ERROR_RCODE_FORMAT_ERROR = 9001;
      //public const uint DNS_ERROR_RCODE_SERVER_FAILURE = 9002;
      //public const uint DNS_ERROR_RCODE_NAME_ERROR = 9003;
      //public const uint DNS_ERROR_RCODE_NOT_IMPLEMENTED = 9004;
      //public const uint DNS_ERROR_RCODE_REFUSED = 9005;
      //public const uint DNS_ERROR_RCODE_YXDOMAIN = 9006;
      //public const uint DNS_ERROR_RCODE_YXRRSET = 9007;
      //public const uint DNS_ERROR_RCODE_NXRRSET = 9008;
      //public const uint DNS_ERROR_RCODE_NOTAUTH = 9009;
      //public const uint DNS_ERROR_RCODE_NOTZONE = 9010;
      //public const uint DNS_ERROR_RCODE_BADSIG = 9016;
      //public const uint DNS_ERROR_RCODE_BADKEY = 9017;
      //public const uint DNS_ERROR_RCODE_BADTIME = 9018;
      //public const uint DNS_ERROR_RCODE_LAST = DNS_ERROR_RCODE_BADTIME;
      //public const uint DNS_ERROR_PACKET_FMT_BASE = 9500;
      //public const uint DNS_INFO_NO_RECORDS = 9501;
      //public const uint DNS_ERROR_BAD_PACKET = 9502;
      //public const uint DNS_ERROR_NO_PACKET = 9503;
      //public const uint DNS_ERROR_RCODE = 9504;
      //public const uint DNS_ERROR_UNSECURE_PACKET = 9505;
      //public const uint DNS_STATUS_PACKET_UNSECURE = DNS_ERROR_UNSECURE_PACKET;
      //public const uint DNS_ERROR_NO_MEMORY = ERROR_OUTOFMEMORY;
      //public const uint DNS_ERROR_INVALID_NAME = ERROR_INVALID_NAME;
      //public const uint DNS_ERROR_INVALID_DATA = ERROR_INVALID_DATA;
      //public const uint DNS_ERROR_GENERAL_API_BASE = 9550;
      //public const uint DNS_ERROR_INVALID_TYPE = 9551;
      //public const uint DNS_ERROR_INVALID_IP_ADDRESS = 9552;
      //public const uint DNS_ERROR_INVALID_PROPERTY = 9553;
      //public const uint DNS_ERROR_TRY_AGAIN_LATER = 9554;
      //public const uint DNS_ERROR_NOT_UNIQUE = 9555;
      //public const uint DNS_ERROR_NON_RFC_NAME = 9556;
      //public const uint DNS_STATUS_FQDN = 9557;
      //public const uint DNS_STATUS_DOTTED_NAME = 9558;
      //public const uint DNS_STATUS_SINGLE_PART_NAME = 9559;
      //public const uint DNS_ERROR_INVALID_NAME_CHAR = 9560;
      //public const uint DNS_ERROR_NUMERIC_NAME = 9561;
      //public const uint DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER = 9562;
      //public const uint DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION = 9563;
      //public const uint DNS_ERROR_CANNOT_FIND_ROOT_HINTS = 9564;
      //public const uint DNS_ERROR_INCONSISTENT_ROOT_HINTS = 9565;
      //public const uint DNS_ERROR_ZONE_BASE = 9600;
      //public const uint DNS_ERROR_ZONE_DOES_NOT_EXIST = 9601;
      //public const uint DNS_ERROR_NO_ZONE_INFO = 9602;
      //public const uint DNS_ERROR_INVALID_ZONE_OPERATION = 9603;
      //public const uint DNS_ERROR_ZONE_CONFIGURATION_ERROR = 9604;
      //public const uint DNS_ERROR_ZONE_HAS_NO_SOA_RECORD = 9605;
      //public const uint DNS_ERROR_ZONE_HAS_NO_NS_RECORDS = 9606;
      //public const uint DNS_ERROR_ZONE_LOCKED = 9607;
      //public const uint DNS_ERROR_ZONE_CREATION_FAILED = 9608;
      //public const uint DNS_ERROR_ZONE_ALREADY_EXISTS = 9609;
      //public const uint DNS_ERROR_AUTOZONE_ALREADY_EXISTS = 9610;
      //public const uint DNS_ERROR_INVALID_ZONE_TYPE = 9611;
      //public const uint DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP = 9612;
      //public const uint DNS_ERROR_ZONE_NOT_SECONDARY = 9613;
      //public const uint DNS_ERROR_NEED_SECONDARY_ADDRESSES = 9614;
      //public const uint DNS_ERROR_WINS_INIT_FAILED = 9615;
      //public const uint DNS_ERROR_NEED_WINS_SERVERS = 9616;
      //public const uint DNS_ERROR_NBSTAT_INIT_FAILED = 9617;
      //public const uint DNS_ERROR_SOA_DELETE_INVALID = 9618;
      //public const uint DNS_ERROR_FORWARDER_ALREADY_EXISTS = 9619;
      //public const uint DNS_ERROR_ZONE_REQUIRES_MASTER_IP = 9620;
      //public const uint DNS_ERROR_ZONE_IS_SHUTDOWN = 9621;
      //public const uint DNS_ERROR_DATAFILE_BASE = 9650;
      //public const uint DNS_ERROR_PRIMARY_REQUIRES_DATAFILE = 9651;
      //public const uint DNS_ERROR_INVALID_DATAFILE_NAME = 9652;
      //public const uint DNS_ERROR_DATAFILE_OPEN_FAILURE = 9653;
      //public const uint DNS_ERROR_FILE_WRITEBACK_FAILED = 9654;
      //public const uint DNS_ERROR_DATAFILE_PARSING = 9655;
      //public const uint DNS_ERROR_DATABASE_BASE = 9700;
      //public const uint DNS_ERROR_RECORD_DOES_NOT_EXIST = 9701;
      //public const uint DNS_ERROR_RECORD_FORMAT = 9702;
      //public const uint DNS_ERROR_NODE_CREATION_FAILED = 9703;
      //public const uint DNS_ERROR_UNKNOWN_RECORD_TYPE = 9704;
      //public const uint DNS_ERROR_RECORD_TIMED_OUT = 9705;
      //public const uint DNS_ERROR_NAME_NOT_IN_ZONE = 9706;
      //public const uint DNS_ERROR_CNAME_LOOP = 9707;
      //public const uint DNS_ERROR_NODE_IS_CNAME = 9708;
      //public const uint DNS_ERROR_CNAME_COLLISION = 9709;
      //public const uint DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT = 9710;
      //public const uint DNS_ERROR_RECORD_ALREADY_EXISTS = 9711;
      //public const uint DNS_ERROR_SECONDARY_DATA = 9712;
      //public const uint DNS_ERROR_NO_CREATE_CACHE_DATA = 9713;
      //public const uint DNS_ERROR_NAME_DOES_NOT_EXIST = 9714;
      //public const uint DNS_WARNING_PTR_CREATE_FAILED = 9715;
      //public const uint DNS_WARNING_DOMAIN_UNDELETED = 9716;
      //public const uint DNS_ERROR_DS_UNAVAILABLE = 9717;
      //public const uint DNS_ERROR_DS_ZONE_ALREADY_EXISTS = 9718;
      //public const uint DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE = 9719;
      //public const uint DNS_ERROR_OPERATION_BASE = 9750;
      //public const uint DNS_INFO_AXFR_COMPLETE = 9751;
      //public const uint DNS_ERROR_AXFR = 9752;
      //public const uint DNS_INFO_ADDED_LOCAL_WINS = 9753;
      //public const uint DNS_ERROR_SECURE_BASE = 9800;
      //public const uint DNS_STATUS_CONTINUE_NEEDED = 9801;
      //public const uint DNS_ERROR_SETUP_BASE = 9850;
      //public const uint DNS_ERROR_NO_TCPIP = 9851;
      //public const uint DNS_ERROR_NO_DNS_SERVERS = 9852;
      //public const uint DNS_ERROR_DP_BASE = 9900;
      //public const uint DNS_ERROR_DP_DOES_NOT_EXIST = 9901;
      //public const uint DNS_ERROR_DP_ALREADY_EXISTS = 9902;
      //public const uint DNS_ERROR_DP_NOT_ENLISTED = 9903;
      //public const uint DNS_ERROR_DP_ALREADY_ENLISTED = 9904;
      //public const uint DNS_ERROR_DP_NOT_AVAILABLE = 9905;
      //public const uint DNS_ERROR_DP_FSMO_ERROR = 9906;
      //public const uint WSABASEERR = 10000;
      //public const uint WSAEINTR = 10004;
      //public const uint WSAEBADF = 10009;
      //public const uint WSAEACCES = 10013;
      //public const uint WSAEFAULT = 10014;
      //public const uint WSAEINVAL = 10022;
      //public const uint WSAEMFILE = 10024;
      //public const uint WSAEWOULDBLOCK = 10035;
      //public const uint WSAEINPROGRESS = 10036;
      //public const uint WSAEALREADY = 10037;
      //public const uint WSAENOTSOCK = 10038;
      //public const uint WSAEDESTADDRREQ = 10039;
      //public const uint WSAEMSGSIZE = 10040;
      //public const uint WSAEPROTOTYPE = 10041;
      //public const uint WSAENOPROTOOPT = 10042;
      //public const uint WSAEPROTONOSUPPORT = 10043;
      //public const uint WSAESOCKTNOSUPPORT = 10044;
      //public const uint WSAEOPNOTSUPP = 10045;
      //public const uint WSAEPFNOSUPPORT = 10046;
      //public const uint WSAEAFNOSUPPORT = 10047;
      //public const uint WSAEADDRINUSE = 10048;
      //public const uint WSAEADDRNOTAVAIL = 10049;
      //public const uint WSAENETDOWN = 10050;
      //public const uint WSAENETUNREACH = 10051;
      //public const uint WSAENETRESET = 10052;
      //public const uint WSAECONNABORTED = 10053;
      //public const uint WSAECONNRESET = 10054;
      //public const uint WSAENOBUFS = 10055;
      //public const uint WSAEISCONN = 10056;
      //public const uint WSAENOTCONN = 10057;
      //public const uint WSAESHUTDOWN = 10058;
      //public const uint WSAETOOMANYREFS = 10059;
      //public const uint WSAETIMEDOUT = 10060;
      //public const uint WSAECONNREFUSED = 10061;
      //public const uint WSAELOOP = 10062;
      //public const uint WSAENAMETOOLONG = 10063;
      //public const uint WSAEHOSTDOWN = 10064;
      //public const uint WSAEHOSTUNREACH = 10065;
      //public const uint WSAENOTEMPTY = 10066;
      //public const uint WSAEPROCLIM = 10067;
      //public const uint WSAEUSERS = 10068;
      //public const uint WSAEDQUOT = 10069;
      //public const uint WSAESTALE = 10070;
      //public const uint WSAEREMOTE = 10071;
      //public const uint WSASYSNOTREADY = 10091;
      //public const uint WSAVERNOTSUPPORTED = 10092;
      //public const uint WSANOTINITIALISED = 10093;
      //public const uint WSAEDISCON = 10101;
      //public const uint WSAENOMORE = 10102;
      //public const uint WSAECANCELLED = 10103;
      //public const uint WSAEINVALIDPROCTABLE = 10104;
      //public const uint WSAEINVALIDPROVIDER = 10105;
      //public const uint WSAEPROVIDERFAILEDINIT = 10106;
      //public const uint WSASYSCALLFAILURE = 10107;
      //public const uint WSASERVICE_NOT_FOUND = 10108;
      //public const uint WSATYPE_NOT_FOUND = 10109;
      //public const uint WSA_E_NO_MORE = 10110;
      //public const uint WSA_E_CANCELLED = 10111;
      //public const uint WSAEREFUSED = 10112;
      //public const uint WSAHOST_NOT_FOUND = 11001;
      //public const uint WSATRY_AGAIN = 11002;
      //public const uint WSANO_RECOVERY = 11003;
      //public const uint WSANO_DATA = 11004;
      //public const uint WSA_QOS_RECEIVERS = 11005;
      //public const uint WSA_QOS_SENDERS = 11006;
      //public const uint WSA_QOS_NO_SENDERS = 11007;
      //public const uint WSA_QOS_NO_RECEIVERS = 11008;
      //public const uint WSA_QOS_REQUEST_CONFIRMED = 11009;
      //public const uint WSA_QOS_ADMISSION_FAILURE = 11010;
      //public const uint WSA_QOS_POLICY_FAILURE = 11011;
      //public const uint WSA_QOS_BAD_STYLE = 11012;
      //public const uint WSA_QOS_BAD_OBJECT = 11013;
      //public const uint WSA_QOS_TRAFFIC_CTRL_ERROR = 11014;
      //public const uint WSA_QOS_GENERIC_ERROR = 11015;
      //public const uint WSA_QOS_ESERVICETYPE = 11016;
      //public const uint WSA_QOS_EFLOWSPEC = 11017;
      //public const uint WSA_QOS_EPROVSPECBUF = 11018;
      //public const uint WSA_QOS_EFILTERSTYLE = 11019;
      //public const uint WSA_QOS_EFILTERTYPE = 11020;
      //public const uint WSA_QOS_EFILTERCOUNT = 11021;
      //public const uint WSA_QOS_EOBJLENGTH = 11022;
      //public const uint WSA_QOS_EFLOWCOUNT = 11023;
      //public const uint WSA_QOS_EUNKOWNPSOBJ = 11024;
      //public const uint WSA_QOS_EPOLICYOBJ = 11025;
      //public const uint WSA_QOS_EFLOWDESC = 11026;
      //public const uint WSA_QOS_EPSFLOWSPEC = 11027;
      //public const uint WSA_QOS_EPSFILTERSPEC = 11028;
      //public const uint WSA_QOS_ESDMODEOBJ = 11029;
      //public const uint WSA_QOS_ESHAPERATEOBJ = 11030;
      //public const uint WSA_QOS_RESERVED_PETYPE = 11031;
      //public const uint ERROR_SXS_SECTION_NOT_FOUND = 14000;
      //public const uint ERROR_SXS_CANT_GEN_ACTCTX = 14001;
      //public const uint ERROR_SXS_INVALID_ACTCTXDATA_FORMAT = 14002;
      //public const uint ERROR_SXS_ASSEMBLY_NOT_FOUND = 14003;
      //public const uint ERROR_SXS_MANIFEST_FORMAT_ERROR = 14004;
      //public const uint ERROR_SXS_MANIFEST_PARSE_ERROR = 14005;
      //public const uint ERROR_SXS_ACTIVATION_CONTEXT_DISABLED = 14006;
      //public const uint ERROR_SXS_KEY_NOT_FOUND = 14007;
      //public const uint ERROR_SXS_VERSION_CONFLICT = 14008;
      //public const uint ERROR_SXS_WRONG_SECTION_TYPE = 14009;
      //public const uint ERROR_SXS_THREAD_QUERIES_DISABLED = 14010;
      //public const uint ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET = 14011;
      //public const uint ERROR_SXS_UNKNOWN_ENCODING_GROUP = 14012;
      //public const uint ERROR_SXS_UNKNOWN_ENCODING = 14013;
      //public const uint ERROR_SXS_INVALID_XML_NAMESPACE_URI = 14014;
      //public const uint ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED = 14015;
      //public const uint ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED = 14016;
      //public const uint ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE = 14017;
      //public const uint ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE = 14018;
      //public const uint ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE = 14019;
      //public const uint ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT = 14020;
      //public const uint ERROR_SXS_DUPLICATE_DLL_NAME = 14021;
      //public const uint ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME = 14022;
      //public const uint ERROR_SXS_DUPLICATE_CLSID = 14023;
      //public const uint ERROR_SXS_DUPLICATE_IID = 14024;
      //public const uint ERROR_SXS_DUPLICATE_TLBID = 14025;
      //public const uint ERROR_SXS_DUPLICATE_PROGID = 14026;
      //public const uint ERROR_SXS_DUPLICATE_ASSEMBLY_NAME = 14027;
      //public const uint ERROR_SXS_FILE_HASH_MISMATCH = 14028;
      //public const uint ERROR_SXS_POLICY_PARSE_ERROR = 14029;
      //public const uint ERROR_SXS_XML_E_MISSINGQUOTE = 14030;
      //public const uint ERROR_SXS_XML_E_COMMENTSYNTAX = 14031;
      //public const uint ERROR_SXS_XML_E_BADSTARTNAMECHAR = 14032;
      //public const uint ERROR_SXS_XML_E_BADNAMECHAR = 14033;
      //public const uint ERROR_SXS_XML_E_BADCHARINSTRING = 14034;
      //public const uint ERROR_SXS_XML_E_XMLDECLSYNTAX = 14035;
      //public const uint ERROR_SXS_XML_E_BADCHARDATA = 14036;
      //public const uint ERROR_SXS_XML_E_MISSINGWHITESPACE = 14037;
      //public const uint ERROR_SXS_XML_E_EXPECTINGTAGEND = 14038;
      //public const uint ERROR_SXS_XML_E_MISSINGSEMICOLON = 14039;
      //public const uint ERROR_SXS_XML_E_UNBALANCEDPAREN = 14040;
      //public const uint ERROR_SXS_XML_E_INTERNALERROR = 14041;
      //public const uint ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE = 14042;
      //public const uint ERROR_SXS_XML_E_INCOMPLETE_ENCODING = 14043;
      //public const uint ERROR_SXS_XML_E_MISSING_PAREN = 14044;
      //public const uint ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE = 14045;
      //public const uint ERROR_SXS_XML_E_MULTIPLE_COLONS = 14046;
      //public const uint ERROR_SXS_XML_E_INVALID_DECIMAL = 14047;
      //public const uint ERROR_SXS_XML_E_INVALID_HEXIDECIMAL = 14048;
      //public const uint ERROR_SXS_XML_E_INVALID_UNICODE = 14049;
      //public const uint ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK = 14050;
      //public const uint ERROR_SXS_XML_E_UNEXPECTEDENDTAG = 14051;
      //public const uint ERROR_SXS_XML_E_UNCLOSEDTAG = 14052;
      //public const uint ERROR_SXS_XML_E_DUPLICATEATTRIBUTE = 14053;
      //public const uint ERROR_SXS_XML_E_MULTIPLEROOTS = 14054;
      //public const uint ERROR_SXS_XML_E_INVALIDATROOTLEVEL = 14055;
      //public const uint ERROR_SXS_XML_E_BADXMLDECL = 14056;
      //public const uint ERROR_SXS_XML_E_MISSINGROOT = 14057;
      //public const uint ERROR_SXS_XML_E_UNEXPECTEDEOF = 14058;
      //public const uint ERROR_SXS_XML_E_BADPEREFINSUBSET = 14059;
      //public const uint ERROR_SXS_XML_E_UNCLOSEDSTARTTAG = 14060;
      //public const uint ERROR_SXS_XML_E_UNCLOSEDENDTAG = 14061;
      //public const uint ERROR_SXS_XML_E_UNCLOSEDSTRING = 14062;
      //public const uint ERROR_SXS_XML_E_UNCLOSEDCOMMENT = 14063;
      //public const uint ERROR_SXS_XML_E_UNCLOSEDDECL = 14064;
      //public const uint ERROR_SXS_XML_E_UNCLOSEDCDATA = 14065;
      //public const uint ERROR_SXS_XML_E_RESERVEDNAMESPACE = 14066;
      //public const uint ERROR_SXS_XML_E_INVALIDENCODING = 14067;
      //public const uint ERROR_SXS_XML_E_INVALIDSWITCH = 14068;
      //public const uint ERROR_SXS_XML_E_BADXMLCASE = 14069;
      //public const uint ERROR_SXS_XML_E_INVALID_STANDALONE = 14070;
      //public const uint ERROR_SXS_XML_E_UNEXPECTED_STANDALONE = 14071;
      //public const uint ERROR_SXS_XML_E_INVALID_VERSION = 14072;
      //public const uint ERROR_SXS_XML_E_MISSINGEQUALS = 14073;
      //public const uint ERROR_SXS_PROTECTION_RECOVERY_FAILED = 14074;
      //public const uint ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT = 14075;
      //public const uint ERROR_SXS_PROTECTION_CATALOG_NOT_VALID = 14076;
      //public const uint ERROR_SXS_UNTRANSLATABLE_HRESULT = 14077;
      //public const uint ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING = 14078;
      //public const uint ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE = 14079;
      //public const uint ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME = 14080;
      //public const uint ERROR_IPSEC_QM_POLICY_EXISTS = 13000;
      //public const uint ERROR_IPSEC_QM_POLICY_NOT_FOUND = 13001;
      //public const uint ERROR_IPSEC_QM_POLICY_IN_USE = 13002;
      //public const uint ERROR_IPSEC_MM_POLICY_EXISTS = 13003;
      //public const uint ERROR_IPSEC_MM_POLICY_NOT_FOUND = 13004;
      //public const uint ERROR_IPSEC_MM_POLICY_IN_USE = 13005;
      //public const uint ERROR_IPSEC_MM_FILTER_EXISTS = 13006;
      //public const uint ERROR_IPSEC_MM_FILTER_NOT_FOUND = 13007;
      //public const uint ERROR_IPSEC_TRANSPORT_FILTER_EXISTS = 13008;
      //public const uint ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND = 13009;
      //public const uint ERROR_IPSEC_MM_AUTH_EXISTS = 13010;
      //public const uint ERROR_IPSEC_MM_AUTH_NOT_FOUND = 13011;
      //public const uint ERROR_IPSEC_MM_AUTH_IN_USE = 13012;
      //public const uint ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND = 13013;
      //public const uint ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND = 13014;
      //public const uint ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND = 13015;
      //public const uint ERROR_IPSEC_TUNNEL_FILTER_EXISTS = 13016;
      //public const uint ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND = 13017;
      //public const uint ERROR_IPSEC_MM_FILTER_PENDING_DELETION = 13018;
      //public const uint ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION = 13019;
      //public const uint ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION = 13020;
      //public const uint ERROR_IPSEC_MM_POLICY_PENDING_DELETION = 13021;
      //public const uint ERROR_IPSEC_MM_AUTH_PENDING_DELETION = 13022;
      //public const uint ERROR_IPSEC_QM_POLICY_PENDING_DELETION = 13023;
      //public const uint WARNING_IPSEC_MM_POLICY_PRUNED = 13024;
      //public const uint WARNING_IPSEC_QM_POLICY_PRUNED = 13025;
      //public const uint ERROR_IPSEC_IKE_NEG_STATUS_BEGIN = 13800;
      //public const uint ERROR_IPSEC_IKE_AUTH_FAIL = 13801;
      //public const uint ERROR_IPSEC_IKE_ATTRIB_FAIL = 13802;
      //public const uint ERROR_IPSEC_IKE_NEGOTIATION_PENDING = 13803;
      //public const uint ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR = 13804;
      //public const uint ERROR_IPSEC_IKE_TIMED_OUT = 13805;
      //public const uint ERROR_IPSEC_IKE_NO_CERT = 13806;
      //public const uint ERROR_IPSEC_IKE_SA_DELETED = 13807;
      //public const uint ERROR_IPSEC_IKE_SA_REAPED = 13808;
      //public const uint ERROR_IPSEC_IKE_MM_ACQUIRE_DROP = 13809;
      //public const uint ERROR_IPSEC_IKE_QM_ACQUIRE_DROP = 13810;
      //public const uint ERROR_IPSEC_IKE_QUEUE_DROP_MM = 13811;
      //public const uint ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM = 13812;
      //public const uint ERROR_IPSEC_IKE_DROP_NO_RESPONSE = 13813;
      //public const uint ERROR_IPSEC_IKE_MM_DELAY_DROP = 13814;
      //public const uint ERROR_IPSEC_IKE_QM_DELAY_DROP = 13815;
      //public const uint ERROR_IPSEC_IKE_ERROR = 13816;
      //public const uint ERROR_IPSEC_IKE_CRL_FAILED = 13817;
      //public const uint ERROR_IPSEC_IKE_INVALID_KEY_USAGE = 13818;
      //public const uint ERROR_IPSEC_IKE_INVALID_CERT_TYPE = 13819;
      //public const uint ERROR_IPSEC_IKE_NO_PRIVATE_KEY = 13820;
      //public const uint ERROR_IPSEC_IKE_DH_FAIL = 13822;
      //public const uint ERROR_IPSEC_IKE_INVALID_HEADER = 13824;
      //public const uint ERROR_IPSEC_IKE_NO_POLICY = 13825;
      //public const uint ERROR_IPSEC_IKE_INVALID_SIGNATURE = 13826;
      //public const uint ERROR_IPSEC_IKE_KERBEROS_ERROR = 13827;
      //public const uint ERROR_IPSEC_IKE_NO_PUBLIC_KEY = 13828;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR = 13829;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_SA = 13830;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_PROP = 13831;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_TRANS = 13832;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_KE = 13833;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_ID = 13834;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_CERT = 13835;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ = 13836;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_HASH = 13837;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_SIG = 13838;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_NONCE = 13839;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY = 13840;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_DELETE = 13841;
      //public const uint ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR = 13842;
      //public const uint ERROR_IPSEC_IKE_INVALID_PAYLOAD = 13843;
      //public const uint ERROR_IPSEC_IKE_LOAD_SOFT_SA = 13844;
      //public const uint ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN = 13845;
      //public const uint ERROR_IPSEC_IKE_INVALID_COOKIE = 13846;
      //public const uint ERROR_IPSEC_IKE_NO_PEER_CERT = 13847;
      //public const uint ERROR_IPSEC_IKE_PEER_CRL_FAILED = 13848;
      //public const uint ERROR_IPSEC_IKE_POLICY_CHANGE = 13849;
      //public const uint ERROR_IPSEC_IKE_NO_MM_POLICY = 13850;
      //public const uint ERROR_IPSEC_IKE_NOTCBPRIV = 13851;
      //public const uint ERROR_IPSEC_IKE_SECLOADFAIL = 13852;
      //public const uint ERROR_IPSEC_IKE_FAILSSPINIT = 13853;
      //public const uint ERROR_IPSEC_IKE_FAILQUERYSSP = 13854;
      //public const uint ERROR_IPSEC_IKE_SRVACQFAIL = 13855;
      //public const uint ERROR_IPSEC_IKE_SRVQUERYCRED = 13856;
      //public const uint ERROR_IPSEC_IKE_GETSPIFAIL = 13857;
      //public const uint ERROR_IPSEC_IKE_INVALID_FILTER = 13858;
      //public const uint ERROR_IPSEC_IKE_OUT_OF_MEMORY = 13859;
      //public const uint ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED = 13860;
      //public const uint ERROR_IPSEC_IKE_INVALID_POLICY = 13861;
      //public const uint ERROR_IPSEC_IKE_UNKNOWN_DOI = 13862;
      //public const uint ERROR_IPSEC_IKE_INVALID_SITUATION = 13863;
      //public const uint ERROR_IPSEC_IKE_DH_FAILURE = 13864;
      //public const uint ERROR_IPSEC_IKE_INVALID_GROUP = 13865;
      //public const uint ERROR_IPSEC_IKE_ENCRYPT = 13866;
      //public const uint ERROR_IPSEC_IKE_DECRYPT = 13867;
      //public const uint ERROR_IPSEC_IKE_POLICY_MATCH = 13868;
      //public const uint ERROR_IPSEC_IKE_UNSUPPORTED_ID = 13869;
      //public const uint ERROR_IPSEC_IKE_INVALID_HASH = 13870;
      //public const uint ERROR_IPSEC_IKE_INVALID_HASH_ALG = 13871;
      //public const uint ERROR_IPSEC_IKE_INVALID_HASH_SIZE = 13872;
      //public const uint ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG = 13873;
      //public const uint ERROR_IPSEC_IKE_INVALID_AUTH_ALG = 13874;
      //public const uint ERROR_IPSEC_IKE_INVALID_SIG = 13875;
      //public const uint ERROR_IPSEC_IKE_LOAD_FAILED = 13876;
      //public const uint ERROR_IPSEC_IKE_RPC_DELETE = 13877;
      //public const uint ERROR_IPSEC_IKE_BENIGN_REINIT = 13878;
      //public const uint ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY = 13879;
      //public const uint ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN = 13881;
      //public const uint ERROR_IPSEC_IKE_MM_LIMIT = 13882;
      //public const uint ERROR_IPSEC_IKE_NEGOTIATION_DISABLED = 13883;
      //public const uint ERROR_IPSEC_IKE_NEG_STATUS_END = 13884;
      //public const uint SEVERITY_SUCCESS = 0;
      //public const uint SEVERITY_ERROR = 1;
      //public const uint NOERROR = 0;

      //public const uint E_UNEXPECTED = 0x8000FFFF;
      //public const uint E_NOTIMPL = 0x80004001;
      //public const uint E_OUTOFMEMORY = 0x8007000E;
      //public const uint E_INVALIDARG = 0x80070057;
      //public const uint E_NOINTERFACE = 0x80004002;
      public const uint E_POINTER = 0x80004003;
      //public const uint E_HANDLE = 0x80070006;
      //public const uint E_ABORT = 0x80004004;
      //public const uint E_FAIL = 0x80004005;
      //public const uint E_ACCESSDENIED = 0x80070005;
      //public const uint E_PENDING = 0x8000000A;
      //public const uint CO_E_INIT_TLS = 0x80004006;
      //public const uint CO_E_INIT_SHARED_ALLOCATOR = 0x80004007;
      //public const uint CO_E_INIT_MEMORY_ALLOCATOR = 0x80004008;
      //public const uint CO_E_INIT_CLASS_CACHE = 0x80004009;
      //public const uint CO_E_INIT_RPC_CHANNEL = 0x8000400A;
      //public const uint CO_E_INIT_TLS_SET_CHANNEL_CONTROL = 0x8000400B;
      //public const uint CO_E_INIT_TLS_CHANNEL_CONTROL = 0x8000400C;
      //public const uint CO_E_INIT_UNACCEPTED_USER_ALLOCATOR = 0x8000400D;
      //public const uint CO_E_INIT_SCM_MUTEX_EXISTS = 0x8000400E;
      //public const uint CO_E_INIT_SCM_FILE_MAPPING_EXISTS = 0x8000400F;
      //public const uint CO_E_INIT_SCM_MAP_VIEW_OF_FILE = 0x80004010;
      //public const uint CO_E_INIT_SCM_EXEC_FAILURE = 0x80004011;
      //public const uint CO_E_INIT_ONLY_SINGLE_THREADED = 0x80004012;
      //public const uint CO_E_CANT_REMOTE = 0x80004013;
      //public const uint CO_E_BAD_SERVER_NAME = 0x80004014;
      //public const uint CO_E_WRONG_SERVER_IDENTITY = 0x80004015;
      //public const uint CO_E_OLE1DDE_DISABLED = 0x80004016;
      //public const uint CO_E_RUNAS_SYNTAX = 0x80004017;
      //public const uint CO_E_CREATEPROCESS_FAILURE = 0x80004018;
      //public const uint CO_E_RUNAS_CREATEPROCESS_FAILURE = 0x80004019;
      //public const uint CO_E_RUNAS_LOGON_FAILURE = 0x8000401A;
      //public const uint CO_E_LAUNCH_PERMSSION_DENIED = 0x8000401B;
      //public const uint CO_E_START_SERVICE_FAILURE = 0x8000401C;
      //public const uint CO_E_REMOTE_COMMUNICATION_FAILURE = 0x8000401D;
      //public const uint CO_E_SERVER_START_TIMEOUT = 0x8000401E;
      //public const uint CO_E_CLSREG_INCONSISTENT = 0x8000401F;
      //public const uint CO_E_IIDREG_INCONSISTENT = 0x80004020;
      //public const uint CO_E_NOT_SUPPORTED = 0x80004021;
      //public const uint CO_E_RELOAD_DLL = 0x80004022;
      //public const uint CO_E_MSI_ERROR = 0x80004023;
      //public const uint CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT = 0x80004024;
      //public const uint CO_E_SERVER_PAUSED = 0x80004025;
      //public const uint CO_E_SERVER_NOT_PAUSED = 0x80004026;
      //public const uint CO_E_CLASS_DISABLED = 0x80004027;
      //public const uint CO_E_CLRNOTAVAILABLE = 0x80004028;
      //public const uint CO_E_ASYNC_WORK_REJECTED = 0x80004029;
      //public const uint CO_E_SERVER_INIT_TIMEOUT = 0x8000402A;
      //public const uint CO_E_NO_SECCTX_IN_ACTIVATE = 0x8000402B;
      //public const uint CO_E_TRACKER_CONFIG = 0x80004030;
      //public const uint CO_E_THREADPOOL_CONFIG = 0x80004031;
      //public const uint CO_E_SXS_CONFIG = 0x80004032;
      //public const uint CO_E_MALFORMED_SPN = 0x80004033;

      /// <summary>(0) The operation completed successfully.</summary>
      public const uint S_OK = 0x00000000;

      //public const uint S_FALSE = 0x00000001;
      //public const uint OLE_E_FIRST = 0x80040000;
      //public const uint OLE_E_LAST = 0x800400FF;
      //public const uint OLE_S_FIRST = 0x00040000;
      //public const uint OLE_S_LAST = 0x000400FF;
      //public const uint OLE_E_OLEVERB = 0x80040000;
      //public const uint OLE_E_ADVF = 0x80040001;
      //public const uint OLE_E_ENUM_NOMORE = 0x80040002;
      //public const uint OLE_E_ADVISENOTSUPPORTED = 0x80040003;
      //public const uint OLE_E_NOCONNECTION = 0x80040004;
      //public const uint OLE_E_NOTRUNNING = 0x80040005;
      //public const uint OLE_E_NOCACHE = 0x80040006;
      //public const uint OLE_E_BLANK = 0x80040007;
      //public const uint OLE_E_CLASSDIFF = 0x80040008;
      //public const uint OLE_E_CANT_GETMONIKER = 0x80040009;
      //public const uint OLE_E_CANT_BINDTOSOURCE = 0x8004000A;
      //public const uint OLE_E_STATIC = 0x8004000B;
      //public const uint OLE_E_PROMPTSAVECANCELLED = 0x8004000C;
      //public const uint OLE_E_INVALIDRECT = 0x8004000D;
      //public const uint OLE_E_WRONGCOMPOBJ = 0x8004000E;
      //public const uint OLE_E_INVALIDHWND = 0x8004000F;
      //public const uint OLE_E_NOT_INPLACEACTIVE = 0x80040010;
      //public const uint OLE_E_CANTCONVERT = 0x80040011;
      //public const uint OLE_E_NOSTORAGE = 0x80040012;
      //public const uint DV_E_FORMATETC = 0x80040064;
      //public const uint DV_E_DVTARGETDEVICE = 0x80040065;
      //public const uint DV_E_STGMEDIUM = 0x80040066;
      //public const uint DV_E_STATDATA = 0x80040067;
      //public const uint DV_E_LINDEX = 0x80040068;
      //public const uint DV_E_TYMED = 0x80040069;
      //public const uint DV_E_CLIPFORMAT = 0x8004006A;
      //public const uint DV_E_DVASPECT = 0x8004006B;
      //public const uint DV_E_DVTARGETDEVICE_SIZE = 0x8004006C;
      //public const uint DV_E_NOIVIEWOBJECT = 0x8004006D;
      //public const uint DRAGDROP_E_FIRST = 0x80040100;
      //public const uint DRAGDROP_E_LAST = 0x8004010F;
      //public const uint DRAGDROP_S_FIRST = 0x00040100;
      //public const uint DRAGDROP_S_LAST = 0x0004010F;
      //public const uint DRAGDROP_E_NOTREGISTERED = 0x80040100;
      //public const uint DRAGDROP_E_ALREADYREGISTERED = 0x80040101;
      //public const uint DRAGDROP_E_INVALIDHWND = 0x80040102;
      //public const uint CLASSFACTORY_E_FIRST = 0x80040110;
      //public const uint CLASSFACTORY_E_LAST = 0x8004011F;
      //public const uint CLASSFACTORY_S_FIRST = 0x00040110;
      //public const uint CLASSFACTORY_S_LAST = 0x0004011F;
      //public const uint CLASS_E_NOAGGREGATION = 0x80040110;
      //public const uint CLASS_E_CLASSNOTAVAILABLE = 0x80040111;
      //public const uint CLASS_E_NOTLICENSED = 0x80040112;
      //public const uint MARSHAL_E_FIRST = 0x80040120;
      //public const uint MARSHAL_E_LAST = 0x8004012F;
      //public const uint MARSHAL_S_FIRST = 0x00040120;
      //public const uint MARSHAL_S_LAST = 0x0004012F;
      //public const uint DATA_E_FIRST = 0x80040130;
      //public const uint DATA_E_LAST = 0x8004013F;
      //public const uint DATA_S_FIRST = 0x00040130;
      //public const uint DATA_S_LAST = 0x0004013F;
      //public const uint VIEW_E_FIRST = 0x80040140;
      //public const uint VIEW_E_LAST = 0x8004014F;
      //public const uint VIEW_S_FIRST = 0x00040140;
      //public const uint VIEW_S_LAST = 0x0004014F;
      //public const uint VIEW_E_DRAW = 0x80040140;
      //public const uint REGDB_E_FIRST = 0x80040150;
      //public const uint REGDB_E_LAST = 0x8004015F;
      //public const uint REGDB_S_FIRST = 0x00040150;
      //public const uint REGDB_S_LAST = 0x0004015F;
      //public const uint REGDB_E_READREGDB = 0x80040150;
      //public const uint REGDB_E_WRITEREGDB = 0x80040151;
      //public const uint REGDB_E_KEYMISSING = 0x80040152;
      //public const uint REGDB_E_INVALIDVALUE = 0x80040153;
      //public const uint REGDB_E_CLASSNOTREG = 0x80040154;
      //public const uint REGDB_E_IIDNOTREG = 0x80040155;
      //public const uint REGDB_E_BADTHREADINGMODEL = 0x80040156;
      //public const uint CAT_E_FIRST = 0x80040160;
      //public const uint CAT_E_LAST = 0x80040161;
      //public const uint CAT_E_CATIDNOEXIST = 0x80040160;
      //public const uint CAT_E_NODESCRIPTION = 0x80040161;
      //public const uint CS_E_FIRST = 0x80040164;
      //public const uint CS_E_LAST = 0x8004016F;
      //public const uint CS_E_PACKAGE_NOTFOUND = 0x80040164;
      //public const uint CS_E_NOT_DELETABLE = 0x80040165;
      //public const uint CS_E_CLASS_NOTFOUND = 0x80040166;
      //public const uint CS_E_INVALID_VERSION = 0x80040167;
      //public const uint CS_E_NO_CLASSSTORE = 0x80040168;
      //public const uint CS_E_OBJECT_NOTFOUND = 0x80040169;
      //public const uint CS_E_OBJECT_ALREADY_EXISTS = 0x8004016A;
      //public const uint CS_E_INVALID_PATH = 0x8004016B;
      //public const uint CS_E_NETWORK_ERROR = 0x8004016C;
      //public const uint CS_E_ADMIN_LIMIT_EXCEEDED = 0x8004016D;
      //public const uint CS_E_SCHEMA_MISMATCH = 0x8004016E;
      //public const uint CS_E_INTERNAL_ERROR = 0x8004016F;
      //public const uint CACHE_E_FIRST = 0x80040170;
      //public const uint CACHE_E_LAST = 0x8004017F;
      //public const uint CACHE_S_FIRST = 0x00040170;
      //public const uint CACHE_S_LAST = 0x0004017F;
      //public const uint CACHE_E_NOCACHE_UPDATED = 0x80040170;
      //public const uint OLEOBJ_E_FIRST = 0x80040180;
      //public const uint OLEOBJ_E_LAST = 0x8004018F;
      //public const uint OLEOBJ_S_FIRST = 0x00040180;
      //public const uint OLEOBJ_S_LAST = 0x0004018F;
      //public const uint OLEOBJ_E_NOVERBS = 0x80040180;
      //public const uint OLEOBJ_E_INVALIDVERB = 0x80040181;
      //public const uint CLIENTSITE_E_FIRST = 0x80040190;
      //public const uint CLIENTSITE_E_LAST = 0x8004019F;
      //public const uint CLIENTSITE_S_FIRST = 0x00040190;
      //public const uint CLIENTSITE_S_LAST = 0x0004019F;
      //public const uint INPLACE_E_NOTUNDOABLE = 0x800401A0;
      //public const uint INPLACE_E_NOTOOLSPACE = 0x800401A1;
      //public const uint INPLACE_E_FIRST = 0x800401A0;
      //public const uint INPLACE_E_LAST = 0x800401AF;
      //public const uint INPLACE_S_FIRST = 0x000401A0;
      //public const uint INPLACE_S_LAST = 0x000401AF;
      //public const uint ENUM_E_FIRST = 0x800401B0;
      //public const uint ENUM_E_LAST = 0x800401BF;
      //public const uint ENUM_S_FIRST = 0x000401B0;
      //public const uint ENUM_S_LAST = 0x000401BF;
      //public const uint CONVERT10_E_FIRST = 0x800401C0;
      //public const uint CONVERT10_E_LAST = 0x800401CF;
      //public const uint CONVERT10_S_FIRST = 0x000401C0;
      //public const uint CONVERT10_S_LAST = 0x000401CF;
      //public const uint CONVERT10_E_OLESTREAM_GET = 0x800401C0;
      //public const uint CONVERT10_E_OLESTREAM_PUT = 0x800401C1;
      //public const uint CONVERT10_E_OLESTREAM_FMT = 0x800401C2;
      //public const uint CONVERT10_E_OLESTREAM_BITMAP_TO_DIB = 0x800401C3;
      //public const uint CONVERT10_E_STG_FMT = 0x800401C4;
      //public const uint CONVERT10_E_STG_NO_STD_STREAM = 0x800401C5;
      //public const uint CONVERT10_E_STG_DIB_TO_BITMAP = 0x800401C6;
      //public const uint CLIPBRD_E_FIRST = 0x800401D0;
      //public const uint CLIPBRD_E_LAST = 0x800401DF;
      //public const uint CLIPBRD_S_FIRST = 0x000401D0;
      //public const uint CLIPBRD_S_LAST = 0x000401DF;
      //public const uint CLIPBRD_E_CANT_OPEN = 0x800401D0;
      //public const uint CLIPBRD_E_CANT_EMPTY = 0x800401D1;
      //public const uint CLIPBRD_E_CANT_SET = 0x800401D2;
      //public const uint CLIPBRD_E_BAD_DATA = 0x800401D3;
      //public const uint CLIPBRD_E_CANT_CLOSE = 0x800401D4;
      //public const uint MK_E_FIRST = 0x800401E0;
      //public const uint MK_E_LAST = 0x800401EF;
      //public const uint MK_S_FIRST = 0x000401E0;
      //public const uint MK_S_LAST = 0x000401EF;
      //public const uint MK_E_CONNECTMANUALLY = 0x800401E0;
      //public const uint MK_E_EXCEEDEDDEADLINE = 0x800401E1;
      //public const uint MK_E_NEEDGENERIC = 0x800401E2;
      //public const uint MK_E_UNAVAILABLE = 0x800401E3;
      //public const uint MK_E_SYNTAX = 0x800401E4;
      //public const uint MK_E_NOOBJECT = 0x800401E5;
      //public const uint MK_E_INVALIDEXTENSION = 0x800401E6;
      //public const uint MK_E_INTERMEDIATEINTERFACENOTSUPPORTED = 0x800401E7;
      //public const uint MK_E_NOTBINDABLE = 0x800401E8;
      //public const uint MK_E_NOTBOUND = 0x800401E9;
      //public const uint MK_E_CANTOPENFILE = 0x800401EA;
      //public const uint MK_E_MUSTBOTHERUSER = 0x800401EB;
      //public const uint MK_E_NOINVERSE = 0x800401EC;
      //public const uint MK_E_NOSTORAGE = 0x800401ED;
      //public const uint MK_E_NOPREFIX = 0x800401EE;
      //public const uint MK_E_ENUMERATION_FAILED = 0x800401EF;
      //public const uint CO_E_FIRST = 0x800401F0;
      //public const uint CO_E_LAST = 0x800401FF;
      //public const uint CO_S_FIRST = 0x000401F0;
      //public const uint CO_S_LAST = 0x000401FF;
      //public const uint CO_E_NOTINITIALIZED = 0x800401F0;
      //public const uint CO_E_ALREADYINITIALIZED = 0x800401F1;
      //public const uint CO_E_CANTDETERMINECLASS = 0x800401F2;
      //public const uint CO_E_CLASSSTRING = 0x800401F3;
      //public const uint CO_E_IIDSTRING = 0x800401F4;
      //public const uint CO_E_APPNOTFOUND = 0x800401F5;
      //public const uint CO_E_APPSINGLEUSE = 0x800401F6;
      //public const uint CO_E_ERRORINAPP = 0x800401F7;
      //public const uint CO_E_DLLNOTFOUND = 0x800401F8;
      //public const uint CO_E_ERRORINDLL = 0x800401F9;
      //public const uint CO_E_WRONGOSFORAPP = 0x800401FA;
      //public const uint CO_E_OBJNOTREG = 0x800401FB;
      //public const uint CO_E_OBJISREG = 0x800401FC;
      //public const uint CO_E_OBJNOTCONNECTED = 0x800401FD;
      //public const uint CO_E_APPDIDNTREG = 0x800401FE;
      //public const uint CO_E_RELEASED = 0x800401FF;
      //public const uint EVENT_E_FIRST = 0x80040200;
      //public const uint EVENT_E_LAST = 0x8004021F;
      //public const uint EVENT_S_FIRST = 0x00040200;
      //public const uint EVENT_S_LAST = 0x0004021F;
      //public const uint EVENT_S_SOME_SUBSCRIBERS_FAILED = 0x00040200;
      //public const uint EVENT_E_ALL_SUBSCRIBERS_FAILED = 0x80040201;
      //public const uint EVENT_S_NOSUBSCRIBERS = 0x00040202;
      //public const uint EVENT_E_QUERYSYNTAX = 0x80040203;
      //public const uint EVENT_E_QUERYFIELD = 0x80040204;
      //public const uint EVENT_E_INTERNALEXCEPTION = 0x80040205;
      //public const uint EVENT_E_INTERNALERROR = 0x80040206;
      //public const uint EVENT_E_INVALID_PER_USER_SID = 0x80040207;
      //public const uint EVENT_E_USER_EXCEPTION = 0x80040208;
      //public const uint EVENT_E_TOO_MANY_METHODS = 0x80040209;
      //public const uint EVENT_E_MISSING_EVENTCLASS = 0x8004020A;
      //public const uint EVENT_E_NOT_ALL_REMOVED = 0x8004020B;
      //public const uint EVENT_E_COMPLUS_NOT_INSTALLED = 0x8004020C;
      //public const uint EVENT_E_CANT_MODIFY_OR_DELETE_UNCONFIGURED_OBJECT = 0x8004020D;
      //public const uint EVENT_E_CANT_MODIFY_OR_DELETE_CONFIGURED_OBJECT = 0x8004020E;
      //public const uint EVENT_E_INVALID_EVENT_CLASS_PARTITION = 0x8004020F;
      //public const uint EVENT_E_PER_USER_SID_NOT_LOGGED_ON = 0x80040210;
      //public const uint XACT_E_FIRST = 0x8004D000;
      //public const uint XACT_E_LAST = 0x8004D029;
      //public const uint XACT_S_FIRST = 0x0004D000;
      //public const uint XACT_S_LAST = 0x0004D010;
      //public const uint XACT_E_ALREADYOTHERSINGLEPHASE = 0x8004D000;
      //public const uint XACT_E_CANTRETAIN = 0x8004D001;
      //public const uint XACT_E_COMMITFAILED = 0x8004D002;
      //public const uint XACT_E_COMMITPREVENTED = 0x8004D003;
      //public const uint XACT_E_HEURISTICABORT = 0x8004D004;
      //public const uint XACT_E_HEURISTICCOMMIT = 0x8004D005;
      //public const uint XACT_E_HEURISTICDAMAGE = 0x8004D006;
      //public const uint XACT_E_HEURISTICDANGER = 0x8004D007;
      //public const uint XACT_E_ISOLATIONLEVEL = 0x8004D008;
      //public const uint XACT_E_NOASYNC = 0x8004D009;
      //public const uint XACT_E_NOENLIST = 0x8004D00A;
      //public const uint XACT_E_NOISORETAIN = 0x8004D00B;
      //public const uint XACT_E_NORESOURCE = 0x8004D00C;
      //public const uint XACT_E_NOTCURRENT = 0x8004D00D;
      //public const uint XACT_E_NOTRANSACTION = 0x8004D00E;
      //public const uint XACT_E_NOTSUPPORTED = 0x8004D00F;
      //public const uint XACT_E_UNKNOWNRMGRID = 0x8004D010;
      //public const uint XACT_E_WRONGSTATE = 0x8004D011;
      //public const uint XACT_E_WRONGUOW = 0x8004D012;
      //public const uint XACT_E_XTIONEXISTS = 0x8004D013;
      //public const uint XACT_E_NOIMPORTOBJECT = 0x8004D014;
      //public const uint XACT_E_INVALIDCOOKIE = 0x8004D015;
      //public const uint XACT_E_INDOUBT = 0x8004D016;
      //public const uint XACT_E_NOTIMEOUT = 0x8004D017;
      //public const uint XACT_E_ALREADYINPROGRESS = 0x8004D018;
      //public const uint XACT_E_ABORTED = 0x8004D019;
      //public const uint XACT_E_LOGFULL = 0x8004D01A;
      //public const uint XACT_E_TMNOTAVAILABLE = 0x8004D01B;
      //public const uint XACT_E_CONNECTION_DOWN = 0x8004D01C;
      //public const uint XACT_E_CONNECTION_DENIED = 0x8004D01D;
      //public const uint XACT_E_REENLISTTIMEOUT = 0x8004D01E;
      //public const uint XACT_E_TIP_CONNECT_FAILED = 0x8004D01F;
      //public const uint XACT_E_TIP_PROTOCOL_ERROR = 0x8004D020;
      //public const uint XACT_E_TIP_PULL_FAILED = 0x8004D021;
      //public const uint XACT_E_DEST_TMNOTAVAILABLE = 0x8004D022;
      //public const uint XACT_E_TIP_DISABLED = 0x8004D023;
      //public const uint XACT_E_NETWORK_TX_DISABLED = 0x8004D024;
      //public const uint XACT_E_PARTNER_NETWORK_TX_DISABLED = 0x8004D025;
      //public const uint XACT_E_XA_TX_DISABLED = 0x8004D026;
      //public const uint XACT_E_UNABLE_TO_READ_DTC_CONFIG = 0x8004D027;
      //public const uint XACT_E_UNABLE_TO_LOAD_DTC_PROXY = 0x8004D028;
      //public const uint XACT_E_ABORTING = 0x8004D029;
      //public const uint XACT_E_CLERKNOTFOUND = 0x8004D080;
      //public const uint XACT_E_CLERKEXISTS = 0x8004D081;
      //public const uint XACT_E_RECOVERYINPROGRESS = 0x8004D082;
      //public const uint XACT_E_TRANSACTIONCLOSED = 0x8004D083;
      //public const uint XACT_E_INVALIDLSN = 0x8004D084;
      //public const uint XACT_E_REPLAYREQUEST = 0x8004D085;
      //public const uint XACT_S_ASYNC = 0x0004D000;
      //public const uint XACT_S_DEFECT = 0x0004D001;
      //public const uint XACT_S_READONLY = 0x0004D002;
      //public const uint XACT_S_SOMENORETAIN = 0x0004D003;
      //public const uint XACT_S_OKINFORM = 0x0004D004;
      //public const uint XACT_S_MADECHANGESCONTENT = 0x0004D005;
      //public const uint XACT_S_MADECHANGESINFORM = 0x0004D006;
      //public const uint XACT_S_ALLNORETAIN = 0x0004D007;
      //public const uint XACT_S_ABORTING = 0x0004D008;
      //public const uint XACT_S_SINGLEPHASE = 0x0004D009;
      //public const uint XACT_S_LOCALLY_OK = 0x0004D00A;
      //public const uint XACT_S_LASTRESOURCEMANAGER = 0x0004D010;
      //public const uint CONTEXT_E_FIRST = 0x8004E000;
      //public const uint CONTEXT_E_LAST = 0x8004E02F;
      //public const uint CONTEXT_S_FIRST = 0x0004E000;
      //public const uint CONTEXT_S_LAST = 0x0004E02F;
      //public const uint CONTEXT_E_ABORTED = 0x8004E002;
      //public const uint CONTEXT_E_ABORTING = 0x8004E003;
      //public const uint CONTEXT_E_NOCONTEXT = 0x8004E004;
      //public const uint CONTEXT_E_WOULD_DEADLOCK = 0x8004E005;
      //public const uint CONTEXT_E_SYNCH_TIMEOUT = 0x8004E006;
      //public const uint CONTEXT_E_OLDREF = 0x8004E007;
      //public const uint CONTEXT_E_ROLENOTFOUND = 0x8004E00C;
      //public const uint CONTEXT_E_TMNOTAVAILABLE = 0x8004E00F;
      //public const uint CO_E_ACTIVATIONFAILED = 0x8004E021;
      //public const uint CO_E_ACTIVATIONFAILED_EVENTLOGGED = 0x8004E022;
      //public const uint CO_E_ACTIVATIONFAILED_CATALOGERROR = 0x8004E023;
      //public const uint CO_E_ACTIVATIONFAILED_TIMEOUT = 0x8004E024;
      //public const uint CO_E_INITIALIZATIONFAILED = 0x8004E025;
      //public const uint CONTEXT_E_NOJIT = 0x8004E026;
      //public const uint CONTEXT_E_NOTRANSACTION = 0x8004E027;
      //public const uint CO_E_THREADINGMODEL_CHANGED = 0x8004E028;
      //public const uint CO_E_NOIISINTRINSICS = 0x8004E029;
      //public const uint CO_E_NOCOOKIES = 0x8004E02A;
      //public const uint CO_E_DBERROR = 0x8004E02B;
      //public const uint CO_E_NOTPOOLED = 0x8004E02C;
      //public const uint CO_E_NOTCONSTRUCTED = 0x8004E02D;
      //public const uint CO_E_NOSYNCHRONIZATION = 0x8004E02E;
      //public const uint CO_E_ISOLEVELMISMATCH = 0x8004E02F;
      //public const uint OLE_S_USEREG = 0x00040000;
      //public const uint OLE_S_STATIC = 0x00040001;
      //public const uint OLE_S_MAC_CLIPFORMAT = 0x00040002;
      //public const uint DRAGDROP_S_DROP = 0x00040100;
      //public const uint DRAGDROP_S_CANCEL = 0x00040101;
      //public const uint DRAGDROP_S_USEDEFAULTCURSORS = 0x00040102;
      //public const uint DATA_S_SAMEFORMATETC = 0x00040130;
      //public const uint VIEW_S_ALREADY_FROZEN = 0x00040140;
      //public const uint CACHE_S_FORMATETC_NOTSUPPORTED = 0x00040170;
      //public const uint CACHE_S_SAMECACHE = 0x00040171;
      //public const uint CACHE_S_SOMECACHES_NOTUPDATED = 0x00040172;
      //public const uint OLEOBJ_S_INVALIDVERB = 0x00040180;
      //public const uint OLEOBJ_S_CANNOT_DOVERB_NOW = 0x00040181;
      //public const uint OLEOBJ_S_INVALIDHWND = 0x00040182;
      //public const uint INPLACE_S_TRUNCATED = 0x000401A0;
      //public const uint CONVERT10_S_NO_PRESENTATION = 0x000401C0;
      //public const uint MK_S_REDUCED_TO_SELF = 0x000401E2;
      //public const uint MK_S_ME = 0x000401E4;
      //public const uint MK_S_HIM = 0x000401E5;
      //public const uint MK_S_US = 0x000401E6;
      //public const uint MK_S_MONIKERALREADYREGISTERED = 0x000401E7;
      //public const uint SCHED_S_TASK_READY = 0x00041300;
      //public const uint SCHED_S_TASK_RUNNING = 0x00041301;
      //public const uint SCHED_S_TASK_DISABLED = 0x00041302;
      //public const uint SCHED_S_TASK_HAS_NOT_RUN = 0x00041303;
      //public const uint SCHED_S_TASK_NO_MORE_RUNS = 0x00041304;
      //public const uint SCHED_S_TASK_NOT_SCHEDULED = 0x00041305;
      //public const uint SCHED_S_TASK_TERMINATED = 0x00041306;
      //public const uint SCHED_S_TASK_NO_VALID_TRIGGERS = 0x00041307;
      //public const uint SCHED_S_EVENT_TRIGGER = 0x00041308;
      //public const uint SCHED_E_TRIGGER_NOT_FOUND = 0x80041309;
      //public const uint SCHED_E_TASK_NOT_READY = 0x8004130A;
      //public const uint SCHED_E_TASK_NOT_RUNNING = 0x8004130B;
      //public const uint SCHED_E_SERVICE_NOT_INSTALLED = 0x8004130C;
      //public const uint SCHED_E_CANNOT_OPEN_TASK = 0x8004130D;
      //public const uint SCHED_E_INVALID_TASK = 0x8004130E;
      //public const uint SCHED_E_ACCOUNT_INFORMATION_NOT_SET = 0x8004130F;
      //public const uint SCHED_E_ACCOUNT_NAME_NOT_FOUND = 0x80041310;
      //public const uint SCHED_E_ACCOUNT_DBASE_CORRUPT = 0x80041311;
      //public const uint SCHED_E_NO_SECURITY_SERVICES = 0x80041312;
      //public const uint SCHED_E_UNKNOWN_OBJECT_VERSION = 0x80041313;
      //public const uint SCHED_E_UNSUPPORTED_ACCOUNT_OPTION = 0x80041314;
      //public const uint SCHED_E_SERVICE_NOT_RUNNING = 0x80041315;
      //public const uint CO_E_CLASS_CREATE_FAILED = 0x80080001;
      //public const uint CO_E_SCM_ERROR = 0x80080002;
      //public const uint CO_E_SCM_RPC_FAILURE = 0x80080003;
      //public const uint CO_E_BAD_PATH = 0x80080004;
      //public const uint CO_E_SERVER_EXEC_FAILURE = 0x80080005;
      //public const uint CO_E_OBJSRV_RPC_FAILURE = 0x80080006;
      //public const uint MK_E_NO_NORMALIZED = 0x80080007;
      //public const uint CO_E_SERVER_STOPPING = 0x80080008;
      //public const uint MEM_E_INVALID_ROOT = 0x80080009;
      //public const uint MEM_E_INVALID_LINK = 0x80080010;
      //public const uint MEM_E_INVALID_SIZE = 0x80080011;
      //public const uint CO_S_NOTALLINTERFACES = 0x00080012;
      //public const uint CO_S_MACHINENAMENOTFOUND = 0x00080013;
      //public const uint DISP_E_UNKNOWNINTERFACE = 0x80020001;
      //public const uint DISP_E_MEMBERNOTFOUND = 0x80020003;
      //public const uint DISP_E_PARAMNOTFOUND = 0x80020004;
      //public const uint DISP_E_TYPEMISMATCH = 0x80020005;
      //public const uint DISP_E_UNKNOWNNAME = 0x80020006;
      //public const uint DISP_E_NONAMEDARGS = 0x80020007;
      //public const uint DISP_E_BADVARTYPE = 0x80020008;
      //public const uint DISP_E_EXCEPTION = 0x80020009;
      //public const uint DISP_E_OVERFLOW = 0x8002000A;
      //public const uint DISP_E_BADINDEX = 0x8002000B;
      //public const uint DISP_E_UNKNOWNLCID = 0x8002000C;
      //public const uint DISP_E_ARRAYISLOCKED = 0x8002000D;
      //public const uint DISP_E_BADPARAMCOUNT = 0x8002000E;
      //public const uint DISP_E_PARAMNOTOPTIONAL = 0x8002000F;
      //public const uint DISP_E_BADCALLEE = 0x80020010;
      //public const uint DISP_E_NOTACOLLECTION = 0x80020011;
      //public const uint DISP_E_DIVBYZERO = 0x80020012;
      //public const uint DISP_E_BUFFERTOOSMALL = 0x80020013;
      //public const uint TYPE_E_BUFFERTOOSMALL = 0x80028016;
      //public const uint TYPE_E_FIELDNOTFOUND = 0x80028017;
      //public const uint TYPE_E_INVDATAREAD = 0x80028018;
      //public const uint TYPE_E_UNSUPFORMAT = 0x80028019;
      //public const uint TYPE_E_REGISTRYACCESS = 0x8002801C;
      //public const uint TYPE_E_LIBNOTREGISTERED = 0x8002801D;
      //public const uint TYPE_E_UNDEFINEDTYPE = 0x80028027;
      //public const uint TYPE_E_QUALIFIEDNAMEDISALLOWED = 0x80028028;
      //public const uint TYPE_E_INVALIDSTATE = 0x80028029;
      //public const uint TYPE_E_WRONGTYPEKIND = 0x8002802A;
      //public const uint TYPE_E_ELEMENTNOTFOUND = 0x8002802B;
      //public const uint TYPE_E_AMBIGUOUSNAME = 0x8002802C;
      //public const uint TYPE_E_NAMECONFLICT = 0x8002802D;
      //public const uint TYPE_E_UNKNOWNLCID = 0x8002802E;
      //public const uint TYPE_E_DLLFUNCTIONNOTFOUND = 0x8002802F;
      //public const uint TYPE_E_BADMODULEKIND = 0x800288BD;
      //public const uint TYPE_E_SIZETOOBIG = 0x800288C5;
      //public const uint TYPE_E_DUPLICATEID = 0x800288C6;
      //public const uint TYPE_E_INVALIDID = 0x800288CF;
      //public const uint TYPE_E_TYPEMISMATCH = 0x80028CA0;
      //public const uint TYPE_E_OUTOFBOUNDS = 0x80028CA1;
      //public const uint TYPE_E_IOERROR = 0x80028CA2;
      //public const uint TYPE_E_CANTCREATETMPFILE = 0x80028CA3;
      //public const uint TYPE_E_CANTLOADLIBRARY = 0x80029C4A;
      //public const uint TYPE_E_INCONSISTENTPROPFUNCS = 0x80029C83;
      //public const uint TYPE_E_CIRCULARTYPE = 0x80029C84;
      //public const uint STG_E_INVALIDFUNCTION = 0x80030001;
      //public const uint STG_E_FILENOTFOUND = 0x80030002;
      //public const uint STG_E_PATHNOTFOUND = 0x80030003;
      //public const uint STG_E_TOOMANYOPENFILES = 0x80030004;
      //public const uint STG_E_ACCESSDENIED = 0x80030005;
      //public const uint STG_E_INVALIDHANDLE = 0x80030006;
      //public const uint STG_E_INSUFFICIENTMEMORY = 0x80030008;
      //public const uint STG_E_INVALIDPOINTER = 0x80030009;
      //public const uint STG_E_NOMOREFILES = 0x80030012;
      //public const uint STG_E_DISKISWRITEPROTECTED = 0x80030013;
      //public const uint STG_E_SEEKERROR = 0x80030019;
      //public const uint STG_E_WRITEFAULT = 0x8003001D;
      //public const uint STG_E_READFAULT = 0x8003001E;
      //public const uint STG_E_SHAREVIOLATION = 0x80030020;
      //public const uint STG_E_LOCKVIOLATION = 0x80030021;
      //public const uint STG_E_FILEALREADYEXISTS = 0x80030050;
      //public const uint STG_E_INVALIDPARAMETER = 0x80030057;
      //public const uint STG_E_MEDIUMFULL = 0x80030070;
      //public const uint STG_E_PROPSETMISMATCHED = 0x800300F0;
      //public const uint STG_E_ABNORMALAPIEXIT = 0x800300FA;
      //public const uint STG_E_INVALIDHEADER = 0x800300FB;
      //public const uint STG_E_INVALIDNAME = 0x800300FC;
      //public const uint STG_E_UNKNOWN = 0x800300FD;
      //public const uint STG_E_UNIMPLEMENTEDFUNCTION = 0x800300FE;
      //public const uint STG_E_INVALIDFLAG = 0x800300FF;
      //public const uint STG_E_INUSE = 0x80030100;
      //public const uint STG_E_NOTCURRENT = 0x80030101;
      //public const uint STG_E_REVERTED = 0x80030102;
      //public const uint STG_E_CANTSAVE = 0x80030103;
      //public const uint STG_E_OLDFORMAT = 0x80030104;
      //public const uint STG_E_OLDDLL = 0x80030105;
      //public const uint STG_E_SHAREREQUIRED = 0x80030106;
      //public const uint STG_E_NOTFILEBASEDSTORAGE = 0x80030107;
      //public const uint STG_E_EXTANTMARSHALLINGS = 0x80030108;
      //public const uint STG_E_DOCFILECORRUPT = 0x80030109;
      //public const uint STG_E_BADBASEADDRESS = 0x80030110;
      //public const uint STG_E_DOCFILETOOLARGE = 0x80030111;
      //public const uint STG_E_NOTSIMPLEFORMAT = 0x80030112;
      //public const uint STG_E_INCOMPLETE = 0x80030201;
      //public const uint STG_E_TERMINATED = 0x80030202;
      //public const uint STG_S_CONVERTED = 0x00030200;
      //public const uint STG_S_BLOCK = 0x00030201;
      //public const uint STG_S_RETRYNOW = 0x00030202;
      //public const uint STG_S_MONITORING = 0x00030203;
      //public const uint STG_S_MULTIPLEOPENS = 0x00030204;
      //public const uint STG_S_CONSOLIDATIONFAILED = 0x00030205;
      //public const uint STG_S_CANNOTCONSOLIDATE = 0x00030206;
      //public const uint STG_E_STATUS_COPY_PROTECTION_FAILURE = 0x80030305;
      //public const uint STG_E_CSS_AUTHENTICATION_FAILURE = 0x80030306;
      //public const uint STG_E_CSS_KEY_NOT_PRESENT = 0x80030307;
      //public const uint STG_E_CSS_KEY_NOT_ESTABLISHED = 0x80030308;
      //public const uint STG_E_CSS_SCRAMBLED_SECTOR = 0x80030309;
      //public const uint STG_E_CSS_REGION_MISMATCH = 0x8003030A;
      //public const uint STG_E_RESETS_EXHAUSTED = 0x8003030B;
      //public const uint RPC_E_CALL_REJECTED = 0x80010001;
      //public const uint RPC_E_CALL_CANCELED = 0x80010002;
      //public const uint RPC_E_CANTPOST_INSENDCALL = 0x80010003;
      //public const uint RPC_E_CANTCALLOUT_INASYNCCALL = 0x80010004;
      //public const uint RPC_E_CANTCALLOUT_INEXTERNALCALL = 0x80010005;
      //public const uint RPC_E_CONNECTION_TERMINATED = 0x80010006;
      //public const uint RPC_E_SERVER_DIED = 0x80010007;
      //public const uint RPC_E_CLIENT_DIED = 0x80010008;
      //public const uint RPC_E_INVALID_DATAPACKET = 0x80010009;
      //public const uint RPC_E_CANTTRANSMIT_CALL = 0x8001000A;
      //public const uint RPC_E_CLIENT_CANTMARSHAL_DATA = 0x8001000B;
      //public const uint RPC_E_CLIENT_CANTUNMARSHAL_DATA = 0x8001000C;
      //public const uint RPC_E_SERVER_CANTMARSHAL_DATA = 0x8001000D;
      //public const uint RPC_E_SERVER_CANTUNMARSHAL_DATA = 0x8001000E;
      //public const uint RPC_E_INVALID_DATA = 0x8001000F;
      //public const uint RPC_E_INVALID_PARAMETER = 0x80010010;
      //public const uint RPC_E_CANTCALLOUT_AGAIN = 0x80010011;
      //public const uint RPC_E_SERVER_DIED_DNE = 0x80010012;
      //public const uint RPC_E_SYS_CALL_FAILED = 0x80010100;
      //public const uint RPC_E_OUT_OF_RESOURCES = 0x80010101;
      //public const uint RPC_E_ATTEMPTED_MULTITHREAD = 0x80010102;
      //public const uint RPC_E_NOT_REGISTERED = 0x80010103;
      //public const uint RPC_E_FAULT = 0x80010104;
      //public const uint RPC_E_SERVERFAULT = 0x80010105;
      //public const uint RPC_E_CHANGED_MODE = 0x80010106;
      //public const uint RPC_E_INVALIDMETHOD = 0x80010107;
      //public const uint RPC_E_DISCONNECTED = 0x80010108;
      //public const uint RPC_E_RETRY = 0x80010109;
      //public const uint RPC_E_SERVERCALL_RETRYLATER = 0x8001010A;
      //public const uint RPC_E_SERVERCALL_REJECTED = 0x8001010B;
      //public const uint RPC_E_INVALID_CALLDATA = 0x8001010C;
      //public const uint RPC_E_CANTCALLOUT_ININPUTSYNCCALL = 0x8001010D;
      //public const uint RPC_E_WRONG_THREAD = 0x8001010E;
      //public const uint RPC_E_THREAD_NOT_INIT = 0x8001010F;
      //public const uint RPC_E_VERSION_MISMATCH = 0x80010110;
      //public const uint RPC_E_INVALID_HEADER = 0x80010111;
      //public const uint RPC_E_INVALID_EXTENSION = 0x80010112;
      //public const uint RPC_E_INVALID_IPID = 0x80010113;
      //public const uint RPC_E_INVALID_OBJECT = 0x80010114;
      //public const uint RPC_S_CALLPENDING = 0x80010115;
      //public const uint RPC_S_WAITONTIMER = 0x80010116;
      //public const uint RPC_E_CALL_COMPLETE = 0x80010117;
      //public const uint RPC_E_UNSECURE_CALL = 0x80010118;
      //public const uint RPC_E_TOO_LATE = 0x80010119;
      //public const uint RPC_E_NO_GOOD_SECURITY_PACKAGES = 0x8001011A;
      //public const uint RPC_E_ACCESS_DENIED = 0x8001011B;
      //public const uint RPC_E_REMOTE_DISABLED = 0x8001011C;
      //public const uint RPC_E_INVALID_OBJREF = 0x8001011D;
      //public const uint RPC_E_NO_CONTEXT = 0x8001011E;
      //public const uint RPC_E_TIMEOUT = 0x8001011F;
      //public const uint RPC_E_NO_SYNC = 0x80010120;
      //public const uint RPC_E_FULLSIC_REQUIRED = 0x80010121;
      //public const uint RPC_E_INVALID_STD_NAME = 0x80010122;
      //public const uint CO_E_FAILEDTOIMPERSONATE = 0x80010123;
      //public const uint CO_E_FAILEDTOGETSECCTX = 0x80010124;
      //public const uint CO_E_FAILEDTOOPENTHREADTOKEN = 0x80010125;
      //public const uint CO_E_FAILEDTOGETTOKENINFO = 0x80010126;
      //public const uint CO_E_TRUSTEEDOESNTMATCHCLIENT = 0x80010127;
      //public const uint CO_E_FAILEDTOQUERYCLIENTBLANKET = 0x80010128;
      //public const uint CO_E_FAILEDTOSETDACL = 0x80010129;
      //public const uint CO_E_ACCESSCHECKFAILED = 0x8001012A;
      //public const uint CO_E_NETACCESSAPIFAILED = 0x8001012B;
      //public const uint CO_E_WRONGTRUSTEENAMESYNTAX = 0x8001012C;
      //public const uint CO_E_INVALIDSID = 0x8001012D;
      //public const uint CO_E_CONVERSIONFAILED = 0x8001012E;
      //public const uint CO_E_NOMATCHINGSIDFOUND = 0x8001012F;
      //public const uint CO_E_LOOKUPACCSIDFAILED = 0x80010130;
      //public const uint CO_E_NOMATCHINGNAMEFOUND = 0x80010131;
      //public const uint CO_E_LOOKUPACCNAMEFAILED = 0x80010132;
      //public const uint CO_E_SETSERLHNDLFAILED = 0x80010133;
      //public const uint CO_E_FAILEDTOGETWINDIR = 0x80010134;
      //public const uint CO_E_PATHTOOLONG = 0x80010135;
      //public const uint CO_E_FAILEDTOGENUUID = 0x80010136;
      //public const uint CO_E_FAILEDTOCREATEFILE = 0x80010137;
      //public const uint CO_E_FAILEDTOCLOSEHANDLE = 0x80010138;
      //public const uint CO_E_EXCEEDSYSACLLIMIT = 0x80010139;
      //public const uint CO_E_ACESINWRONGORDER = 0x8001013A;
      //public const uint CO_E_INCOMPATIBLESTREAMVERSION = 0x8001013B;
      //public const uint CO_E_FAILEDTOOPENPROCESSTOKEN = 0x8001013C;
      //public const uint CO_E_DECODEFAILED = 0x8001013D;
      //public const uint CO_E_ACNOTINITIALIZED = 0x8001013F;
      //public const uint CO_E_CANCEL_DISABLED = 0x80010140;
      //public const uint RPC_E_UNEXPECTED = 0x8001FFFF;
      //public const uint ERROR_AUDITING_DISABLED = 0xC0090001;
      //public const uint ERROR_ALL_SIDS_FILTERED = 0xC0090002;
      //public const uint NTE_BAD_UID = 0x80090001;
      //public const uint NTE_BAD_HASH = 0x80090002;
      //public const uint NTE_BAD_KEY = 0x80090003;
      //public const uint NTE_BAD_LEN = 0x80090004;
      //public const uint NTE_BAD_DATA = 0x80090005;
      //public const uint NTE_BAD_SIGNATURE = 0x80090006;
      //public const uint NTE_BAD_VER = 0x80090007;
      //public const uint NTE_BAD_ALGID = 0x80090008;
      //public const uint NTE_BAD_FLAGS = 0x80090009;
      //public const uint NTE_BAD_TYPE = 0x8009000A;
      //public const uint NTE_BAD_KEY_STATE = <KEY>;
      //public const uint NTE_BAD_HASH_STATE = 0x8009000C;
      //public const uint NTE_NO_KEY = 0x8009000D;
      //public const uint NTE_NO_MEMORY = 0x8009000E;
      //public const uint NTE_EXISTS = 0x8009000F;
      //public const uint NTE_PERM = 0x80090010;
      //public const uint NTE_NOT_FOUND = 0x80090011;
      //public const uint NTE_DOUBLE_ENCRYPT = 0x80090012;
      //public const uint NTE_BAD_PROVIDER = 0x80090013;
      //public const uint NTE_BAD_PROV_TYPE = 0x80090014;
      //public const uint NTE_BAD_PUBLIC_KEY = 0x80090015;
      //public const uint NTE_BAD_KEYSET = 0x80090016;
      //public const uint NTE_PROV_TYPE_NOT_DEF = 0x80090017;
      //public const uint NTE_PROV_TYPE_ENTRY_BAD = 0x80090018;
      //public const uint NTE_KEYSET_NOT_DEF = 0x80090019;
      //public const uint NTE_KEYSET_ENTRY_BAD = 0x8009001A;
      //public const uint NTE_PROV_TYPE_NO_MATCH = 0x8009001B;
      //public const uint NTE_SIGNATURE_FILE_BAD = 0x8009001C;
      //public const uint NTE_PROVIDER_DLL_FAIL = 0x8009001D;
      //public const uint NTE_PROV_DLL_NOT_FOUND = 0x8009001E;
      //public const uint NTE_BAD_KEYSET_PARAM = 0x8009001F;
      //public const uint NTE_FAIL = 0x80090020;
      //public const uint NTE_SYS_ERR = 0x80090021;
      //public const uint NTE_SILENT_CONTEXT = 0x80090022;
      //public const uint NTE_TOKEN_KEYSET_STORAGE_FULL = 0x80090023;
      //public const uint NTE_TEMPORARY_PROFILE = 0x80090024;
      //public const uint NTE_FIXEDPARAMETER = 0x80090025;
      //public const uint SEC_E_INSUFFICIENT_MEMORY = 0x80090300;
      //public const uint SEC_E_INVALID_HANDLE = 0x80090301;
      //public const uint SEC_E_UNSUPPORTED_FUNCTION = 0x80090302;
      //public const uint SEC_E_TARGET_UNKNOWN = 0x80090303;
      //public const uint SEC_E_INTERNAL_ERROR = 0x80090304;
      //public const uint SEC_E_SECPKG_NOT_FOUND = 0x80090305;
      //public const uint SEC_E_NOT_OWNER = 0x80090306;
      //public const uint SEC_E_CANNOT_INSTALL = 0x80090307;
      //public const uint SEC_E_INVALID_TOKEN = 0x80090308;
      //public const uint SEC_E_CANNOT_PACK = 0x80090309;
      //public const uint SEC_E_QOP_NOT_SUPPORTED = 0x8009030A;
      //public const uint SEC_E_NO_IMPERSONATION = 0x8009030B;
      //public const uint SEC_E_LOGON_DENIED = 0x8009030C;
      //public const uint SEC_E_UNKNOWN_CREDENTIALS = 0x8009030D;
      //public const uint SEC_E_NO_CREDENTIALS = 0x8009030E;
      //public const uint SEC_E_MESSAGE_ALTERED = 0x8009030F;
      //public const uint SEC_E_OUT_OF_SEQUENCE = 0x80090310;
      //public const uint SEC_E_NO_AUTHENTICATING_AUTHORITY = 0x80090311;
      //public const uint SEC_I_CONTINUE_NEEDED = 0x00090312;
      //public const uint SEC_I_COMPLETE_NEEDED = 0x00090313;
      //public const uint SEC_I_COMPLETE_AND_CONTINUE = 0x00090314;
      //public const uint SEC_I_LOCAL_LOGON = 0x00090315;
      //public const uint SEC_E_BAD_PKGID = 0x80090316;
      //public const uint SEC_E_CONTEXT_EXPIRED = 0x80090317;
      //public const uint SEC_I_CONTEXT_EXPIRED = 0x00090317;
      //public const uint SEC_E_INCOMPLETE_MESSAGE = 0x80090318;
      //public const uint SEC_E_INCOMPLETE_CREDENTIALS = 0x80090320;
      //public const uint SEC_E_BUFFER_TOO_SMALL = 0x80090321;
      //public const uint SEC_I_INCOMPLETE_CREDENTIALS = 0x00090320;
      //public const uint SEC_I_RENEGOTIATE = 0x00090321;
      //public const uint SEC_E_WRONG_PRINCIPAL = 0x80090322;
      //public const uint SEC_I_NO_LSA_CONTEXT = 0x00090323;
      //public const uint SEC_E_TIME_SKEW = 0x80090324;
      //public const uint SEC_E_UNTRUSTED_ROOT = 0x80090325;
      //public const uint SEC_E_ILLEGAL_MESSAGE = 0x80090326;
      //public const uint SEC_E_CERT_UNKNOWN = 0x80090327;
      //public const uint SEC_E_CERT_EXPIRED = 0x80090328;
      //public const uint SEC_E_ENCRYPT_FAILURE = 0x80090329;
      //public const uint SEC_E_DECRYPT_FAILURE = 0x80090330;
      //public const uint SEC_E_ALGORITHM_MISMATCH = 0x80090331;
      //public const uint SEC_E_SECURITY_QOS_FAILED = 0x80090332;
      //public const uint SEC_E_UNFINISHED_CONTEXT_DELETED = 0x80090333;
      //public const uint SEC_E_NO_TGT_REPLY = 0x80090334;
      //public const uint SEC_E_NO_IP_ADDRESSES = 0x80090335;
      //public const uint SEC_E_WRONG_CREDENTIAL_HANDLE = 0x80090336;
      //public const uint SEC_E_CRYPTO_SYSTEM_INVALID = 0x80090337;
      //public const uint SEC_E_MAX_REFERRALS_EXCEEDED = 0x80090338;
      //public const uint SEC_E_MUST_BE_KDC = 0x80090339;
      //public const uint SEC_E_STRONG_CRYPTO_NOT_SUPPORTED = 0x8009033A;
      //public const uint SEC_E_TOO_MANY_PRINCIPALS = 0x8009033B;
      //public const uint SEC_E_NO_PA_DATA = 0x8009033C;
      //public const uint SEC_E_PKINIT_NAME_MISMATCH = 0x8009033D;
      //public const uint SEC_E_SMARTCARD_LOGON_REQUIRED = 0x8009033E;
      //public const uint SEC_E_SHUTDOWN_IN_PROGRESS = 0x8009033F;
      //public const uint SEC_E_KDC_INVALID_REQUEST = 0x80090340;
      //public const uint SEC_E_KDC_UNABLE_TO_REFER = 0x80090341;
      //public const uint SEC_E_KDC_UNKNOWN_ETYPE = 0x80090342;
      //public const uint SEC_E_UNSUPPORTED_PREAUTH = 0x80090343;
      //public const uint SEC_E_DELEGATION_REQUIRED = 0x80090345;
      //public const uint SEC_E_BAD_BINDINGS = 0x80090346;
      //public const uint SEC_E_MULTIPLE_ACCOUNTS = 0x80090347;
      //public const uint SEC_E_NO_KERB_KEY = 0x80090348;
      //public const uint SEC_E_CERT_WRONG_USAGE = 0x80090349;
      //public const uint SEC_E_DOWNGRADE_DETECTED = 0x80090350;
      //public const uint SEC_E_SMARTCARD_CERT_REVOKED = 0x80090351;
      //public const uint SEC_E_ISSUING_CA_UNTRUSTED = 0x80090352;
      //public const uint SEC_E_REVOCATION_OFFLINE_C = 0x80090353;
      //public const uint SEC_E_PKINIT_CLIENT_FAILURE = 0x80090354;
      //public const uint SEC_E_SMARTCARD_CERT_EXPIRED = 0x80090355;
      //public const uint SEC_E_NO_S4U_PROT_SUPPORT = 0x80090356;
      //public const uint SEC_E_CROSSREALM_DELEGATION_FAILURE = 0x80090357;
      //public const uint SEC_E_REVOCATION_OFFLINE_KDC = 0x80090358;
      //public const uint SEC_E_ISSUING_CA_UNTRUSTED_KDC = 0x80090359;
      //public const uint SEC_E_KDC_CERT_EXPIRED = 0x8009035A;
      //public const uint SEC_E_KDC_CERT_REVOKED = 0x8009035B;
      //public const uint SEC_E_NO_SPM = SEC_E_INTERNAL_ERROR;
      //public const uint SEC_E_NOT_SUPPORTED = SEC_E_UNSUPPORTED_FUNCTION;
      //public const uint CRYPT_E_MSG_ERROR = 0x80091001;
      //public const uint CRYPT_E_UNKNOWN_ALGO = 0x80091002;
      //public const uint CRYPT_E_OID_FORMAT = 0x80091003;
      //public const uint CRYPT_E_INVALID_MSG_TYPE = 0x80091004;
      //public const uint CRYPT_E_UNEXPECTED_ENCODING = 0x80091005;
      //public const uint CRYPT_E_AUTH_ATTR_MISSING = 0x80091006;
      //public const uint CRYPT_E_HASH_VALUE = 0x80091007;
      //public const uint CRYPT_E_INVALID_INDEX = 0x80091008;
      //public const uint CRYPT_E_ALREADY_DECRYPTED = 0x80091009;
      //public const uint CRYPT_E_NOT_DECRYPTED = 0x8009100A;
      //public const uint CRYPT_E_RECIPIENT_NOT_FOUND = 0x8009100B;
      //public const uint CRYPT_E_CONTROL_TYPE = 0x8009100C;
      //public const uint CRYPT_E_ISSUER_SERIALNUMBER = 0x8009100D;
      //public const uint CRYPT_E_SIGNER_NOT_FOUND = 0x8009100E;
      //public const uint CRYPT_E_ATTRIBUTES_MISSING = 0x8009100F;
      //public const uint CRYPT_E_STREAM_MSG_NOT_READY = 0x80091010;
      //public const uint CRYPT_E_STREAM_INSUFFICIENT_DATA = 0x80091011;
      //public const uint CRYPT_I_NEW_PROTECTION_REQUIRED = 0x00091012;
      //public const uint CRYPT_E_BAD_LEN = 0x80092001;
      //public const uint CRYPT_E_BAD_ENCODE = 0x80092002;
      //public const uint CRYPT_E_FILE_ERROR = 0x80092003;
      //public const uint CRYPT_E_NOT_FOUND = 0x80092004;
      //public const uint CRYPT_E_EXISTS = 0x80092005;
      //public const uint CRYPT_E_NO_PROVIDER = 0x80092006;
      //public const uint CRYPT_E_SELF_SIGNED = 0x80092007;
      //public const uint CRYPT_E_DELETED_PREV = 0x80092008;
      //public const uint CRYPT_E_NO_MATCH = 0x80092009;
      //public const uint CRYPT_E_UNEXPECTED_MSG_TYPE = 0x8009200A;
      //public const uint CRYPT_E_NO_KEY_PROPERTY = 0x8009200B;
      //public const uint CRYPT_E_NO_DECRYPT_CERT = 0x8009200C;
      //public const uint CRYPT_E_BAD_MSG = 0x8009200D;
      //public const uint CRYPT_E_NO_SIGNER = 0x8009200E;
      //public const uint CRYPT_E_PENDING_CLOSE = 0x8009200F;
      //public const uint CRYPT_E_REVOKED = 0x80092010;
      //public const uint CRYPT_E_NO_REVOCATION_DLL = 0x80092011;
      //public const uint CRYPT_E_NO_REVOCATION_CHECK = 0x80092012;
      //public const uint CRYPT_E_REVOCATION_OFFLINE = 0x80092013;
      //public const uint CRYPT_E_NOT_IN_REVOCATION_DATABASE = 0x80092014;
      //public const uint CRYPT_E_INVALID_NUMERIC_STRING = 0x80092020;
      //public const uint CRYPT_E_INVALID_PRINTABLE_STRING = 0x80092021;
      //public const uint CRYPT_E_INVALID_IA5_STRING = 0x80092022;
      //public const uint CRYPT_E_INVALID_X500_STRING = 0x80092023;
      //public const uint CRYPT_E_NOT_CHAR_STRING = 0x80092024;
      //public const uint CRYPT_E_FILERESIZED = 0x80092025;
      //public const uint CRYPT_E_SECURITY_SETTINGS = 0x80092026;
      //public const uint CRYPT_E_NO_VERIFY_USAGE_DLL = 0x80092027;
      //public const uint CRYPT_E_NO_VERIFY_USAGE_CHECK = 0x80092028;
      //public const uint CRYPT_E_VERIFY_USAGE_OFFLINE = 0x80092029;
      //public const uint CRYPT_E_NOT_IN_CTL = 0x8009202A;
      //public const uint CRYPT_E_NO_TRUSTED_SIGNER = 0x8009202B;
      //public const uint CRYPT_E_MISSING_PUBKEY_PARA = 0x8009202C;
      //public const uint CRYPT_E_OSS_ERROR = 0x80093000;
      //public const uint OSS_MORE_BUF = 0x80093001;
      //public const uint OSS_NEGATIVE_longEGER = 0x80093002;
      //public const uint OSS_PDU_RANGE = 0x80093003;
      //public const uint OSS_MORE_INPUT = 0x80093004;
      //public const uint OSS_DATA_ERROR = 0x80093005;
      //public const uint OSS_BAD_ARG = 0x80093006;
      //public const uint OSS_BAD_VERSION = 0x80093007;
      //public const uint OSS_OUT_MEMORY = 0x80093008;
      //public const uint OSS_PDU_MISMATCH = 0x80093009;
      //public const uint OSS_LIMITED = 0x8009300A;
      //public const uint OSS_BAD_PTR = 0x8009300B;
      //public const uint OSS_BAD_TIME = 0x8009300C;
      //public const uint OSS_INDEFINITE_NOT_SUPPORTED = 0x8009300D;
      //public const uint OSS_MEM_ERROR = 0x8009300E;
      //public const uint OSS_BAD_TABLE = 0x8009300F;
      //public const uint OSS_TOO_LONG = 0x80093010;
      //public const uint OSS_CONSTRAINT_VIOLATED = 0x80093011;
      //public const uint OSS_FATAL_ERROR = 0x80093012;
      //public const uint OSS_ACCESS_SERIALIZATION_ERROR = 0x80093013;
      //public const uint OSS_NULL_TBL = 0x80093014;
      //public const uint OSS_NULL_FCN = 0x80093015;
      //public const uint OSS_BAD_ENCRULES = 0x80093016;
      //public const uint OSS_UNAVAIL_ENCRULES = 0x80093017;
      //public const uint OSS_CANT_OPEN_TRACE_WINDOW = 0x80093018;
      //public const uint OSS_UNIMPLEMENTED = 0x80093019;
      //public const uint OSS_OID_DLL_NOT_LINKED = 0x8009301A;
      //public const uint OSS_CANT_OPEN_TRACE_FILE = 0x8009301B;
      //public const uint OSS_TRACE_FILE_ALREADY_OPEN = 0x8009301C;
      //public const uint OSS_TABLE_MISMATCH = 0x8009301D;
      //public const uint OSS_TYPE_NOT_SUPPORTED = 0x8009301E;
      //public const uint OSS_REAL_DLL_NOT_LINKED = 0x8009301F;
      //public const uint OSS_REAL_CODE_NOT_LINKED = 0x80093020;
      //public const uint OSS_OUT_OF_RANGE = 0x80093021;
      //public const uint OSS_COPIER_DLL_NOT_LINKED = 0x80093022;
      //public const uint OSS_CONSTRAINT_DLL_NOT_LINKED = 0x80093023;
      //public const uint OSS_COMPARATOR_DLL_NOT_LINKED = 0x80093024;
      //public const uint OSS_COMPARATOR_CODE_NOT_LINKED = 0x80093025;
      //public const uint OSS_MEM_MGR_DLL_NOT_LINKED = 0x80093026;
      //public const uint OSS_PDV_DLL_NOT_LINKED = 0x80093027;
      //public const uint OSS_PDV_CODE_NOT_LINKED = 0x80093028;
      //public const uint OSS_API_DLL_NOT_LINKED = 0x80093029;
      //public const uint OSS_BERDER_DLL_NOT_LINKED = 0x8009302A;
      //public const uint OSS_PER_DLL_NOT_LINKED = 0x8009302B;
      //public const uint OSS_OPEN_TYPE_ERROR = 0x8009302C;
      //public const uint OSS_MUTEX_NOT_CREATED = 0x8009302D;
      //public const uint OSS_CANT_CLOSE_TRACE_FILE = 0x8009302E;
      //public const uint CRYPT_E_ASN1_ERROR = 0x80093100;
      //public const uint CRYPT_E_ASN1_INTERNAL = 0x80093101;
      //public const uint CRYPT_E_ASN1_EOD = 0x80093102;
      //public const uint CRYPT_E_ASN1_CORRUPT = 0x80093103;
      //public const uint CRYPT_E_ASN1_LARGE = 0x80093104;
      //public const uint CRYPT_E_ASN1_CONSTRAINT = 0x80093105;
      //public const uint CRYPT_E_ASN1_MEMORY = 0x80093106;
      //public const uint CRYPT_E_ASN1_OVERFLOW = 0x80093107;
      //public const uint CRYPT_E_ASN1_BADPDU = 0x80093108;
      //public const uint CRYPT_E_ASN1_BADARGS = 0x80093109;
      //public const uint CRYPT_E_ASN1_BADREAL = 0x8009310A;
      //public const uint CRYPT_E_ASN1_BADTAG = 0x8009310B;
      //public const uint CRYPT_E_ASN1_CHOICE = 0x8009310C;
      //public const uint CRYPT_E_ASN1_RULE = 0x8009310D;
      //public const uint CRYPT_E_ASN1_UTF8 = 0x8009310E;
      //public const uint CRYPT_E_ASN1_PDU_TYPE = 0x80093133;
      //public const uint CRYPT_E_ASN1_NYI = 0x80093134;
      //public const uint CRYPT_E_ASN1_EXTENDED = 0x80093201;
      //public const uint CRYPT_E_ASN1_NOEOD = 0x80093202;
      //public const uint CERTSRV_E_BAD_REQUESTSUBJECT = 0x80094001;
      //public const uint CERTSRV_E_NO_REQUEST = 0x80094002;
      //public const uint CERTSRV_E_BAD_REQUESTSTATUS = 0x80094003;
      //public const uint CERTSRV_E_PROPERTY_EMPTY = 0x80094004;
      //public const uint CERTSRV_E_INVALID_CA_CERTIFICATE = 0x80094005;
      //public const uint CERTSRV_E_SERVER_SUSPENDED = 0x80094006;
      //public const uint CERTSRV_E_ENCODING_LENGTH = 0x80094007;
      //public const uint CERTSRV_E_ROLECONFLICT = 0x80094008;
      //public const uint CERTSRV_E_RESTRICTEDOFFICER = 0x80094009;
      //public const uint CERTSRV_E_KEY_ARCHIVAL_NOT_CONFIGURED = 0x8009400A;
      //public const uint CERTSRV_E_NO_VALID_KRA = 0x8009400B;
      //public const uint CERTSRV_E_BAD_REQUEST_KEY_ARCHIVAL = 0x8009400C;
      //public const uint CERTSRV_E_NO_CAADMIN_DEFINED = 0x8009400D;
      //public const uint CERTSRV_E_BAD_RENEWAL_CERT_ATTRIBUTE = 0x8009400E;
      //public const uint CERTSRV_E_NO_DB_SESSIONS = 0x8009400F;
      //public const uint CERTSRV_E_ALIGNMENT_FAULT = 0x80094010;
      //public const uint CERTSRV_E_ENROLL_DENIED = 0x80094011;
      //public const uint CERTSRV_E_TEMPLATE_DENIED = 0x80094012;
      //public const uint CERTSRV_E_DOWNLEVEL_DC_SSL_OR_UPGRADE = 0x80094013;
      //public const uint CERTSRV_E_UNSUPPORTED_CERT_TYPE = 0x80094800;
      //public const uint CERTSRV_E_NO_CERT_TYPE = 0x80094801;
      //public const uint CERTSRV_E_TEMPLATE_CONFLICT = 0x80094802;
      //public const uint CERTSRV_E_SUBJECT_ALT_NAME_REQUIRED = 0x80094803;
      //public const uint CERTSRV_E_ARCHIVED_KEY_REQUIRED = 0x80094804;
      //public const uint CERTSRV_E_SMIME_REQUIRED = 0x80094805;
      //public const uint CERTSRV_E_BAD_RENEWAL_SUBJECT = 0x80094806;
      //public const uint CERTSRV_E_BAD_TEMPLATE_VERSION = 0x80094807;
      //public const uint CERTSRV_E_TEMPLATE_POLICY_REQUIRED = 0x80094808;
      //public const uint CERTSRV_E_SIGNATURE_POLICY_REQUIRED = 0x80094809;
      //public const uint CERTSRV_E_SIGNATURE_COUNT = 0x8009480A;
      //public const uint CERTSRV_E_SIGNATURE_REJECTED = 0x8009480B;
      //public const uint CERTSRV_E_ISSUANCE_POLICY_REQUIRED = 0x8009480C;
      //public const uint CERTSRV_E_SUBJECT_UPN_REQUIRED = 0x8009480D;
      //public const uint CERTSRV_E_SUBJECT_DIRECTORY_GUID_REQUIRED = 0x8009480E;
      //public const uint CERTSRV_E_SUBJECT_DNS_REQUIRED = 0x8009480F;
      //public const uint CERTSRV_E_ARCHIVED_KEY_UNEXPECTED = 0x80094810;
      //public const uint CERTSRV_E_KEY_LENGTH = 0x80094811;
      //public const uint CERTSRV_E_SUBJECT_EMAIL_REQUIRED = 0x80094812;
      //public const uint CERTSRV_E_UNKNOWN_CERT_TYPE = 0x80094813;
      //public const uint CERTSRV_E_CERT_TYPE_OVERLAP = 0x80094814;
      //public const uint XENROLL_E_KEY_NOT_EXPORTABLE = 0x80095000;
      //public const uint XENROLL_E_CANNOT_ADD_ROOT_CERT = 0x80095001;
      //public const uint XENROLL_E_RESPONSE_KA_HASH_NOT_FOUND = 0x80095002;
      //public const uint XENROLL_E_RESPONSE_UNEXPECTED_KA_HASH = 0x80095003;
      //public const uint XENROLL_E_RESPONSE_KA_HASH_MISMATCH = 0x80095004;
      //public const uint XENROLL_E_KEYSPEC_SMIME_MISMATCH = 0x80095005;
      //public const uint TRUST_E_SYSTEM_ERROR = 0x80096001;
      //public const uint TRUST_E_NO_SIGNER_CERT = 0x80096002;
      //public const uint TRUST_E_COUNTER_SIGNER = 0x80096003;
      //public const uint TRUST_E_CERT_SIGNATURE = 0x80096004;
      //public const uint TRUST_E_TIME_STAMP = 0x80096005;
      //public const uint TRUST_E_BAD_DIGEST = 0x80096010;
      //public const uint TRUST_E_BASIC_CONSTRAINTS = 0x80096019;
      //public const uint TRUST_E_FINANCIAL_CRITERIA = 0x8009601E;
      //public const uint MSSIPOTF_E_OUTOFMEMRANGE = 0x80097001;
      //public const uint MSSIPOTF_E_CANTGETOBJECT = 0x80097002;
      //public const uint MSSIPOTF_E_NOHEADTABLE = 0x80097003;
      //public const uint MSSIPOTF_E_BAD_MAGICNUMBER = 0x80097004;
      //public const uint MSSIPOTF_E_BAD_OFFSET_TABLE = 0x80097005;
      //public const uint MSSIPOTF_E_TABLE_TAGORDER = 0x80097006;
      //public const uint MSSIPOTF_E_TABLE_LONGWORD = 0x80097007;
      //public const uint MSSIPOTF_E_BAD_FIRST_TABLE_PLACEMENT = 0x80097008;
      //public const uint MSSIPOTF_E_TABLES_OVERLAP = 0x80097009;
      //public const uint MSSIPOTF_E_TABLE_PADBYTES = 0x8009700A;
      //public const uint MSSIPOTF_E_FILETOOSMALL = 0x8009700B;
      //public const uint MSSIPOTF_E_TABLE_CHECKSUM = 0x8009700C;
      //public const uint MSSIPOTF_E_FILE_CHECKSUM = 0x8009700D;
      //public const uint MSSIPOTF_E_FAILED_POLICY = 0x80097010;
      //public const uint MSSIPOTF_E_FAILED_HINTS_CHECK = 0x80097011;
      //public const uint MSSIPOTF_E_NOT_OPENTYPE = 0x80097012;
      //public const uint MSSIPOTF_E_FILE = 0x80097013;
      //public const uint MSSIPOTF_E_CRYPT = 0x80097014;
      //public const uint MSSIPOTF_E_BADVERSION = 0x80097015;
      //public const uint MSSIPOTF_E_DSIG_STRUCTURE = 0x80097016;
      //public const uint MSSIPOTF_E_PCONST_CHECK = 0x80097017;
      //public const uint MSSIPOTF_E_STRUCTURE = 0x80097018;
      //public const uint NTE_OP_OK = 0;
      //public const uint TRUST_E_PROVIDER_UNKNOWN = 0x800B0001;
      //public const uint TRUST_E_ACTION_UNKNOWN = 0x800B0002;
      //public const uint TRUST_E_SUBJECT_FORM_UNKNOWN = 0x800B0003;
      //public const uint TRUST_E_SUBJECT_NOT_TRUSTED = 0x800B0004;
      //public const uint DIGSIG_E_ENCODE = 0x800B0005;
      //public const uint DIGSIG_E_DECODE = 0x800B0006;
      //public const uint DIGSIG_E_EXTENSIBILITY = 0x800B0007;
      //public const uint DIGSIG_E_CRYPTO = 0x800B0008;
      //public const uint PERSIST_E_SIZEDEFINITE = 0x800B0009;
      //public const uint PERSIST_E_SIZEINDEFINITE = 0x800B000A;
      //public const uint PERSIST_E_NOTSELFSIZING = 0x800B000B;
      //public const uint TRUST_E_NOSIGNATURE = 0x800B0100;
      //public const uint CERT_E_EXPIRED = 0x800B0101;
      //public const uint CERT_E_VALIDITYPERIODNESTING = 0x800B0102;
      //public const uint CERT_E_ROLE = 0x800B0103;
      //public const uint CERT_E_PATHLENCONST = 0x800B0104;
      //public const uint CERT_E_CRITICAL = 0x800B0105;
      //public const uint CERT_E_PURPOSE = 0x800B0106;
      //public const uint CERT_E_ISSUERCHAINING = 0x800B0107;
      //public const uint CERT_E_MALFORMED = 0x800B0108;
      //public const uint CERT_E_UNTRUSTEDROOT = 0x800B0109;
      //public const uint CERT_E_CHAINING = 0x800B010A;
      //public const uint TRUST_E_FAIL = 0x800B010B;
      //public const uint CERT_E_REVOKED = 0x800B010C;
      //public const uint CERT_E_UNTRUSTEDTESTROOT = 0x800B010D;
      //public const uint CERT_E_REVOCATION_FAILURE = 0x800B010E;
      //public const uint CERT_E_CN_NO_MATCH = 0x800B010F;
      //public const uint CERT_E_WRONG_USAGE = 0x800B0110;
      //public const uint TRUST_E_EXPLICIT_DISTRUST = 0x800B0111;
      //public const uint CERT_E_UNTRUSTEDCA = 0x800B0112;
      //public const uint CERT_E_INVALID_POLICY = 0x800B0113;
      //public const uint CERT_E_INVALID_NAME = 0x800B0114;
      //public const uint SPAPI_E_EXPECTED_SECTION_NAME = 0x800F0000;
      //public const uint SPAPI_E_BAD_SECTION_NAME_LINE = 0x800F0001;
      //public const uint SPAPI_E_SECTION_NAME_TOO_LONG = 0x800F0002;
      //public const uint SPAPI_E_GENERAL_SYNTAX = 0x800F0003;
      //public const uint SPAPI_E_WRONG_INF_STYLE = 0x800F0100;
      //public const uint SPAPI_E_SECTION_NOT_FOUND = 0x800F0101;
      //public const uint SPAPI_E_LINE_NOT_FOUND = 0x800F0102;
      //public const uint SPAPI_E_NO_BACKUP = 0x800F0103;
      //public const uint SPAPI_E_NO_ASSOCIATED_CLASS = 0x800F0200;
      //public const uint SPAPI_E_CLASS_MISMATCH = 0x800F0201;
      //public const uint SPAPI_E_DUPLICATE_FOUND = 0x800F0202;
      //public const uint SPAPI_E_NO_DRIVER_SELECTED = 0x800F0203;
      //public const uint SPAPI_E_KEY_DOES_NOT_EXIST = <KEY>;
      //public const uint SPAPI_E_INVALID_DEVINST_NAME = 0x800F0205;
      //public const uint SPAPI_E_INVALID_CLASS = 0x800F0206;
      //public const uint SPAPI_E_DEVINST_ALREADY_EXISTS = 0x800F0207;
      //public const uint SPAPI_E_DEVINFO_NOT_REGISTERED = 0x800F0208;
      //public const uint SPAPI_E_INVALID_REG_PROPERTY = 0x800F0209;
      //public const uint SPAPI_E_NO_INF = 0x800F020A;
      //public const uint SPAPI_E_NO_SUCH_DEVINST = 0x800F020B;
      //public const uint SPAPI_E_CANT_LOAD_CLASS_ICON = 0x800F020C;
      //public const uint SPAPI_E_INVALID_CLASS_INSTALLER = 0x800F020D;
      //public const uint SPAPI_E_DI_DO_DEFAULT = 0x800F020E;
      //public const uint SPAPI_E_DI_NOFILECOPY = 0x800F020F;
      //public const uint SPAPI_E_INVALID_HWPROFILE = 0x800F0210;
      //public const uint SPAPI_E_NO_DEVICE_SELECTED = 0x800F0211;
      //public const uint SPAPI_E_DEVINFO_LIST_LOCKED = 0x800F0212;
      //public const uint SPAPI_E_DEVINFO_DATA_LOCKED = 0x800F0213;
      //public const uint SPAPI_E_DI_BAD_PATH = 0x800F0214;
      //public const uint SPAPI_E_NO_CLASSINSTALL_PARAMS = 0x800F0215;
      //public const uint SPAPI_E_FILEQUEUE_LOCKED = 0x800F0216;
      //public const uint SPAPI_E_BAD_SERVICE_INSTALLSECT = 0x800F0217;
      //public const uint SPAPI_E_NO_CLASS_DRIVER_LIST = 0x800F0218;
      //public const uint SPAPI_E_NO_ASSOCIATED_SERVICE = 0x800F0219;
      //public const uint SPAPI_E_NO_DEFAULT_DEVICE_INTERFACE = 0x800F021A;
      //public const uint SPAPI_E_DEVICE_INTERFACE_ACTIVE = 0x800F021B;
      //public const uint SPAPI_E_DEVICE_INTERFACE_REMOVED = 0x800F021C;
      //public const uint SPAPI_E_BAD_INTERFACE_INSTALLSECT = 0x800F021D;
      //public const uint SPAPI_E_NO_SUCH_INTERFACE_CLASS = 0x800F021E;
      //public const uint SPAPI_E_INVALID_REFERENCE_STRING = 0x800F021F;
      //public const uint SPAPI_E_INVALID_MACHINENAME = 0x800F0220;
      //public const uint SPAPI_E_REMOTE_COMM_FAILURE = 0x800F0221;
      //public const uint SPAPI_E_MACHINE_UNAVAILABLE = 0x800F0222;
      //public const uint SPAPI_E_NO_CONFIGMGR_SERVICES = 0x800F0223;
      //public const uint SPAPI_E_INVALID_PROPPAGE_PROVIDER = 0x800F0224;
      //public const uint SPAPI_E_NO_SUCH_DEVICE_INTERFACE = 0x800F0225;
      //public const uint SPAPI_E_DI_POSTPROCESSING_REQUIRED = 0x800F0226;
      //public const uint SPAPI_E_INVALID_COINSTALLER = 0x800F0227;
      //public const uint SPAPI_E_NO_COMPAT_DRIVERS = 0x800F0228;
      //public const uint SPAPI_E_NO_DEVICE_ICON = 0x800F0229;
      //public const uint SPAPI_E_INVALID_INF_LOGCONFIG = 0x800F022A;
      //public const uint SPAPI_E_DI_DONT_INSTALL = 0x800F022B;
      //public const uint SPAPI_E_INVALID_FILTER_DRIVER = 0x800F022C;
      //public const uint SPAPI_E_NON_WINDOWS_NT_DRIVER = 0x800F022D;
      //public const uint SPAPI_E_NON_WINDOWS_DRIVER = 0x800F022E;
      //public const uint SPAPI_E_NO_CATALOG_FOR_OEM_INF = 0x800F022F;
      //public const uint SPAPI_E_DEVINSTALL_QUEUE_NONNATIVE = 0x800F0230;
      //public const uint SPAPI_E_NOT_DISABLEABLE = 0x800F0231;
      //public const uint SPAPI_E_CANT_REMOVE_DEVINST = 0x800F0232;
      //public const uint SPAPI_E_INVALID_TARGET = 0x800F0233;
      //public const uint SPAPI_E_DRIVER_NONNATIVE = 0x800F0234;
      //public const uint SPAPI_E_IN_WOW64 = 0x800F0235;
      //public const uint SPAPI_E_SET_SYSTEM_RESTORE_POINT = 0x800F0236;
      //public const uint SPAPI_E_INCORRECTLY_COPIED_INF = 0x800F0237;
      //public const uint SPAPI_E_SCE_DISABLED = 0x800F0238;
      //public const uint SPAPI_E_UNKNOWN_EXCEPTION = 0x800F0239;
      //public const uint SPAPI_E_PNP_REGISTRY_ERROR = 0x800F023A;
      //public const uint SPAPI_E_REMOTE_REQUEST_UNSUPPORTED = 0x800F023B;
      //public const uint SPAPI_E_NOT_AN_INSTALLED_OEM_INF = 0x800F023C;
      //public const uint SPAPI_E_INF_IN_USE_BY_DEVICES = 0x800F023D;
      //public const uint SPAPI_E_DI_FUNCTION_OBSOLETE = 0x800F023E;
      //public const uint SPAPI_E_NO_AUTHENTICODE_CATALOG = 0x800F023F;
      //public const uint SPAPI_E_AUTHENTICODE_DISALLOWED = 0x800F0240;
      //public const uint SPAPI_E_AUTHENTICODE_TRUSTED_PUBLISHER = 0x800F0241;
      //public const uint SPAPI_E_AUTHENTICODE_TRUST_NOT_ESTABLISHED = 0x800F0242;
      //public const uint SPAPI_E_AUTHENTICODE_PUBLISHER_NOT_TRUSTED = 0x800F0243;
      //public const uint SPAPI_E_SIGNATURE_OSATTRIBUTE_MISMATCH = 0x800F0244;
      //public const uint SPAPI_E_ONLY_VALIDATE_VIA_AUTHENTICODE = 0x800F0245;
      //public const uint SPAPI_E_UNRECOVERABLE_STACK_OVERFLOW = 0x800F0300;
      //public const uint SPAPI_E_ERROR_NOT_INSTALLED = 0x800F1000;
      //public const uint SCARD_S_SUCCESS = NO_ERROR;
      //public const uint SCARD_F_INTERNAL_ERROR = 0x80100001;
      //public const uint SCARD_E_CANCELLED = 0x80100002;
      //public const uint SCARD_E_INVALID_HANDLE = 0x80100003;
      //public const uint SCARD_E_INVALID_PARAMETER = 0x80100004;
      //public const uint SCARD_E_INVALID_TARGET = 0x80100005;
      //public const uint SCARD_E_NO_MEMORY = 0x80100006;
      //public const uint SCARD_F_WAITED_TOO_LONG = 0x80100007;
      //public const uint SCARD_E_INSUFFICIENT_BUFFER = 0x80100008;
      //public const uint SCARD_E_UNKNOWN_READER = 0x80100009;
      //public const uint SCARD_E_TIMEOUT = 0x8010000A;
      //public const uint SCARD_E_SHARING_VIOLATION = 0x8010000B;
      //public const uint SCARD_E_NO_SMARTCARD = 0x8010000C;
      //public const uint SCARD_E_UNKNOWN_CARD = 0x8010000D;
      //public const uint SCARD_E_CANT_DISPOSE = 0x8010000E;
      //public const uint SCARD_E_PROTO_MISMATCH = 0x8010000F;
      //public const uint SCARD_E_NOT_READY = 0x80100010;
      //public const uint SCARD_E_INVALID_VALUE = 0x80100011;
      //public const uint SCARD_E_SYSTEM_CANCELLED = 0x80100012;
      //public const uint SCARD_F_COMM_ERROR = 0x80100013;
      //public const uint SCARD_F_UNKNOWN_ERROR = 0x80100014;
      //public const uint SCARD_E_INVALID_ATR = 0x80100015;
      //public const uint SCARD_E_NOT_TRANSACTED = 0x80100016;
      //public const uint SCARD_E_READER_UNAVAILABLE = 0x80100017;
      //public const uint SCARD_P_SHUTDOWN = 0x80100018;
      //public const uint SCARD_E_PCI_TOO_SMALL = 0x80100019;
      //public const uint SCARD_E_READER_UNSUPPORTED = 0x8010001A;
      //public const uint SCARD_E_DUPLICATE_READER = 0x8010001B;
      //public const uint SCARD_E_CARD_UNSUPPORTED = 0x8010001C;
      //public const uint SCARD_E_NO_SERVICE = 0x8010001D;
      //public const uint SCARD_E_SERVICE_STOPPED = 0x8010001E;
      //public const uint SCARD_E_UNEXPECTED = 0x8010001F;
      //public const uint SCARD_E_ICC_INSTALLATION = 0x80100020;
      //public const uint SCARD_E_ICC_CREATEORDER = 0x80100021;
      //public const uint SCARD_E_UNSUPPORTED_FEATURE = 0x80100022;
      //public const uint SCARD_E_DIR_NOT_FOUND = 0x80100023;
      //public const uint SCARD_E_FILE_NOT_FOUND = 0x80100024;
      //public const uint SCARD_E_NO_DIR = 0x80100025;
      //public const uint SCARD_E_NO_FILE = 0x80100026;
      //public const uint SCARD_E_NO_ACCESS = 0x80100027;
      //public const uint SCARD_E_WRITE_TOO_MANY = 0x80100028;
      //public const uint SCARD_E_BAD_SEEK = 0x80100029;
      //public const uint SCARD_E_INVALID_CHV = 0x8010002A;
      //public const uint SCARD_E_UNKNOWN_RES_MNG = 0x8010002B;
      //public const uint SCARD_E_NO_SUCH_CERTIFICATE = 0x8010002C;
      //public const uint SCARD_E_CERTIFICATE_UNAVAILABLE = 0x8010002D;
      //public const uint SCARD_E_NO_READERS_AVAILABLE = 0x8010002E;
      //public const uint SCARD_E_COMM_DATA_LOST = 0x8010002F;
      //public const uint SCARD_E_NO_KEY_CONTAINER = 0x80100030;
      //public const uint SCARD_E_SERVER_TOO_BUSY = 0x80100031;
      //public const uint SCARD_W_UNSUPPORTED_CARD = 0x80100065;
      //public const uint SCARD_W_UNRESPONSIVE_CARD = 0x80100066;
      //public const uint SCARD_W_UNPOWERED_CARD = 0x80100067;
      //public const uint SCARD_W_RESET_CARD = 0x80100068;
      //public const uint SCARD_W_REMOVED_CARD = 0x80100069;
      //public const uint SCARD_W_SECURITY_VIOLATION = 0x8010006A;
      //public const uint SCARD_W_WRONG_CHV = 0x8010006B;
      //public const uint SCARD_W_CHV_BLOCKED = 0x8010006C;
      //public const uint SCARD_W_EOF = 0x8010006D;
      //public const uint SCARD_W_CANCELLED_BY_USER = 0x8010006E;
      //public const uint SCARD_W_CARD_NOT_AUTHENTICATED = 0x8010006F;
      //public const uint COMADMIN_E_OBJECTERRORS = 0x80110401;
      //public const uint COMADMIN_E_OBJECTINVALID = 0x80110402;
      //public const uint COMADMIN_E_KEYMISSING = 0x80110403;
      //public const uint COMADMIN_E_ALREADYINSTALLED = 0x80110404;
      //public const uint COMADMIN_E_APP_FILE_WRITEFAIL = 0x80110407;
      //public const uint COMADMIN_E_APP_FILE_READFAIL = 0x80110408;
      //public const uint COMADMIN_E_APP_FILE_VERSION = 0x80110409;
      //public const uint COMADMIN_E_BADPATH = 0x8011040A;
      //public const uint COMADMIN_E_APPLICATIONEXISTS = 0x8011040B;
      //public const uint COMADMIN_E_ROLEEXISTS = 0x8011040C;
      //public const uint COMADMIN_E_CANTCOPYFILE = 0x8011040D;
      //public const uint COMADMIN_E_NOUSER = 0x8011040F;
      //public const uint COMADMIN_E_INVALIDUSERIDS = 0x80110410;
      //public const uint COMADMIN_E_NOREGISTRYCLSID = 0x80110411;
      //public const uint COMADMIN_E_BADREGISTRYPROGID = 0x80110412;
      //public const uint COMADMIN_E_AUTHENTICATIONLEVEL = 0x80110413;
      //public const uint COMADMIN_E_USERPASSWDNOTVALID = <PASSWORD>;
      //public const uint COMADMIN_E_CLSIDORIIDMISMATCH = 0x80110418;
      //public const uint COMADMIN_E_REMOTEINTERFACE = 0x80110419;
      //public const uint COMADMIN_E_DLLREGISTERSERVER = 0x8011041A;
      //public const uint COMADMIN_E_NOSERVERSHARE = 0x8011041B;
      //public const uint COMADMIN_E_DLLLOADFAILED = 0x8011041D;
      //public const uint COMADMIN_E_BADREGISTRYLIBID = 0x8011041E;
      //public const uint COMADMIN_E_APPDIRNOTFOUND = 0x8011041F;
      //public const uint COMADMIN_E_REGISTRARFAILED = 0x80110423;
      //public const uint COMADMIN_E_COMPFILE_DOESNOTEXIST = 0x80110424;
      //public const uint COMADMIN_E_COMPFILE_LOADDLLFAIL = 0x80110425;
      //public const uint COMADMIN_E_COMPFILE_GETCLASSOBJ = 0x80110426;
      //public const uint COMADMIN_E_COMPFILE_CLASSNOTAVAIL = 0x80110427;
      //public const uint COMADMIN_E_COMPFILE_BADTLB = 0x80110428;
      //public const uint COMADMIN_E_COMPFILE_NOTINSTALLABLE = 0x80110429;
      //public const uint COMADMIN_E_NOTCHANGEABLE = 0x8011042A;
      //public const uint COMADMIN_E_NOTDELETEABLE = 0x8011042B;
      //public const uint COMADMIN_E_SESSION = 0x8011042C;
      //public const uint COMADMIN_E_COMP_MOVE_LOCKED = 0x8011042D;
      //public const uint COMADMIN_E_COMP_MOVE_BAD_DEST = 0x8011042E;
      //public const uint COMADMIN_E_REGISTERTLB = 0x80110430;
      //public const uint COMADMIN_E_SYSTEMAPP = 0x80110433;
      //public const uint COMADMIN_E_COMPFILE_NOREGISTRAR = 0x80110434;
      //public const uint COMADMIN_E_COREQCOMPINSTALLED = 0x80110435;
      //public const uint COMADMIN_E_SERVICENOTINSTALLED = 0x80110436;
      //public const uint COMADMIN_E_PROPERTYSAVEFAILED = 0x80110437;
      //public const uint COMADMIN_E_OBJECTEXISTS = 0x80110438;
      //public const uint COMADMIN_E_COMPONENTEXISTS = 0x80110439;
      //public const uint COMADMIN_E_REGFILE_CORRUPT = 0x8011043B;
      //public const uint COMADMIN_E_PROPERTY_OVERFLOW = 0x8011043C;
      //public const uint COMADMIN_E_NOTINREGISTRY = 0x8011043E;
      //public const uint COMADMIN_E_OBJECTNOTPOOLABLE = 0x8011043F;
      //public const uint COMADMIN_E_APPLID_MATCHES_CLSID = 0x80110446;
      //public const uint COMADMIN_E_ROLE_DOES_NOT_EXIST = 0x80110447;
      //public const uint COMADMIN_E_START_APP_NEEDS_COMPONENTS = 0x80110448;
      //public const uint COMADMIN_E_REQUIRES_DIFFERENT_PLATFORM = 0x80110449;
      //public const uint COMADMIN_E_CAN_NOT_EXPORT_APP_PROXY = 0x8011044A;
      //public const uint COMADMIN_E_CAN_NOT_START_APP = 0x8011044B;
      //public const uint COMADMIN_E_CAN_NOT_EXPORT_SYS_APP = 0x8011044C;
      //public const uint COMADMIN_E_CANT_SUBSCRIBE_TO_COMPONENT = 0x8011044D;
      //public const uint COMADMIN_E_EVENTCLASS_CANT_BE_SUBSCRIBER = 0x8011044E;
      //public const uint COMADMIN_E_LIB_APP_PROXY_INCOMPATIBLE = 0x8011044F;
      //public const uint COMADMIN_E_BASE_PARTITION_ONLY = 0x80110450;
      //public const uint COMADMIN_E_START_APP_DISABLED = 0x80110451;
      //public const uint COMADMIN_E_CAT_DUPLICATE_PARTITION_NAME = 0x80110457;
      //public const uint COMADMIN_E_CAT_INVALID_PARTITION_NAME = 0x80110458;
      //public const uint COMADMIN_E_CAT_PARTITION_IN_USE = 0x80110459;
      //public const uint COMADMIN_E_FILE_PARTITION_DUPLICATE_FILES = 0x8011045A;
      //public const uint COMADMIN_E_CAT_IMPORTED_COMPONENTS_NOT_ALLOWED = 0x8011045B;
      //public const uint COMADMIN_E_AMBIGUOUS_APPLICATION_NAME = 0x8011045C;
      //public const uint COMADMIN_E_AMBIGUOUS_PARTITION_NAME = 0x8011045D;
      //public const uint COMADMIN_E_REGDB_NOTINITIALIZED = 0x80110472;
      //public const uint COMADMIN_E_REGDB_NOTOPEN = 0x80110473;
      //public const uint COMADMIN_E_REGDB_SYSTEMERR = 0x80110474;
      //public const uint COMADMIN_E_REGDB_ALREADYRUNNING = 0x80110475;
      //public const uint COMADMIN_E_MIG_VERSIONNOTSUPPORTED = 0x80110480;
      //public const uint COMADMIN_E_MIG_SCHEMANOTFOUND = 0x80110481;
      //public const uint COMADMIN_E_CAT_BITNESSMISMATCH = 0x80110482;
      //public const uint COMADMIN_E_CAT_UNACCEPTABLEBITNESS = 0x80110483;
      //public const uint COMADMIN_E_CAT_WRONGAPPBITNESS = 0x80110484;
      //public const uint COMADMIN_E_CAT_PAUSE_RESUME_NOT_SUPPORTED = 0x80110485;
      //public const uint COMADMIN_E_CAT_SERVERFAULT = 0x80110486;
      //public const uint COMQC_E_APPLICATION_NOT_QUEUED = 0x80110600;
      //public const uint COMQC_E_NO_QUEUEABLE_INTERFACES = 0x80110601;
      //public const uint COMQC_E_QUEUING_SERVICE_NOT_AVAILABLE = 0x80110602;
      //public const uint COMQC_E_NO_IPERSISTSTREAM = 0x80110603;
      //public const uint COMQC_E_BAD_MESSAGE = 0x80110604;
      //public const uint COMQC_E_UNAUTHENTICATED = 0x80110605;
      //public const uint COMQC_E_UNTRUSTED_ENQUEUER = 0x80110606;
      //public const uint MSDTC_E_DUPLICATE_RESOURCE = 0x80110701;
      //public const uint COMADMIN_E_OBJECT_PARENT_MISSING = 0x80110808;
      //public const uint COMADMIN_E_OBJECT_DOES_NOT_EXIST = 0x80110809;
      //public const uint COMADMIN_E_APP_NOT_RUNNING = 0x8011080A;
      //public const uint COMADMIN_E_INVALID_PARTITION = 0x8011080B;
      //public const uint COMADMIN_E_SVCAPP_NOT_POOLABLE_OR_RECYCLABLE = 0x8011080D;
      //public const uint COMADMIN_E_USER_IN_SET = 0x8011080E;
      //public const uint COMADMIN_E_CANTRECYCLELIBRARYAPPS = 0x8011080F;
      //public const uint COMADMIN_E_CANTRECYCLESERVICEAPPS = 0x80110811;
      //public const uint COMADMIN_E_PROCESSALREADYRECYCLED = 0x80110812;
      //public const uint COMADMIN_E_PAUSEDPROCESSMAYNOTBERECYCLED = 0x80110813;
      //public const uint COMADMIN_E_CANTMAKEINPROCSERVICE = 0x80110814;
      //public const uint COMADMIN_E_PROGIDINUSEBYCLSID = 0x80110815;
      //public const uint COMADMIN_E_DEFAULT_PARTITION_NOT_IN_SET = 0x80110816;
      //public const uint COMADMIN_E_RECYCLEDPROCESSMAYNOTBEPAUSED = 0x80110817;
      //public const uint COMADMIN_E_PARTITION_ACCESSDENIED = 0x80110818;
      //public const uint COMADMIN_E_PARTITION_MSI_ONLY = 0x80110819;
      //public const uint COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_1_0_FORMAT = 0x8011081A;
      //public const uint COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_NONBASE_PARTITIONS = 0x8011081B;
      //public const uint COMADMIN_E_COMP_MOVE_SOURCE = 0x8011081C;
      //public const uint COMADMIN_E_COMP_MOVE_DEST = 0x8011081D;
      //public const uint COMADMIN_E_COMP_MOVE_PRIVATE = 0x8011081E;
      //public const uint COMADMIN_E_BASEPARTITION_REQUIRED_IN_SET = 0x8011081F;
      //public const uint COMADMIN_E_CANNOT_ALIAS_EVENTCLASS = 0x80110820;
      //public const uint COMADMIN_E_PRIVATE_ACCESSDENIED = 0x80110821;
      //public const uint COMADMIN_E_SAFERINVALID = 0x80110822;
      //public const uint COMADMIN_E_REGISTRY_ACCESSDENIED = 0x80110823;
      //public const uint COMADMIN_E_PARTITIONS_DISABLED = 0x80110824;


      #region Network Management Error Codes

      // http://msdn.microsoft.com/en-us/library/windows/desktop/aa370674%28v=vs.85%29.aspx

      /// <summary>(0) The operation completed successfully.</summary>
      public const uint NERR_Success = 0;

      ///// <summary>The workstation driver is not installed.</summary>
      //public const uint NERR_NetNotStarted = 2102;

      ///// <summary>The server could not be located.</summary>
      //public const uint NERR_UnknownServer = 2103;

      ///// <summary>An internal error occurred. The network cannot access a shared memory segment.</summary>
      //public const uint NERR_ShareMem = 2104;

      ///// <summary>A network resource shortage occurred.</summary>
      //public const uint NERR_NoNetworkResource = 2105;

      ///// <summary>This operation is not supported on workstations.</summary>
      //public const uint NERR_RemoteOnly = 2106;

      ///// <summary>The device is not connected.</summary>
      //public const uint NERR_DevNotRedirected = 2107;

      ///// <summary>The Server service is not started.</summary>
      //public const uint NERR_ServerNotStarted = 2114;

      ///// <summary>The queue is empty.</summary>
      //public const uint NERR_ItemNotFound = 2115;

      ///// <summary>The device or directory does not exist.</summary>
      //public const uint NERR_UnknownDevDir = 2116;

      ///// <summary>The operation is invalid on a redirected resource.</summary>
      //public const uint NERR_RedirectedPath = 2117;

      ///// <summary>The name has already been shared.</summary>
      //public const uint NERR_DuplicateShare = 2118;

      ///// <summary>The server is currently out of the requested resource.</summary>
      //public const uint NERR_NoRoom = 2119;

      ///// <summary>Requested addition of items exceeds the maximum allowed.</summary>
      //public const uint NERR_TooManyItems = 2121;

      ///// <summary>The Peer service supports only two simultaneous users.</summary>
      //public const uint NERR_InvalidMaxUsers = 2122;

      ///// <summary>The API return buffer is too small.</summary>
      //public const uint NERR_BufTooSmall = 2123;

      ///// <summary>A remote API error occurred.</summary>
      //public const uint NERR_RemoteErr = 2127;

      ///// <summary>An error occurred when opening or reading the configuration file.</summary>
      //public const uint NERR_LanmanIniError = 2131;

      ///// <summary>A general network error occurred.</summary>
      //public const uint NERR_NetworkError = 2136;

      ///// <summary>The Workstation service is in an inconsistent state. Restart the computer before restarting the Workstation service.</summary>
      //public const uint NERR_WkstaInconsistentState = 2137;

      ///// <summary>The Workstation service has not been started.</summary>
      //public const uint NERR_WkstaNotStarted = 2138;

      ///// <summary>The requested information is not available.</summary>
      //public const uint NERR_BrowserNotStarted = 2139;

      ///// <summary>An internal error occurred.</summary>
      //public const uint NERR_InternalError = 2140;

      ///// <summary>The server is not configured for transactions.</summary>
      //public const uint NERR_BadTransactConfig = 2141;

      ///// <summary>The requested API is not supported on the remote server.</summary>
      //public const uint NERR_InvalidAPI = 2142;

      ///// <summary>The event name is invalid.</summary>
      //public const uint NERR_BadEventName = 2143;

      ///// <summary>The computer name already exists on the network. Change it and restart the computer.</summary>
      //public const uint NERR_DupNameReboot = 2144;

      ///// <summary>The specified component could not be found in the configuration information.</summary>
      //public const uint NERR_CfgCompNotFound = 2146;

      ///// <summary>The specified parameter could not be found in the configuration information.</summary>
      //public const uint NERR_CfgParamNotFound = 2147;

      ///// <summary>A line in the configuration file is too long.</summary>
      //public const uint NERR_LineTooLong = 2149;

      ///// <summary>The printer does not exist.</summary>
      //public const uint NERR_QNotFound = 2150;

      ///// <summary>The print job does not exist.</summary>
      //public const uint NERR_JobNotFound = 2151;

      ///// <summary>The printer destination cannot be found.</summary>
      //public const uint NERR_DestNotFound = 2152;

      ///// <summary>The printer destination already exists.</summary>
      //public const uint NERR_DestExists = 2153;

      ///// <summary>The printer queue already exists.</summary>
      //public const uint NERR_QExists = 2154;

      ///// <summary>No more printers can be added.</summary>
      //public const uint NERR_QNoRoom = 2155;

      ///// <summary>No more print jobs can be added.</summary>
      //public const uint NERR_JobNoRoom = 2156;

      ///// <summary>No more printer destinations can be added.</summary>
      //public const uint NERR_DestNoRoom = 2157;

      ///// <summary>This printer destination is idle and cannot accept control operations.</summary>
      //public const uint NERR_DestIdle = 2158;

      ///// <summary>This printer destination request contains an invalid control function.</summary>
      //public const uint NERR_DestInvalidOp = 2159;

      ///// <summary>The print processor is not responding.</summary>
      //public const uint NERR_ProcNoRespond = 2160;

      ///// <summary>The spooler is not running.</summary>
      //public const uint NERR_SpoolerNotLoaded = 2161;

      ///// <summary>This operation cannot be performed on the print destination in its current state.</summary>
      //public const uint NERR_DestInvalidState = 2162;

      ///// <summary>This operation cannot be performed on the printer queue in its current state.</summary>
      //public const uint NERR_QinvalidState = 2163;

      ///// <summary>This operation cannot be performed on the print job in its current state.</summary>
      //public const uint NERR_JobInvalidState = 2164;

      ///// <summary>A spooler memory allocation failure occurred.</summary>
      //public const uint NERR_SpoolNoMemory = 2165;

      ///// <summary>The device driver does not exist.</summary>
      //public const uint NERR_DriverNotFound = 2166;

      ///// <summary>The data type is not supported by the print processor.</summary>
      //public const uint NERR_DataTypeInvalid = 2167;

      ///// <summary>The print processor is not installed.</summary>
      //public const uint NERR_ProcNotFound = 2168;

      ///// <summary>The service database is locked.</summary>
      //public const uint NERR_ServiceTableLocked = 2180;

      ///// <summary>The service table is full.</summary>
      //public const uint NERR_ServiceTableFull = 2181;

      ///// <summary>The requested service has already been started.</summary>
      //public const uint NERR_ServiceInstalled = 2182;

      ///// <summary>The service does not respond to control actions.</summary>
      //public const uint NERR_ServiceEntryLocked = 2183;

      ///// <summary>The service has not been started.</summary>
      //public const uint NERR_ServiceNotInstalled = 2184;

      ///// <summary>The service name is invalid.</summary>
      //public const uint NERR_BadServiceName = 2185;

      ///// <summary>The service is not responding to the control function.</summary>
      //public const uint NERR_ServiceCtlTimeout = 2186;

      ///// <summary>The service control is busy.</summary>
      //public const uint NERR_ServiceCtlBusy = 2187;

      ///// <summary>The configuration file contains an invalid service program name.</summary>
      //public const uint NERR_BadServiceProgName = 2188;

      ///// <summary>The service could not be controlled in its present state.</summary>
      //public const uint NERR_ServiceNotCtrl = 2189;

      ///// <summary>The service ended abnormally.</summary>
      //public const uint NERR_ServiceKillProc = 2190;

      ///// <summary>The requested pause or stop is not valid for this service.</summary>
      //public const uint NERR_ServiceCtlNotValid = 2191;

      ///// <summary>The service control dispatcher could not find the service name in the dispatch table.</summary>
      //public const uint NERR_NotInDispatchTbl = 2192;

      ///// <summary>The service control dispatcher pipe read failed.</summary>
      //public const uint NERR_BadControlRecv = 2193;

      ///// <summary>A thread for the new service could not be created.</summary>
      //public const uint NERR_ServiceNotStarting = 2194;

      ///// <summary>This workstation is already logged on to the local-area network.</summary>
      //public const uint NERR_AlreadyLoggedOn = 2200;

      ///// <summary>The workstation is not logged on to the local-area network.</summary>
      //public const uint NERR_NotLoggedOn = 2201;

      ///// <summary>The user name or group name parameter is invalid.</summary>
      //public const uint NERR_BadUsername = 2202;

      ///// <summary>The password parameter is invalid.</summary>
      //public const uint NERR_BadPassword = 2203;

      ///// <summary>@W The logon processor did not add the message alias.</summary>
      //public const uint NERR_UnableToAddName_W = 2204;

      ///// <summary>The logon processor did not add the message alias.</summary>
      //public const uint NERR_UnableToAddName_F = 2205;

      ///// <summary>@W The logoff processor did not delete the message alias.</summary>
      //public const uint NERR_UnableToDelName_W = 2206;

      ///// <summary>The logoff processor did not delete the message alias.</summary>
      //public const uint NERR_UnableToDelName_F = 2207;

      ///// <summary>Network logons are paused.</summary>
      //public const uint NERR_LogonsPaused = 2209;

      ///// <summary>A centralized logon-server conflict occurred.</summary>
      //public const uint NERR_LogonServerConflict = 2210;

      ///// <summary>The server is configured without a valid user path.</summary>
      //public const uint NERR_LogonNoUserPath = 2211;

      ///// <summary>An error occurred while loading or running the logon script.</summary>
      //public const uint NERR_LogonScriptError = 2212;

      ///// <summary>The logon server was not specified. Your computer will be logged on as STANDALONE.</summary>
      //public const uint NERR_StandaloneLogon = 2214;

      ///// <summary>The logon server could not be found.</summary>
      //public const uint NERR_LogonServerNotFound = 2215;

      ///// <summary>There is already a logon domain for this computer.</summary>
      //public const uint NERR_LogonDomainExists = 2216;

      ///// <summary>The logon server could not validate the logon.</summary>
      //public const uint NERR_NonValidatedLogon = 2217;

      ///// <summary>The security database could not be found.</summary>
      //public const uint NERR_ACFNotFound = 2219;

      ///// <summary>The group name could not be found.</summary>
      //public const uint NERR_GroupNotFound = 2220;

      ///// <summary>The user name could not be found.</summary>
      //public const uint NERR_UserNotFound = 2221;

      ///// <summary>The resource name could not be found.</summary>
      //public const uint NERR_ResourceNotFound = 2222;

      ///// <summary>The group already exists.</summary>
      //public const uint NERR_GroupExists = 2223;

      ///// <summary>The user account already exists.</summary>
      //public const uint NERR_UserExists = 2224;

      ///// <summary>The resource permission list already exists.</summary>
      //public const uint NERR_ResourceExists = 2225;

      ///// <summary>This operation is only allowed on the primary domain controller of the domain.</summary>
      //public const uint NERR_NotPrimary = 2226;

      ///// <summary>The security database has not been started.</summary>
      //public const uint NERR_ACFNotLoaded = 2227;

      ///// <summary>There are too many names in the user accounts database.</summary>
      //public const uint NERR_ACFNoRoom = 2228;

      ///// <summary>A disk I/O failure occurred.</summary>
      //public const uint NERR_ACFFileIOFail = 2229;

      ///// <summary>The limit of 64 entries per resource was exceeded.</summary>
      //public const uint NERR_ACFTooManyLists = 2230;

      ///// <summary>Deleting a user with a session is not allowed.</summary>
      //public const uint NERR_UserLogon = 2231;

      ///// <summary>The parent directory could not be located.</summary>
      //public const uint NERR_ACFNoParent = 2232;

      ///// <summary>Unable to add to the security database session cache segment.</summary>
      //public const uint NERR_CanNotGrowSegment = 2233;

      ///// <summary>This operation is not allowed on this special group.</summary>
      //public const uint NERR_SpeGroupOp = 2234;

      ///// <summary>This user is not cached in user accounts database session cache.</summary>
      //public const uint NERR_NotInCache = 2235;

      ///// <summary>The user already belongs to this group.</summary>
      //public const uint NERR_UserInGroup = 2236;

      ///// <summary>The user does not belong to this group.</summary>
      //public const uint NERR_UserNotInGroup = 2237;

      ///// <summary>This user account is undefined.</summary>
      //public const uint NERR_AccountUndefined = 2238;

      ///// <summary>This user account has expired.</summary>
      //public const uint NERR_AccountExpired = 2239;

      ///// <summary>The user is not allowed to log on from this workstation.</summary>
      //public const uint NERR_InvalidWorkstation = 2240;

      ///// <summary>The user is not allowed to log on at this time.</summary>
      //public const uint NERR_InvalidLogonHours = 2241;

      ///// <summary>The password of this user has expired.</summary>
      //public const uint NERR_PasswordExpired = 2242;

      ///// <summary>The password of this user cannot change.</summary>
      //public const uint NERR_PasswordCantChange = 2243;

      ///// <summary>This password cannot be used now.</summary>
      //public const uint NERR_PasswordHistConflict = 2244;

      ///// <summary>The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements.</summary>
      //public const uint NERR_PasswordTooShort = 2245;

      ///// <summary>The password of this user is too recent to change.</summary>
      //public const uint NERR_PasswordTooRecent = 2246;

      ///// <summary>The security database is corrupted.</summary>
      //public const uint NERR_InvalidDatabase = 2247;

      ///// <summary>No updates are necessary to this replicant network/local security database.</summary>
      //public const uint NERR_DatabaseUpToDate = 2248;

      ///// <summary>This replicant database is outdated; synchronization is required.</summary>
      //public const uint NERR_SyncRequired = 2249;

      //// <summary>(2250) The network connection could not be found.</summary>
      //public const uint NERR_UseNotFound = 2250;

      ///// <summary>This asg_type is invalid.</summary>
      //public const uint NERR_BadAsgType = 2251;

      ///// <summary>This device is currently being shared.</summary>
      //public const uint NERR_DeviceIsShared = 2252;

      ///// <summary>The computer name could not be added as a message alias. The name may already exist on the network.</summary>
      //public const uint NERR_NoComputerName = 2270;

      ///// <summary>The Messenger service is already started.</summary>
      //public const uint NERR_MsgAlreadyStarted = 2271;

      ///// <summary>The Messenger service failed to start.</summary>
      //public const uint NERR_MsgInitFailed = 2272;

      ///// <summary>The message alias could not be found on the network.</summary>
      //public const uint NERR_NameNotFound = 2273;

      ///// <summary>This message alias has already been forwarded.</summary>
      //public const uint NERR_AlreadyForwarded = 2274;

      ///// <summary>This message alias has been added but is still forwarded.</summary>
      //public const uint NERR_AddForwarded = 2275;

      ///// <summary>This message alias already exists locally.</summary>
      //public const uint NERR_AlreadyExists = 2276;

      ///// <summary>The maximum number of added message aliases has been exceeded.</summary>
      //public const uint NERR_TooManyNames = 2277;

      ///// <summary>The computer name could not be deleted.</summary>
      //public const uint NERR_DelComputerName = 2278;

      ///// <summary>Messages cannot be forwarded back to the same workstation.</summary>
      //public const uint NERR_LocalForward = 2279;

      ///// <summary>An error occurred in the domain message processor.</summary>
      //public const uint NERR_GrpMsgProcessor = 2280;

      ///// <summary>The message was sent, but the recipient has paused the Messenger service.</summary>
      //public const uint NERR_PausedRemote = 2281;

      ///// <summary>The message was sent but not received.</summary>
      //public const uint NERR_BadReceive = 2282;

      ///// <summary>The message alias is currently in use. Try again later.</summary>
      //public const uint NERR_NameInUse = 2283;

      ///// <summary>The Messenger service has not been started.</summary>
      //public const uint NERR_MsgNotStarted = 2284;

      ///// <summary>The name is not on the local computer.</summary>
      //public const uint NERR_NotLocalName = 2285;

      ///// <summary>The forwarded message alias could not be found on the network.</summary>
      //public const uint NERR_NoForwardName = 2286;

      ///// <summary>The message alias table on the remote station is full.</summary>
      //public const uint NERR_RemoteFull = 2287;

      ///// <summary>Messages for this alias are not currently being forwarded.</summary>
      //public const uint NERR_NameNotForwarded = 2288;

      ///// <summary>The broadcast message was truncated.</summary>
      //public const uint NERR_TruncatedBroadcast = 2289;

      ///// <summary>This is an invalid device name.</summary>
      //public const uint NERR_InvalidDevice = 2294;

      ///// <summary>A write fault occurred.</summary>
      //public const uint NERR_WriteFault = 2295;

      ///// <summary>A duplicate message alias exists on the network.</summary>
      //public const uint NERR_DuplicateName = 2297;

      ///// <summary>@W This message alias will be deleted later.</summary>
      //public const uint NERR_DeleteLater = 2298;

      ///// <summary>The message alias was not successfully deleted from all networks.</summary>
      //public const uint NERR_IncompleteDel = 2299;

      ///// <summary>This operation is not supported on computers with multiple networks.</summary>
      //public const uint NERR_MultipleNets = 2300;

      //// <summary>(2310) This shared resource does not exist.</summary>
      //public const uint NERR_NetNameNotFound = 2310;

      ///// <summary>This device is not shared.</summary>
      //public const uint NERR_DeviceNotShared = 2311;

      ///// <summary>A session does not exist with that computer name.</summary>
      //public const uint NERR_ClientNameNotFound = 2312;

      /// <summary>(2314) There is not an open file with that identification number.</summary>
      public const uint NERR_FileIdNotFound = 2314;

      ///// <summary>A failure occurred when executing a remote administration command.</summary>
      //public const uint NERR_ExecFailure = 2315;

      ///// <summary>A failure occurred when opening a remote temporary file.</summary>
      //public const uint NERR_TmpFile = 2316;

      ///// <summary>The data returned from a remote administration command has been truncated to 64K.</summary>
      //public const uint NERR_TooMuchData = 2317;

      ///// <summary>This device cannot be shared as both a spooled and a non-spooled resource.</summary>
      //public const uint NERR_DeviceShareConflict = 2318;

      ///// <summary>The information in the list of servers may be incorrect.</summary>
      //public const uint NERR_BrowserTableIncomplete = 2319;

      ///// <summary>The computer is not active in this domain.</summary>
      //public const uint NERR_NotLocalDomain = 2320;

      ///// <summary>The share must be removed from the Distributed File System before it can be deleted.</summary>
      //public const uint NERR_IsDfsShare = 2321;

      ///// <summary>The operation is invalid for this device.</summary>
      //public const uint NERR_DevInvalidOpCode = 2331;

      ///// <summary>This device cannot be shared.</summary>
      //public const uint NERR_DevNotFound = 2332;

      ///// <summary>This device was not open.</summary>
      //public const uint 	NERR_DevNotOpen = 2333;

      ///// <summary>This device name list is invalid.</summary>
      //public const uint NERR_BadQueueDevString = 2334;

      ///// <summary>The queue priority is invalid.</summary>
      //public const uint NERR_BadQueuePriority = 2335;

      ///// <summary>There are no shared communication devices.</summary>
      //public const uint NERR_NoCommDevs = 2337;

      ///// <summary>The queue you specified does not exist.</summary>
      //public const uint NERR_QueueNotFound = 2338;

      ///// <summary>This list of devices is invalid.</summary>
      //public const uint NERR_BadDevString = 2340;

      ///// <summary>The requested device is invalid.</summary>
      //public const uint NERR_BadDev = 2341;      

      ///// <summary>This device is already in use by the spooler.</summary>
      //public const uint NERR_InUseBySpooler = 2342;

      ///// <summary>This device is already in use as a communication device.</summary>
      //public const uint NERR_CommDevInUse = 2343;

      ///// <summary>This computer name is invalid.</summary>
      //public const uint NERR_InvalidComputer = 2351;

      ///// <summary>The string and prefix specified are too long.</summary>
      //public const uint NERR_MaxLenExceeded = 2354;

      ///// <summary>This path component is invalid.</summary>
      //public const uint NERR_BadComponent = 2356;

      ///// <summary>Could not determine the type of input.</summary>
      //public const uint NERR_CantType = 2357;

      ///// <summary>The buffer for types is not big enough.</summary>
      //public const uint NERR_TooManyEntries = 2362;

      ///// <summary>Profile files cannot exceed 64K.</summary>
      //public const uint NERR_ProfileFileTooBig = 2370;      

      ///// <summary>The start offset is out of range.</summary>
      //public const uint NERR_ProfileOffset = 2371;

      ///// <summary>The system cannot delete current connections to network resources.</summary>
      //public const uint NERR_ProfileCleanup = 2372;

      ///// <summary>The system was unable to parse the command line in this file.</summary>
      //public const uint NERR_ProfileUnknownCmd = 2373;

      ///// <summary>An error occurred while loading the profile file.</summary>
      //public const uint NERR_ProfileLoadErr = 2374;

      ///// <summary>@W Errors occurred while saving the profile file. The profile was partially saved.</summary>
      //public const uint NERR_ProfileSaveErr = 2375;

      ///// <summary>Log file %1 is full.</summary>
      //public const uint NERR_LogOverflow = 2377;

      ///// <summary>This log file has changed between reads.</summary>
      //public const uint NERR_LogFileChanged = 2378;

      ///// <summary>Log file %1 is corrupt.</summary>
      //public const uint NERR_LogFileCorrupt = 2379;      

      ///// <summary>The source path cannot be a directory.</summary>
      //public const uint NERR_SourceIsDir = 2380;

      ///// <summary>The source path is illegal.</summary>
      //public const uint NERR_BadSource = 2381;

      ///// <summary>The destination path is illegal.</summary>
      //public const uint NERR_BadDest = 2382;

      ///// <summary>The source and destination paths are on different servers.</summary>
      //public const uint NERR_DifferentServers = 2383;

      ///// <summary>The Run server you requested is paused.</summary>
      //public const uint NERR_RunSrvPaused = 2385;

      ///// <summary>An error occurred when communicating with a Run server.</summary>
      //public const uint NERR_ErrCommRunSrv = 2389;

      ///// <summary>An error occurred when starting a background process.</summary>
      //public const uint NERR_ErrorExecingGhost = 2391;

      ///// <summary>The shared resource you are connected to could not be found.</summary>
      //public const uint NERR_ShareNotFound = 2392;      

      ///// <summary>The LAN adapter number is invalid.</summary>
      //public const uint NERR_InvalidLana = 2400;

      ///// <summary>There are open files on the connection.</summary>
      //public const uint NERR_OpenFiles = 2401;

      ///// <summary>Active connections still exist.</summary>
      //public const uint NERR_ActiveConns = 2402;

      ///// <summary>This share name or password is invalid.</summary>
      //public const uint NERR_BadPasswordCore = 2403;

      ///// <summary>The device is being accessed by an active process.</summary>
      //public const uint NERR_DevInUse = 2404;

      ///// <summary>The drive letter is in use locally.</summary>
      //public const uint NERR_LocalDrive = 2405;

      ///// <summary>The specified client is already registered for the specified event.</summary>
      //public const uint NERR_AlertExists = 2430;

      ///// <summary>The alert table is full.</summary>
      //public const uint NERR_TooManyAlerts = 2431;      

      ///// <summary>An invalid or nonexistent alert name was raised.</summary>
      //public const uint NERR_NoSuchAlert = 2432;

      ///// <summary>The alert recipient is invalid.</summary>
      //public const uint NERR_BadRecipient = 2433;

      ///// <summary>A user's session with this server has been deleted</summary>
      //public const uint NERR_AcctLimitExceeded = 2434;

      ///// <summary>The log file does not contain the requested record number.</summary>
      //public const uint NERR_InvalidLogSeek = 2440;

      ///// <summary>The user accounts database is not configured correctly.</summary>
      //public const uint NERR_BadUasConfig = 2450;

      ///// <summary>This operation is not permitted when the Netlogon service is running.</summary>
      //public const uint NERR_InvalidUASOp = 2451;

      ///// <summary>This operation is not allowed on the last administrative account.</summary>
      //public const uint NERR_LastAdmin = 2452;

      ///// <summary>Could not find domain controller for this domain.</summary>
      //public const uint NERR_DCNotFound = 2453;      

      ///// <summary>Could not set logon information for this user.</summary>
      //public const uint NERR_LogonTrackingError = 2454;

      ///// <summary>The Netlogon service has not been started.</summary>
      //public const uint NERR_NetlogonNotStarted = 2455;

      ///// <summary>Unable to add to the user accounts database.</summary>
      //public const uint NERR_CanNotGrowUASFile = 2456;

      ///// <summary>This server's clock is not synchronized with the primary domain controller's clock.</summary>
      //public const uint NERR_TimeDiffAtDC = 2457;

      ///// <summary>A password mismatch has been detected.</summary>
      //public const uint NERR_PasswordMismatch = 2458;

      ///// <summary>The server identification does not specify a valid server.</summary>
      //public const uint NERR_NoSuchServer = 2460;

      ///// <summary>The session identification does not specify a valid session.</summary>
      //public const uint NERR_NoSuchSession = 2461;

      ///// <summary>The connection identification does not specify a valid connection.</summary>
      //public const uint NERR_NoSuchConnection = 2462;      

      ///// <summary>There is no space for another entry in the table of available servers.</summary>
      //public const uint NERR_TooManyServers = 2463;

      ///// <summary>The server has reached the maximum number of sessions it supports.</summary>
      //public const uint NERR_TooManySessions = 2464;

      ///// <summary>The server has reached the maximum number of connections it supports.</summary>
      //public const uint NERR_TooManyConnections = 2465;

      ///// <summary>The server cannot open more files because it has reached its maximum number.</summary>
      //public const uint NERR_TooManyFiles = 2466;

      ///// <summary>There are no alternate servers registered on this server.</summary>
      //public const uint NERR_NoAlternateServers = 2467;

      ///// <summary>Try down-level (remote admin protocol) version of API instead.</summary>
      //public const uint NERR_TryDownLevel = 2470;

      ///// <summary>The UPS driver could not be accessed by the UPS service.</summary>
      //public const uint NERR_UPSDriverNotStarted = 2480;

      ///// <summary>The UPS service is not configured correctly.</summary>
      //public const uint NERR_UPSInvalidConfig = 2481;      

      ///// <summary>The UPS service could not access the specified Comm Port.</summary>
      //public const uint NERR_UPSInvalidCommPort = 2482;

      ///// <summary>The UPS indicated a line fail or low battery situation. Service not started.</summary>
      //public const uint NERR_UPSSignalAsserted = 2483;

      ///// <summary>The UPS service failed to perform a system shut down.</summary>
      //public const uint NERR_UPSShutdownFailed = 2484;

      ///// <summary>The program below returned an MS-DOS error code:</summary>
      //public const uint NERR_BadDosRetCode = 2500;

      ///// <summary>The program below needs more memory:</summary>
      //public const uint NERR_ProgNeedsExtraMem = 2501;

      ///// <summary>The program below called an unsupported MS-DOS function:</summary>
      //public const uint NERR_BadDosFunction = 2502;

      ///// <summary>The workstation failed to boot.</summary>
      //public const uint NERR_RemoteBootFailed = 2503;

      ///// <summary>The file below is corrupt.</summary>
      //public const uint NERR_BadFileCheckSum = 2504;      

      ///// <summary>No loader is specified in the boot-block definition file.</summary>
      //public const uint NERR_NoRplBootSystem = 2505;

      ///// <summary>NetBIOS returned an error: The NCB and SMB are dumped above.</summary>
      //public const uint NERR_RplLoadrNetBiosErr = 2506;

      ///// <summary>A disk I/O error occurred.</summary>
      //public const uint NERR_RplLoadrDiskErr = 2507;

      ///// <summary>Image parameter substitution failed.</summary>
      //public const uint NERR_ImageParamErr = 2508;

      ///// <summary>Too many image parameters cross disk sector boundaries.</summary>
      //public const uint NERR_TooManyImageParams = 2509;

      ///// <summary>The image was not generated from an MS-DOS diskette formatted with /S.</summary>
      //public const uint NERR_NonDosFloppyUsed = 2510;

      ///// <summary>Remote boot will be restarted later.</summary>
      //public const uint NERR_RplBootRestart = 2511;

      ///// <summary>The call to the Remoteboot server failed.</summary>
      //public const uint NERR_RplSrvrCallFailed = 2512;      

      ///// <summary>Cannot connect to the Remoteboot server.</summary>
      //public const uint NERR_CantConnectRplSrvr = 2513;

      ///// <summary>Cannot open image file on the Remoteboot server.</summary>
      //public const uint NERR_CantOpenImageFile = 2514;

      ///// <summary>Connecting to the Remoteboot server.</summary>
      //public const uint NERR_CallingRplSrvr = 2515;

      ///// <summary>Connecting to the Remoteboot server.</summary>
      //public const uint NERR_StartingRplBoot = 2516;

      ///// <summary>Remote boot service was stopped; check the error log for the cause of the problem.</summary>
      //public const uint NERR_RplBootServiceTerm = 2517;

      ///// <summary>Remote boot startup failed; check the error log for the cause of the problem.</summary>
      //public const uint NERR_RplBootStartFailed = 2518;

      ////// <summary>A second connection to a Remoteboot resource is not allowed.</summary>
      //public const uint NERR_RplConnected = 2519;

      ///// <summary>The browser service was configured with MaintainServerList=No.</summary>
      //public const uint NERR_BrowserConfiguredToNotRun = 2550;      

      ///// <summary>Service failed to start since none of the network adapters started with this service.</summary>
      //public const uint NERR_RplNoAdaptersStarted = 2610;

      ///// <summary>Service failed to start due to bad startup information in the registry.</summary>
      //public const uint NERR_RplBadRegistry = 2611;

      ///// <summary>Service failed to start because its database is absent or corrupt.</summary>
      //public const uint NERR_RplBadDatabase = 2612;

      ///// <summary>Service failed to start because RPLFILES share is absent.</summary>
      //public const uint NERR_RplRplfilesShare = 2613;

      ///// <summary>Service failed to start because RPLUSER group is absent.</summary>
      //public const uint NERR_RplNotRplServer = 2614;

      ///// <summary>Cannot enumerate service records.</summary>
      //public const uint NERR_RplCannotEnum = 2615;

      ///// <summary>Workstation record information has been corrupted.</summary>
      //public const uint NERR_RplWkstaInfoCorrupted = 2616;

      ///// <summary>Workstation record was not found.</summary>
      //public const uint NERR_RplWkstaNotFound = 2617;      

      ///// <summary>Workstation name is in use by some other workstation.</summary>
      //public const uint NERR_RplWkstaNameUnavailable = 2618;

      ///// <summary>Profile record information has been corrupted.</summary>
      //public const uint NERR_RplProfileInfoCorrupted = 2619;

      ///// <summary>Profile record was not found.</summary>
      //public const uint NERR_RplProfileNotFound = 2620;

      ///// <summary>Profile name is in use by some other profile.</summary>
      //public const uint NERR_RplProfileNameUnavailable = 2621;

      ///// <summary>There are workstations using this profile.</summary>
      //public const uint NERR_RplProfileNotEmpty = 2622;

      ///// <summary>Configuration record information has been corrupted.</summary>
      //public const uint NERR_RplConfigInfoCorrupted = 2623;

      ///// <summary>Configuration record was not found.</summary>
      //public const uint NERR_RplConfigNotFound = 2624;

      ///// <summary>Adapter ID record information has been corrupted.</summary>
      //public const uint NERR_RplAdapterInfoCorrupted = 2625;      

      ///// <summary>An internal service error has occurred.</summary>
      //public const uint NERR_RplInternal = 2626;

      ///// <summary>Vendor ID record information has been corrupted.</summary>
      //public const uint NERR_RplVendorInfoCorrupted = 2627;

      ///// <summary>Boot block record information has been corrupted.</summary>
      //public const uint NERR_RplBootInfoCorrupted = 2628;

      ///// <summary>The user account for this workstation record is missing.</summary>
      //public const uint NERR_RplWkstaNeedsUserAcct = 2629;

      ///// <summary>The RPLUSER local group could not be found.</summary>
      //public const uint NERR_RplNeedsRPLUSERAcct = 2630;

      ///// <summary>Boot block record was not found.</summary>
      //public const uint NERR_RplBootNotFound = 2631;

      ///// <summary>Chosen profile is incompatible with this workstation.</summary>
      //public const uint NERR_RplIncompatibleProfile = 2632;

      ///// <summary>Chosen network adapter ID is in use by some other workstation.</summary>
      //public const uint NERR_RplAdapterNameUnavailable = 2633;      

      ///// <summary>There are profiles using this configuration.</summary>
      //public const uint NERR_RplConfigNotEmpty = 2634;

      ///// <summary>There are workstations, profiles, or configurations using this boot block.</summary>
      //public const uint NERR_RplBootInUse = 2635;

      ///// <summary>Service failed to backup Remoteboot database.</summary>
      //public const uint NERR_RplBackupDatabase = 2636;

      ///// <summary>Adapter record was not found.</summary>
      //public const uint NERR_RplAdapterNotFound = 2637;

      ///// <summary>Vendor record was not found.</summary>
      //public const uint NERR_RplVendorNotFound = 2638;

      ///// <summary>Vendor name is in use by some other vendor record.</summary>
      //public const uint NERR_RplVendorNameUnavailable = 2639;

      ///// <summary>(boot name, vendor ID) is in use by some other boot block record.</summary>
      //public const uint NERR_RplBootNameUnavailable = 2640;

      ///// <summary>Configuration name is in use by some other configuration.</summary>
      //public const uint NERR_RplConfigNameUnavailable = 2641;

      ///// <summary>The internal database maintained by the Dfs service is corrupt.</summary>
      //public const uint NERR_DfsInternalCorruption = 2660;

      ///// <summary>One of the records in the internal Dfs database is corrupt.</summary>
      //public const uint NERR_DfsVolumeDataCorrupt = 2661;

      ///// <summary>There is no DFS name whose entry path matches the input Entry Path.</summary>
      //public const uint NERR_DfsNoSuchVolume = 2662;

      ///// <summary>A root or link with the given name already exists.</summary>
      //public const uint NERR_DfsVolumeAlreadyExists = 2663;

      ///// <summary>The server share specified is already shared in the Dfs.</summary>
      //public const uint NERR_DfsAlreadyShared = 2664;

      ///// <summary>The indicated server share does not support the indicated DFS namespace.</summary>
      //public const uint NERR_DfsNoSuchShare = 2665;

      ///// <summary>The operation is not valid on this portion of the namespace.</summary>
      //public const uint NERR_DfsNotALeafVolume = 2666;

      ///// <summary>The operation is not valid on this portion of the namespace.</summary>
      //public const uint NERR_DfsLeafVolume = 2667;

      ///// <summary>The operation is ambiguous because the link has multiple servers.</summary>
      //public const uint NERR_DfsVolumeHasMultipleServers = 2668;

      ///// <summary>Unable to create a link.</summary>
      //public const uint NERR_DfsCantCreateJunctionPoint = 2669;

      ///// <summary>The server is not Dfs Aware.</summary>
      //public const uint NERR_DfsServerNotDfsAware = 2670;

      ///// <summary>The specified rename target path is invalid.</summary>
      //public const uint NERR_DfsBadRenamePath = 2671;

      ///// <summary>The specified DFS link is offline.</summary>
      //public const uint NERR_DfsVolumeIsOffline = 2672;

      ///// <summary>The specified server is not a server for this link.</summary>
      //public const uint NERR_DfsNoSuchServer = 2673;

      ///// <summary>A cycle in the Dfs name was detected.</summary>
      //public const uint NERR_DfsCyclicalName = 2674;

      ///// <summary>The operation is not supported on a server-based Dfs.</summary>
      //public const uint NERR_DfsNotSupportedInServerDfs = 2675;

      ///// <summary>This link is already supported by the specified server-share.</summary>
      //public const uint NERR_DfsDuplicateService = 2676;

      ///// <summary>Can't remove the last server-share supporting this root or link.</summary>
      //public const uint NERR_DfsCantRemoveLastServerShare = 2677;

      ///// <summary>The operation is not supported for an Inter-DFS link.</summary>
      //public const uint NERR_DfsVolumeIsInterDfs = 2678;

      ///// <summary>The internal state of the Dfs Service has become inconsistent.</summary>
      //public const uint NERR_DfsInconsistent = 2679;

      ///// <summary>The Dfs Service has been installed on the specified server.</summary>
      //public const uint NERR_DfsServerUpgraded = 2680;

      ///// <summary>The Dfs data being reconciled is identical.</summary>
      //public const uint NERR_DfsDataIsIdentical = 2681;

      ///// <summary>The DFS root cannot be deleted. Uninstall DFS if required.</summary>
      //public const uint NERR_DfsCantRemoveDfsRoot = 2682;

      ///// <summary>A child or parent directory of the share is already in a Dfs.</summary>
      //public const uint NERR_DfsChildOrParentInDfs = 2683;

      ///// <summary>Dfs internal error.</summary>
      //public const uint NERR_DfsInternalError = 2690;

      ///// <summary>This computer is already joined to a domain.</summary>
      //public const uint NERR_SetupAlreadyJoined = 2691;

      ///// <summary>This computer is not currently joined to a domain.</summary>
      //public const uint NERR_SetupNotJoined = 2692;

      ///// <summary>This computer is a domain controller and cannot be unjoined from a domain.</summary>
      //public const uint NERR_SetupDomainController = 2693;

      ///// <summary>The destination domain controller does not support creating machine accounts in OUs.</summary>
      //public const uint NERR_DefaultJoinRequired = 2694;

      ///// <summary>The specified workgroup name is invalid.</summary>
      //public const uint NERR_InvalidWorkgroupName = 2695;

      ///// <summary>The specified computer name is incompatible with the default language used on the domain controller.</summary>
      //public const uint NERR_NameUsesIncompatibleCodePage = 2696;

      ///// <summary>The specified computer account could not be found.</summary>
      //public const uint NERR_ComputerAccountNotFound = 2697;

      ///// <summary>This version of Windows cannot be joined to a domain.</summary>
      //public const uint NERR_PersonalSku = 2698;

      ///// <summary>The password must change at the next logon.</summary>
      //public const uint NERR_PasswordMustChange = 2701;

      ///// <summary>The account is locked out.</summary>
      //public const uint NERR_AccountLockedOut = 2702;

      ///// <summary>The password is too long.</summary>
      //public const uint NERR_PasswordTooLong = 2703;

      ///// <summary>The password does not meet the complexity policy.</summary>
      //public const uint NERR_PasswordNotComplexEnough = 2704;

      ///// <summary>The password does not meet the requirements of the password filter DLLs.</summary>
      //public const uint NERR_PasswordFilterError = 2705;

      ///// <summary>The offline join completion information was not found.</summary>
      //public const uint NERR_NoOfflineJoinInfo = 2709;

      ///// <summary>The offline join completion information was bad.</summary>
      //public const uint NERR_BadOfflineJoinInfo = 2710;

      ///// <summary>Unable to create offline join information. Please ensure you have access to the specified path location and permissions to modify its contents. Running as an elevated administrator may be required.</summary>
      //public const uint NERR_CantCreateJoinInfo = 2711;

      ///// <summary>The domain join info being saved was incomplete or bad.</summary>
      //public const uint NERR_BadDomainJoinInfo = 2712;

      ///// <summary>Offline join operation successfully completed but a restart is needed.</summary>
      //public const uint NERR_JoinPerformedMustRestart = 2713;

      ///// <summary>There was no offline join operation pending.</summary>
      //public const uint NERR_NoJoinPending = 2714;

      ///// <summary>Unable to set one or more requested machine or domain name values on the local computer.</summary>
      //public const uint NERR_ValuesNotSet = 2715;

      ///// <summary>Could not verify the current machine's hostname against the saved value in the join completion information.</summary>
      //public const uint NERR_CantVerifyHostname = 2716;

      ///// <summary>Unable to load the specified offline registry hive. Please ensure you have access to the specified path location and permissions to modify its contents. Running as an elevated administrator may be required.</summary>
      //public const uint NERR_CantLoadOfflineHive = 2717;

      ///// <summary>The minimum session security requirements for this operation were not met.</summary>
      //public const uint NERR_ConnectionInsecure = 2718;

      ///// <summary>Computer account provisioning blob version is not supported.</summary>
      //public const uint NERR_RplBootInUse = 2719;

      #endregion // Network Management Error Codes

      #region Configuration Manager Error Codes

      /// <summary>(0) The operation completed successfully.</summary>
      public const uint CR_SUCCESS = 0;

      //public const uint CR_DEFAULT = 1;
      //public const uint CR_OUT_OF_MEMORY = 2;
      //public const uint CR_INVALID_POINTER = 3;
      //public const uint CR_INVALID_FLAG = 4;
      //public const uint CR_INVALID_DEVNODE = 5;
      //public const uint CR_INVALID_DEVINST = CR_INVALID_DEVNODE;
      //public const uint CR_INVALID_RES_DES = 6;
      //public const uint CR_INVALID_LOG_CONF = 7;
      //public const uint CR_INVALID_ARBITRATOR = 8;
      //public const uint CR_INVALID_NODELIST = 9;
      //public const uint CR_DEVNODE_HAS_REQS = 10;
      //public const uint CR_DEVINST_HAS_REQS = CR_DEVNODE_HAS_REQS;
      //public const uint CR_INVALID_RESOURCEID = 11;
      //public const uint CR_DLVXD_NOT_FOUND = 12; // WIN 95 ONLY 
      //public const uint CR_NO_SUCH_DEVNODE = 13;
      //public const uint CR_NO_SUCH_DEVINST = CR_NO_SUCH_DEVNODE;
      //public const uint CR_NO_MORE_LOG_CONF = 14;
      //public const uint CR_NO_MORE_RES_DES = 15;
      //public const uint CR_ALREADY_SUCH_DEVNODE = 16;
      //public const uint CR_ALREADY_SUCH_DEVINST = CR_ALREADY_SUCH_DEVNODE;
      //public const uint CR_INVALID_RANGE_LIST = 17;
      //public const uint CR_INVALID_RANGE = 18;
      //public const uint CR_FAILURE = 19;
      //public const uint CR_NO_SUCH_LOGICAL_DEV = 20;
      //public const uint CR_CREATE_BLOCKED = 21;
      //public const uint CR_NOT_SYSTEM_VM = 22; // WIN 95 ONLY 
      //public const uint CR_REMOVE_VETOED = 23;
      //public const uint CR_APM_VETOED = 24;
      //public const uint CR_INVALID_LOAD_TYPE = 25;
      //public const uint CR_BUFFER_SMALL = 26;
      //public const uint CR_NO_ARBITRATOR = 27;
      //public const uint CR_NO_REGISTRY_HANDLE = 28;
      //public const uint CR_REGISTRY_ERROR = 29;
      //public const uint CR_INVALID_DEVICE_ID = 30;
      //public const uint CR_INVALID_DATA = 31;
      //public const uint CR_INVALID_API = 32;
      //public const uint CR_DEVLOADER_NOT_READY = 33;
      //public const uint CR_NEED_RESTART = 34;
      //public const uint CR_NO_MORE_HW_PROFILES = 35;
      //public const uint CR_DEVICE_NOT_THERE = 36;
      //public const uint CR_NO_SUCH_VALUE = 37;
      //public const uint CR_WRONG_TYPE = 38;
      //public const uint CR_INVALID_PRIORITY = 39;
      //public const uint CR_NOT_DISABLEABLE = 40;
      //public const uint CR_FREE_RESOURCES = 41;
      //public const uint CR_QUERY_VETOED = 42;
      //public const uint CR_CANT_SHARE_IRQ = 43;
      //public const uint CR_NO_DEPENDENT = 44;
      //public const uint CR_SAME_RESOURCES = 45;
      //public const uint CR_NO_SUCH_REGISTRY_KEY = 46;
      //public const uint CR_INVALID_MACHINENAME = 47; // NT ONLY 
      //public const uint CR_REMOTE_COMM_FAILURE = 48; // NT ONLY 
      //public const uint CR_MACHINE_UNAVAILABLE = 49; // NT ONLY 
      //public const uint CR_NO_CM_SERVICES = 50; // NT ONLY 
      //public const uint CR_ACCESS_DENIED = 51; // NT ONLY 
      //public const uint CR_CALL_NOT_IMPLEMENTED = 52;
      //public const uint CR_INVALID_PROPERTY = 53;
      //public const uint CR_DEVICE_INTERFACE_ACTIVE = 54;
      //public const uint CR_NO_SUCH_DEVICE_INTERFACE = 55;
      //public const uint CR_INVALID_REFERENCE_STRING = 56;
      //public const uint NUM_CR_RESULTS = 57;

      #endregion // Configuration Manager Error Codes
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.SMB.GetHostShareFromPath.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Filesystem;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>Gets the host and share path name for the given <paramref name="uncPath"/>.</summary>
      /// <param name="uncPath">The share in the format: \\host\share.</param>
      /// <returns>The host and share path. For example, if <paramref name="uncPath"/> is: "\\SERVER001\C$\WINDOWS\System32",
      ///   its is returned as string[0] = "SERVER001" and string[1] = "\C$\WINDOWS\System32".
      /// <para>If the conversion from local path to UNC path fails, <c>null</c> is returned.</para>
      /// </returns>
      [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")]
      [SecurityCritical]
      public static string[] GetHostShareFromPath(string uncPath)
      {
         if (Utils.IsNullOrWhiteSpace(uncPath))
            return null;

         Uri uri;
         if (Uri.TryCreate(Path.GetRegularPathCore(uncPath, GetFullPathOptions.None, false), UriKind.Absolute, out uri) && uri.IsUnc)
         {
            return new[]
            {
               uri.Host,
               uri.GetComponents(UriComponents.Path, UriFormat.Unescaped).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)
            };
         }

         return null;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File.WriteAllLines.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      #region .NET

      /// <summary>Creates a new file, writes a collection of strings to the file, and then closes the file.</summary>
      /// <remarks>The default behavior of the method is to write out data by using UTF-8 encoding without a byte order mark (BOM).</remarks>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The lines to write to the file.</param>
      [SecurityCritical]
      public static void WriteAllLines(string path, IEnumerable<string> contents)
      {
         WriteAppendAllLinesCore(null, path, contents, new UTF8Encoding(false, true), false, true, PathFormat.RelativePath);
      }


      /// <summary>Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The lines to write to the file.</param>
      /// <param name="encoding">The character <see cref="Encoding"/> to use.</param>
      [SecurityCritical]
      public static void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding)
      {
         WriteAppendAllLinesCore(null, path, contents, encoding, false, true, PathFormat.RelativePath);
      }


      /// <summary>Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.</summary>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The string array to write to the file.</param>
      [SecurityCritical]
      public static void WriteAllLines(string path, string[] contents)
      {
         WriteAppendAllLinesCore(null, path, contents, new UTF8Encoding(false, true), false, true, PathFormat.RelativePath);
      }


      /// <summary>Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The string array to write to the file.</param>
      /// <param name="encoding">The character <see cref="Encoding"/> to use.</param>
      [SecurityCritical]
      public static void WriteAllLines(string path, string[] contents, Encoding encoding)
      {
         WriteAppendAllLinesCore(null, path, contents, encoding, false, true, PathFormat.RelativePath);
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Creates a new file, writes a collection of strings to the file, and then closes the file.</summary>
      /// <remarks>The default behavior of the method is to write out data by using UTF-8 encoding without a byte order mark (BOM).</remarks>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The lines to write to the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void WriteAllLines(string path, IEnumerable<string> contents, PathFormat pathFormat)
      {
         WriteAppendAllLinesCore(null, path, contents, new UTF8Encoding(false, true), false, true, pathFormat);
      }


      /// <summary>[AlphaFS] Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The lines to write to the file.</param>
      /// <param name="encoding">The character <see cref="Encoding"/> to use.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding, PathFormat pathFormat)
      {
         WriteAppendAllLinesCore(null, path, contents, encoding, false, true, pathFormat);
      }


      /// <summary>[AlphaFS] Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The string array to write to the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void WriteAllLines(string path, string[] contents, PathFormat pathFormat)
      {
         WriteAppendAllLinesCore(null, path, contents, new UTF8Encoding(false, true), false, true, pathFormat);
      }
      

      /// <summary>[AlphaFS] Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="path">The file to write to.</param>
      /// <param name="contents">The string array to write to the file.</param>
      /// <param name="encoding">The character <see cref="Encoding"/> to use.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void WriteAllLines(string path, string[] contents, Encoding encoding, PathFormat pathFormat)
      {
         WriteAppendAllLinesCore(null, path, contents, encoding, false, true, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Native Other/NETRESOURCE.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>Contains information about a network resource.
      /// <para>The NETRESOURCE structure is returned during an enumeration of network resources.</para>
      /// <para>The NETRESOURCE structure is also specified when making or querying</para>
      /// <para>a network connection with calls to various Windows Networking functions.</para>
      /// </summary>
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      internal struct NETRESOURCE
      {
         /// <summary>The scope of the enumeration.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly ResourceScope dwScope;

         /// <summary>The type of resource</summary>
         [MarshalAs(UnmanagedType.U4)] public ResourceType dwType;

         /// <summary>The display options for the network object in a network browsing user interface.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly ResourceDisplayType dwDisplayType;

         /// <summary>A set of bit flags describing how the resource can be used.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly ResourceUsage dwUsage;

         /// <summary>If the <see cref="dwScope"/> member is equal to <see cref="ResourceScope.Connected"/> or <see cref="ResourceScope.Remembered"/>,
         /// this member is a pointer to a <c>null</c>-terminated character string that specifies the name of a local device.
         /// This member is <c>null</c> if the connection does not use a device.
         /// </summary>
         [MarshalAs(UnmanagedType.LPWStr)] public string lpLocalName;

         /// <summary>If the entry is a network resource, this member is a <see cref="string"/> that specifies the remote network name.
         /// If the entry is a current or persistent connection, <see cref="lpRemoteName"/> member points to 
         /// the network name associated with the name pointed to by the <see cref="lpLocalName"/> member.
         /// The <see cref="string"/> can be <see cref="Alphaleonis.Win32.Filesystem.NativeMethods.MaxPath"/> characters in length,
         /// and it must follow the network provider's naming conventions.
         /// </summary>
         [MarshalAs(UnmanagedType.LPWStr)] public string lpRemoteName;

         /// <summary>A <see cref="string"/> that contains a comment supplied by the network provider.</summary>
         [MarshalAs(UnmanagedType.LPWStr)] public readonly string lpComment;

         /// <summary>A <see cref="string"/> that contains the name of the provider that owns the resource. 
         /// This member can be <c>null</c> if the provider name is unknown.
         /// </summary>
         [MarshalAs(UnmanagedType.LPWStr)] public readonly string lpProvider;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_WithProgress.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Globalization;

namespace AlphaFS.UnitTest
{
   public partial class CopyTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_File_Copy_WithProgress_LocalAndNetwork_Success()
      {
         AlphaFS_File_Copy_WithProgress(false);
         AlphaFS_File_Copy_WithProgress(true);
      }
      

      private void AlphaFS_File_Copy_WithProgress(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var fileSource = tempRoot.CreateFile();
            var fileCopy = tempRoot.CreateFile();

            Console.WriteLine("Src File Path: [{0}] [{1}]", Alphaleonis.Utils.UnitSizeToText(fileSource.Length), fileSource.FullName);
            Console.WriteLine("Dst File Path: [{0}]", fileCopy.FullName);

            
            // Allow copy to overwrite an existing file.
            const Alphaleonis.Win32.Filesystem.CopyOptions copyOptions = Alphaleonis.Win32.Filesystem.CopyOptions.None;


            // The copy progress handler.
            var callback = new Alphaleonis.Win32.Filesystem.CopyMoveProgressRoutine(FileCopyProgressHandler);


            Console.WriteLine();


            // You can pass any piece of data to userProgressData. This data can be accessed from the callback method.
            // Specify file length for assertion.
            var userProgressData = fileSource.Length;


            var copyResult = Alphaleonis.Win32.Filesystem.File.Copy(fileSource.FullName, fileCopy.FullName, copyOptions, callback, userProgressData);

            UnitTestConstants.Dump(copyResult);


            Assert.IsTrue(System.IO.File.Exists(fileCopy.FullName), "The file does not exists, but is expected to.");


            Assert.AreEqual(fileSource.Length, fileCopy.Length, "The file sizes do no match, but are expected to.");

            Assert.IsTrue(System.IO.File.Exists(fileSource.FullName), "The original file does not exist, but is expected to.");
         }
         
         Console.WriteLine();
      }


      private static Alphaleonis.Win32.Filesystem.CopyMoveProgressResult FileCopyProgressHandler(long totalFileSize, long totalBytesTransferred, long streamSize,
         long streamBytesTransferred, int streamNumber, Alphaleonis.Win32.Filesystem.CopyMoveProgressCallbackReason callbackReason, object userData)
      {
         if (callbackReason == Alphaleonis.Win32.Filesystem.CopyMoveProgressCallbackReason.StreamSwitch)

            Assert.AreEqual(0, totalBytesTransferred);


         else
         {
            var pct = Convert.ToDouble(totalBytesTransferred, CultureInfo.InvariantCulture) / totalFileSize * 100;

            Console.WriteLine("\tCallback: Copied: [{0}%] --> [{1:N0}] bytes.", pct.ToString("N2", CultureInfo.CurrentCulture), totalBytesTransferred);

            Assert.IsTrue(totalBytesTransferred > 0);


            var bytes = Convert.ToInt64(userData);

            if (pct.Equals(100))
            {
               Assert.AreEqual(totalBytesTransferred, bytes);
               Assert.AreEqual(totalFileSize, bytes);
            }

            else
               Assert.IsTrue(totalBytesTransferred < bytes);
         }


         return Alphaleonis.Win32.Filesystem.CopyMoveProgressResult.Continue;
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Enumerations/SessionInfoLevel.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

namespace Alphaleonis.Win32.Network
{
   /// <summary>The <see cref="SessionInfo"/> information level.</summary>
   public enum SessionInfoLevel
   {
      /// <summary>Contains the name of the computer that established the session.</summary>
      Info0 = 0,
      
      /// <summary>Contains information about the session, including name of the computer; name of the user; and open files, pipes, and devices on the computer.</summary>
      Info1 = 1,
      
      /// <summary>Contains information about the session, including name of the computer; name of the user; open files, pipes, and devices on the computer; and the type of client that established the session.</summary>
      Info2 = 2,
      
      /// <summary>Contains information about the session, including name of the computer; name of the user; and active and idle times for the session.</summary>
      Info10 = 10,

      /// <summary>Contains information about the session, including name of the computer; name of the user; open files, pipes, and devices on the computer; and the name of the transport the client is using.</summary>
      Info502 = 502
   }
}


<|start_filename|>src/AlphaFS/Device/DriveInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Provides access to information on a local or remote drive.</summary>
   /// <remarks>
   /// This class models a drive and provides methods and properties to query for drive information.
   /// Use DriveInfo to determine what drives are available, and what type of drives they are.
   /// You can also query to determine the capacity and available free space on the drive.
   /// </remarks>
   [Serializable]
   [SecurityCritical]
   public sealed class DriveInfo
   {
      [NonSerialized] private readonly VolumeInfo _volumeInfo;
      [NonSerialized] private readonly DiskSpaceInfo _dsi;
      [NonSerialized] private bool _initDsie;
      [NonSerialized] private DriveType? _driveType;
      [NonSerialized] private string _dosDeviceName;
      [NonSerialized] private DirectoryInfo _rootDirectory;
      [NonSerialized] private readonly string _name;


      #region Constructors

      /// <summary>Provides access to information on the specified drive.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <param name="driveName">
      ///   A valid drive path or drive letter.
      ///   <para>This can be either uppercase or lowercase,</para>
      ///   <para>'a' to 'z' or a network share in the format: \\server\share</para>
      /// </param>
      [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")]
      [SecurityCritical]
      public DriveInfo(string driveName)
      {
         if (Utils.IsNullOrWhiteSpace(driveName))
            throw new ArgumentNullException("driveName");


         driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false);

         if (Utils.IsNullOrWhiteSpace(driveName))
            throw new ArgumentException(Resources.InvalidDriveLetterArgument, "driveName");


         _name = Path.AddTrailingDirectorySeparator(driveName, false);

         // Initiate VolumeInfo() lazyload instance.
         _volumeInfo = new VolumeInfo(_name, false, true);

         // Initiate DiskSpaceInfo() lazyload instance.
         _dsi = new DiskSpaceInfo(_name, null, false, true);
      }

      #endregion // Constructors


      #region Properties

      /// <summary>Indicates the amount of available free space on a drive.</summary>
      /// <returns>The amount of free space available on the drive, in bytes.</returns>
      /// <remarks>This property indicates the amount of free space available on the drive. Note that this number may be different from the <see cref="TotalFreeSpace"/> number because this property takes into account disk quotas.</remarks>
      public long AvailableFreeSpace
      {
         get
         {
            GetDeviceInfo(3, 0);
            return null == _dsi ? 0 : _dsi.FreeBytesAvailable;
         }
      }

      /// <summary>Gets the name of the file system, such as NTFS or FAT32.</summary>
      /// <remarks>Use DriveFormat to determine what formatting a drive uses.</remarks>
      public string DriveFormat
      {
         get { return (string) GetDeviceInfo(0, 1); }
      }


      /// <summary>Gets the drive type.</summary>
      /// <returns>One of the <see cref="System.IO.DriveType"/> values.</returns>
      /// <remarks>
      /// The DriveType property indicates whether a drive is any of: CDRom, Fixed, Unknown, Network, NoRootDirectory,
      /// Ram, Removable, or Unknown. Values are listed in the <see cref="System.IO.DriveType"/> enumeration.
      /// </remarks>
      public DriveType DriveType
      {
         get { return (DriveType) GetDeviceInfo(2, 0); }
      }


      /// <summary>Gets a value indicating whether a drive is ready.</summary>
      /// <returns><c>true</c> if the drive is ready; otherwise, <c>false</c>.</returns>
      /// <remarks>
      /// IsReady indicates whether a drive is ready. For example, it indicates whether a CD is in a CD drive or whether
      /// a removable storage device is ready for read/write operations. If you do not test whether a drive is ready, and
      /// it is not ready, querying the drive using DriveInfo will raise an IOException.
      /// 
      /// Do not rely on IsReady() to avoid catching exceptions from other members such as TotalSize, TotalFreeSpace, and DriveFormat.
      /// Between the time that your code checks IsReady and then accesses one of the other properties
      /// (even if the access occurs immediately after the check), a drive may have been disconnected or a disk may have been removed.
      /// </remarks>
      public bool IsReady
      {
         get { return File.ExistsCore(null, true, Name, PathFormat.LongFullPath); }
      }


      /// <summary>Gets the name of the drive.</summary>
      /// <returns>The name of the drive.</returns>
      /// <remarks>This property is the name assigned to the drive, such as C:\ or E:\</remarks>
      public string Name
      {
         get { return _name; }
      }


      /// <summary>Gets the root directory of a drive.</summary>
      /// <returns>A DirectoryInfo object that contains the root directory of the drive.</returns>
      public DirectoryInfo RootDirectory
      {
         get { return (DirectoryInfo) GetDeviceInfo(2, 1); }
      }

      /// <summary>Gets the total amount of free space available on a drive.</summary>
      /// <returns>The total free space available on a drive, in bytes.</returns>
      /// <remarks>This property indicates the total amount of free space available on the drive, not just what is available to the current user.</remarks>
      public long TotalFreeSpace
      {
         get
         {
            GetDeviceInfo(3, 0);
            return null == _dsi ? 0 : _dsi.TotalNumberOfFreeBytes;
         }
      }


      /// <summary>Gets the total size of storage space on a drive.</summary>
      /// <returns>The total size of the drive, in bytes.</returns>
      /// <remarks>This property indicates the total size of the drive in bytes, not just what is available to the current user.</remarks>
      public long TotalSize
      {
         get
         {
            GetDeviceInfo(3, 0);
            return null == _dsi ? 0 : _dsi.TotalNumberOfBytes;
         }
      }


      /// <summary>Gets or sets the volume label of a drive.</summary>
      /// <returns>The volume label.</returns>
      /// <remarks>
      /// The label length is determined by the operating system. For example, NTFS allows a volume label
      /// to be up to 32 characters long. Note that <c>null</c> is a valid VolumeLabel.
      /// </remarks>
      public string VolumeLabel
      {
         get { return (string) GetDeviceInfo(0, 2); }
         set { Volume.SetVolumeLabel(Name, value); }
      }

      /// <summary>[AlphaFS] Returns the <see ref="Alphaleonis.Win32.Filesystem.DiskSpaceInfo"/> instance.</summary>
      public DiskSpaceInfo DiskSpaceInfo
      {
         get
         {
            GetDeviceInfo(3, 0);
            return _dsi;
         }
      }


      /// <summary>[AlphaFS] The MS-DOS device name.</summary>
      public string DosDeviceName
      {
         get { return (string) GetDeviceInfo(1, 0); }
      }


      /// <summary>[AlphaFS] Indicates if this drive is a SUBST.EXE / DefineDosDevice drive mapping.</summary>
      public bool IsDosDeviceSubstitute
      {
         get { return !Utils.IsNullOrWhiteSpace(DosDeviceName) && DosDeviceName.StartsWith(Path.NonInterpretedPathPrefix, StringComparison.OrdinalIgnoreCase); }
      }


      /// <summary>[AlphaFS] Indicates if this drive is a UNC path.</summary>
      public bool IsUnc
      {
         get
         {
            return !IsDosDeviceSubstitute && DriveType == DriveType.Network ||
               
                   // Handle Host devices with file systems: FAT/FAT32, UDF (CDRom), ...
                   Name.StartsWith(Path.UncPrefix, StringComparison.Ordinal) && DriveType == DriveType.NoRootDirectory && DriveFormat.Equals(DriveType.Unknown.ToString(), StringComparison.OrdinalIgnoreCase);
         }
      }


      /// <summary>[AlphaFS] Determines whether the specified volume name is a defined volume on the current computer.</summary>
      public bool IsVolume
      {
         get { return null != GetDeviceInfo(0, 0); }
      }


      /// <summary>[AlphaFS] Contains information about a file-system volume.</summary>
      /// <returns>A VolumeInfo object that contains file-system volume information of the drive.</returns>
      public VolumeInfo VolumeInfo
      {
         get { return (VolumeInfo) GetDeviceInfo(0, 0); }
      }


      #endregion // Properties


      #region Methods

      #region .NET

      /// <summary>Retrieves the <see cref="DriveInfo"/> of all logical drives on the Computer.</summary>
      /// <returns>An array of type <see cref="Alphaleonis.Win32.Filesystem.DriveInfo"/> that represents the logical drives on the Computer.</returns>
      [SecurityCritical]
      public static DriveInfo[] GetDrives()
      {
         return Directory.EnumerateLogicalDrivesCore(false, false).ToArray();
      }


      /// <summary>Returns a drive name as a string.</summary>
      /// <returns>The name of the drive.</returns>
      /// <remarks>This method returns the Name property.</remarks>
      public override string ToString()
      {
         return _name;
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Enumerates the drive names of all logical drives on the Computer.</summary>
      /// <param name="fromEnvironment">Retrieve logical drives as known by the Environment.</param>
      /// <param name="isReady">Retrieve only when accessible (IsReady) logical drives.</param>
      /// <returns>
      ///   An IEnumerable of type <see cref="Alphaleonis.Win32.Filesystem.DriveInfo"/> that represents
      ///   the logical drives on the Computer.
      /// </returns>      
      [SecurityCritical]
      public static IEnumerable<DriveInfo> EnumerateDrives(bool fromEnvironment, bool isReady)
      {
         return Directory.EnumerateLogicalDrivesCore(fromEnvironment, isReady);
      }


      /// <summary>[AlphaFS] Gets the first available drive letter on the local system.</summary>
      /// <returns>A drive letter as <see cref="char"/>. When no drive letters are available, an exception is thrown.</returns>
      /// <remarks>The letters "A" and "B" are reserved for floppy drives and will never be returned by this function.</remarks>
      public static char GetFreeDriveLetter()
      {
         return GetFreeDriveLetter(false);
      }


      /// <summary>Gets an available drive letter on the local system.</summary>
      /// <param name="getLastAvailable">When <c>true</c> get the last available drive letter. When <c>false</c> gets the first available drive letter.</param>
      /// <returns>A drive letter as <see cref="char"/>. When no drive letters are available, an exception is thrown.</returns>
      /// <remarks>The letters "A" and "B" are reserved for floppy drives and will never be returned by this function.</remarks>
      /// <exception cref="ArgumentOutOfRangeException">No drive letters available.</exception>
      [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
      public static char GetFreeDriveLetter(bool getLastAvailable)
      {
         var freeDriveLetters = "CDEFGHIJKLMNOPQRSTUVWXYZ".Except(Directory.EnumerateLogicalDrivesCore(false, false).Select(d => d.Name[0]));

         try
         {
            return getLastAvailable ? freeDriveLetters.Last() : freeDriveLetters.First();
         }
         catch
         {
            throw new ArgumentOutOfRangeException(Resources.No_Drive_Letters_Available);
         }
      }

      #endregion // Methods


      #region Private Methods

      /// <summary>Retrieves information about the file system and volume associated with the specified root file or directorystream.</summary>
      [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      [SecurityCritical]
      private object GetDeviceInfo(int type, int mode)
      {
         try
         {
            switch (type)
            {
               #region Volume

               // VolumeInfo properties.
               case 0:
                  if (Utils.IsNullOrWhiteSpace(_volumeInfo.FullPath))
                     _volumeInfo.Refresh();

                  switch (mode)
                  {
                     case 0:
                        // IsVolume, VolumeInfo
                        return _volumeInfo;

                     case 1:
                        // DriveFormat
                        return null == _volumeInfo ? DriveType.Unknown.ToString() : _volumeInfo.FileSystemName ?? DriveType.Unknown.ToString();

                     case 2:
                        // VolumeLabel
                        return null == _volumeInfo ? string.Empty : _volumeInfo.Name ?? string.Empty;
                  }

                  break;


               // Volume related.
               case 1:
                  switch (mode)
                  {
                     case 0:
                        // DosDeviceName
                        return _dosDeviceName ?? (_dosDeviceName = Volume.GetVolumeDeviceName(Name));
                  }

                  break;

               #endregion // Volume


               #region Drive

               // Drive related.
               case 2:
                  switch (mode)
                  {
                     case 0:
                        // DriveType
                        return _driveType ?? (_driveType = Volume.GetDriveType(Name));

                     case 1:
                        // RootDirectory
                        return _rootDirectory ?? (_rootDirectory = new DirectoryInfo(null, Name, PathFormat.RelativePath));
                  }

                  break;

               // DiskSpaceInfo related.
               case 3:
                  switch (mode)
                  {
                     case 0:
                        // AvailableFreeSpace, TotalFreeSpace, TotalSize, DiskSpaceInfo
                        if (!_initDsie)
                        {
                           _dsi.Refresh();
                           _initDsie = true;
                        }

                        break;
                  }

                  break;

               #endregion // Drive
            }
         }
         catch
         {
         }

         return type == 0 && mode > 0 ? string.Empty : null;
      }
      
      #endregion // Private
   }
}


<|start_filename|>src/AlphaFS/Filesystem/FileInfo Class/FileInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Provides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of <see cref="FileStream"/> objects. This class cannot be inherited.</summary>
   [Serializable]
   public sealed partial class FileInfo : FileSystemInfo
   {
      #region Fields

      [NonSerialized]
      private string _name;

      #endregion // Fields


      #region Constructors

      #region .NET

      /// <summary>Initializes a new instance of the <see cref="Alphaleonis.Win32.Filesystem.FileInfo"/> class, which acts as a wrapper for a file path.</summary>
      /// <param name="fileName">The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character.</param>
      /// <remarks>This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations.</remarks>
      public FileInfo(string fileName) : this(null, fileName, PathFormat.RelativePath)
      {
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Initializes a new instance of the <see cref="Alphaleonis.Win32.Filesystem.FileInfo"/> class, which acts as a wrapper for a file path.</summary>
      /// <param name="fileName">The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <remarks>This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations.</remarks>
      public FileInfo(string fileName, PathFormat pathFormat) : this(null, fileName, pathFormat)
      {
      }


      /// <summary>[AlphaFS] Initializes a new instance of the <see cref="Alphaleonis.Win32.Filesystem.FileInfo"/> class, which acts as a wrapper for a file path.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="fileName">The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character.</param>
      /// <remarks>This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations.</remarks>
      public FileInfo(KernelTransaction transaction, string fileName) : this(transaction, fileName, PathFormat.RelativePath)
      {
      }


      /// <summary>[AlphaFS] Initializes a new instance of the <see cref="Alphaleonis.Win32.Filesystem.FileInfo"/> class, which acts as a wrapper for a file path.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="fileName">The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <remarks>This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations.</remarks>
      public FileInfo(KernelTransaction transaction, string fileName, PathFormat pathFormat)
      {
         InitializeCore(transaction, false, fileName, pathFormat);

         _name = Path.GetFileName(Path.RemoveTrailingDirectorySeparator(fileName), pathFormat != PathFormat.LongFullPath);
      }

      #endregion // Constructors


      #region Properties

      #region .NET

      /// <summary>Gets an instance of the parent directory.</summary>
      /// <value>A <see cref="DirectoryInfo"/> object representing the parent directory of this file.</value>
      /// <remarks>To get the parent directory as a string, use the DirectoryName property.</remarks>
      /// <exception cref="DirectoryNotFoundException"/>
      public DirectoryInfo Directory
      {
         get
         {
            var dirName = DirectoryName;
            return dirName == null ? null : new DirectoryInfo(Transaction, dirName, PathFormat.FullPath);
         }
      }


      /// <summary>Gets a string representing the directory's full path.</summary>
      /// <value>A string representing the directory's full path.</value>
      /// <remarks>
      ///   <para>To get the parent directory as a DirectoryInfo object, use the Directory property.</para>
      ///   <para>When first called, FileInfo calls Refresh and caches information about the file.</para>
      ///   <para>On subsequent calls, you must call Refresh to get the latest copy of the information.</para>
      /// </remarks>
      /// <exception cref="ArgumentNullException"/>
      public string DirectoryName
      {
         [SecurityCritical]
         get { return Path.GetDirectoryName(FullPath, false); }
      }


      /// <summary>Gets a value indicating whether the file exists.</summary>
      /// <value><c>true</c> if the file exists; otherwise, <c>false</c>.</value>
      /// <remarks>
      ///   <para>The <see cref="Exists"/> property returns <c>false</c> if any error occurs while trying to determine if the specified file exists.</para>
      ///   <para>This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters,</para>
      ///   <para>a failing or missing disk, or if the caller does not have permission to read the file.</para>
      /// </remarks>
      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      public override bool Exists
      {
         [SecurityCritical]
         get
         {
            try
            {
               if (DataInitialised == -1)
                  Refresh();

               var attrs = Win32AttributeData.dwFileAttributes;

               return DataInitialised == 0 && File.HasValidAttributes(attrs) && !IsDirectory;
            }
            catch
            {
               return false;
            }
         }
      }


      /// <summary>Gets or sets a value that determines if the current file is read only.</summary>
      /// <value><c>true</c> if the current file is read only; otherwise, <c>false</c>.</value>
      /// <remarks>
      ///   <para>Use the IsReadOnly property to quickly determine or change whether the current file is read only.</para>
      ///   <para>When first called, FileInfo calls Refresh and caches information about the file.</para>
      ///   <para>On subsequent calls, you must call Refresh to get the latest copy of the information.</para>
      /// </remarks>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      public bool IsReadOnly
      {
         get { return EntryInfo == null || EntryInfo.IsReadOnly; }

         set
         {
            if (value)
               Attributes |= FileAttributes.ReadOnly;
            else
               Attributes &= ~FileAttributes.ReadOnly;
         }
      }


      /// <summary>Gets the size, in bytes, of the current file.</summary>
      /// <value>The size of the current file in bytes.</value>
      /// <remarks>
      ///   <para>The value of the Length property is pre-cached</para>
      ///   <para>To get the latest value, call the Refresh method.</para>
      /// </remarks>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
      public long Length
      {
         [SecurityCritical]
         get
         {
            if (DataInitialised == -1)
            {
               Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
               Refresh();
            }

            // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. 
            if (DataInitialised != 0)
               NativeError.ThrowException(DataInitialised, FullName);


            var attrs = Win32AttributeData.dwFileAttributes;

            // MSDN: .NET 3.5+: FileNotFoundException: The file does not exist or the Length property is called for a directory.
            if (!File.HasValidAttributes(attrs))
               NativeError.ThrowException(Win32Errors.ERROR_FILE_NOT_FOUND, FullName);


            // MSDN: .NET 3.5+: FileNotFoundException: The file does not exist or the Length property is called for a directory.
            if (File.IsDirectory(attrs))
               NativeError.ThrowException(Win32Errors.ERROR_FILE_NOT_FOUND, string.Format(CultureInfo.InvariantCulture, Resources.Target_File_Is_A_Directory, FullName));


            return Win32AttributeData.FileSize;
         }
      }


      /// <summary>Gets the name of the file.</summary>
      /// <value>The name of the file.</value>
      /// <remarks>
      ///   <para>The name of the file includes the file extension.</para>
      ///   <para>When first called, <see cref="FileInfo"/> calls Refresh and caches information about the file.</para>
      ///   <para>On subsequent calls, you must call Refresh to get the latest copy of the information.</para>
      ///   <para>The name of the file includes the file extension.</para>
      /// </remarks>
      public override string Name
      {
         get { return _name; }
      }

      #endregion // .NET

      #endregion // Properties


      #region Methods

      /// <summary>Returns the path as a string.</summary>
      /// <returns>The path.</returns>
      public override string ToString()
      {
         return DisplayPath;
      }

      #endregion // Methods
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Other/MOVE_FILE_FLAGS.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      public enum MOVE_FILE_FLAGS
      {
         /// <summary>No MoveOptions used, this fails when the file name already exists.</summary>
         None = 0,

         /// <summary>MOVE_FILE_REPLACE_EXISTSING
         /// <para>If the destination file name already exists, the function replaces its contents with the contents of the source file.</para>
         /// <para>This value cannot be used if lpNewFileName or lpExistingFileName names a directory.</para>
         /// <para>This value cannot be used if either source or destination names a directory.</para>
         /// </summary>
         MOVE_FILE_REPLACE_EXISTSING = 1,

         /// <summary>MOVE_FILE_COPY_ALLOWED
         /// <para>If the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions.</para>
         /// <para>This value cannot be used with <see cref="MOVE_FILE_FLAGS.MOVE_FILE_DELAY_UNTIL_REBOOT"/>.</para>
         /// </summary>
         MOVE_FILE_COPY_ALLOWED = 2,

         /// <summary>MOVE_FILE_DELAY_UNTIL_REBOOT
         /// <para>
         /// The system does not move the file until the operating system is restarted.
         /// The system moves the file immediately after AUTOCHK is executed, but before creating any paging files.
         /// </para>
         /// <para>
         /// Consequently, this parameter enables the function to delete paging files from previous startups.
         /// This value can only be used if the process is in the context of a user who belongs to the administrators group or the LocalSystem account.
         /// </para>
         /// <para>This value cannot be used with <see cref="MOVE_FILE_FLAGS.MOVE_FILE_COPY_ALLOWED"/>.</para>
         /// </summary>
         MOVE_FILE_DELAY_UNTIL_REBOOT = 4,


         /// <summary>MOVE_FILE_WRITE_THROUGH
         /// <para>The function does not return until the file has actually been moved on the disk.</para>
         /// <para>
         /// Setting this value guarantees that a move performed as a copy and delete operation is flushed to disk before the function returns.
         /// The flush occurs at the end of the copy operation.
         /// </para>
         /// <para>This value has no effect if <see cref="MOVE_FILE_FLAGS.MOVE_FILE_DELAY_UNTIL_REBOOT"/> is set.</para>
         /// </summary>
         MOVE_FILE_WRITE_THROUGH = 8,


         /// <summary>MOVE_FILE_CREATE_HARDLINK
         /// <para>Reserved for future use.</para>
         /// </summary>
         MOVE_FILE_CREATE_HARDLINK = 16,


         /// <summary>MOVE_FILE_FAIL_IF_NOT_TRACKABLE
         /// <para>The function fails if the source file is a link source, but the file cannot be tracked after the move.</para>
         /// <para>This situation can occur if the destination is a volume formatted with the FAT file system.</para>
         /// </summary>
         MOVE_FILE_FAIL_IF_NOT_TRACKABLE = 32
      }
   }
}


<|start_filename|>src/AlphaFS/Device/DeviceInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Network;
using System;
using System.Collections.Generic;
using System.Security;
using System.Security.Permissions;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Provides access to information of a device, on a local or remote host.</summary>
   [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
   [Serializable]
   [SecurityCritical]
   public sealed class DeviceInfo
   {
      #region Constructors
      
      /// <summary>Initializes a DeviceInfo class.</summary>
      [SecurityCritical]
      public DeviceInfo()
      {
         HostName = Host.GetUncName();
      }

      /// <summary>Initializes a DeviceInfo class.</summary>
      /// <param name="host">The DNS or NetBIOS name of the remote server. <c>null</c> refers to the local host.</param>
      [SecurityCritical]
      public DeviceInfo(string host)
      {
         HostName = Host.GetUncName(host).Replace(Path.UncPrefix, string.Empty);
      }

      #endregion // Constructors


      #region Methods

      /// <summary>Enumerates all available devices on the local host.</summary>
      /// <param name="deviceGuid">One of the <see cref="Filesystem.DeviceGuid"/> devices.</param>
      /// <returns><see cref="IEnumerable{DeviceInfo}"/> instances of type <see cref="Filesystem.DeviceGuid"/> from the local host.</returns>
      [SecurityCritical]
      public IEnumerable<DeviceInfo> EnumerateDevices(DeviceGuid deviceGuid)
      {
         return Device.EnumerateDevicesCore(HostName, deviceGuid, true);
      }
      
      #endregion // Methods


      #region Properties

      /// <summary>Represents the <see cref="Guid"/> value of the base container identifier (ID) .The Windows Plug and Play (PnP) manager assigns this value to the device node (devnode).</summary>
      public Guid BaseContainerId { get; internal set; }


      /// <summary>Represents the name of the device setup class that a device instance belongs to.</summary>
      public string DeviceClass { get; internal set; }


      /// <summary>Represents the <see cref="Guid"/> of the device setup class that a device instance belongs to.</summary>
      public Guid ClassGuid { get; internal set; }


      /// <summary>Represents the list of compatible identifiers for a device instance.</summary>
      public string CompatibleIds { get; internal set; }


      /// <summary>Represents a description of a device instance.</summary>
      public string DeviceDescription { get; internal set; }


      /// <summary>The device interface path.</summary>
      public string DevicePath { get; internal set; }


      /// <summary>Represents the registry entry name of the driver key for a device instance.</summary>
      public string Driver { get; internal set; }


      /// <summary>Represents the name of the enumerator for a device instance.</summary>
      public string EnumeratorName { get; internal set; }


      /// <summary>Represents the friendly name of a device instance.</summary>
      public string FriendlyName { get; internal set; }


      /// <summary>Represents the list of hardware identifiers for a device instance.</summary>
      public string HardwareId { get; internal set; }


      /// <summary>The host name that was passed to the class constructor.</summary>
      public string HostName { get; internal set; }


      /// <summary>Gets the instance Id of the device.</summary>
      public string InstanceId { get; internal set; }


      /// <summary>Represents the bus-specific physical location of a device instance.</summary>
      public string LocationInformation { get; internal set; }


      /// <summary>Represents the location of a device instance in the device tree.</summary>
      public string LocationPaths { get; internal set; }


      /// <summary>Represents the name of the manufacturer of a device instance.</summary>
      public string Manufacturer { get; internal set; }


      /// <summary>Encapsulates the physical device location information provided by a device's firmware to Windows.</summary>
      public string PhysicalDeviceObjectName { get; internal set; }


      /// <summary>Represents the name of the service that is installed for a device instance.</summary>
      public string Service { get; internal set; }

      #endregion // Properties
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Security;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>[AlphaFS] Returns an enumerable collection of networks available on the local host.</summary>
      /// <returns>An <see cref="IEnumerable{NetworkInfo}"/> collection of connected and disconnected networks on the local host.</returns>
      [SecurityCritical]
      public static IEnumerable<NetworkInfo> EnumerateNetworks()
      {
         return EnumerateNetworksCore(null, NetworkConnectivityLevels.All);
      }


      /// <summary>[AlphaFS] Returns an enumerable collection of networks available on the local host.</summary>
      /// <returns>An <see cref="IEnumerable{NetworkInfo}"/> collection of networks on the local host, as specified by <paramref name="networkConnectivityLevels"/>.</returns>
      /// <param name="networkConnectivityLevels">The <see cref="NetworkConnectivityLevels"/> that specify the connectivity level of the returned <see cref="NetworkInfo"/> instances.</param>
      [SecurityCritical]
      public static IEnumerable<NetworkInfo> EnumerateNetworks(NetworkConnectivityLevels networkConnectivityLevels)
      {
         return EnumerateNetworksCore(null, networkConnectivityLevels);
      }




      /// <summary>[AlphaFS] Returns an enumerable collection of networks available on the local host.</summary>
      /// <returns>An <see cref="IEnumerable{NetworkInfo}"/> collection of networks on the local host, as specified by <paramref name="networkConnectivityLevels"/>.</returns>
      /// <param name="networkID">The <see cref="Guid"/> that defines a network.</param>
      /// <param name="networkConnectivityLevels">The <see cref="NetworkConnectivityLevels"/> that specify the connectivity level of the returned <see cref="NetworkInfo"/> instances.</param>
      [SecurityCritical]
      internal static IEnumerable<NetworkInfo> EnumerateNetworksCore(Guid? networkID, NetworkConnectivityLevels networkConnectivityLevels)
      {
         if (null != networkID)
            yield return new NetworkInfo(Manager.GetNetwork((Guid) networkID));

         else
         {
            foreach (NativeMethods.INetwork network in Manager.GetNetworks(networkConnectivityLevels))

               yield return new NetworkInfo(network);
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Text.RegularExpressions;

#if !NET35
using System.Threading;
#endif

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Class that retrieves file system entries (i.e. files and directories) using Win32 API FindFirst()/FindNext().</summary>
   [Serializable]
   internal sealed class FindFileSystemEntryInfo
   {
      #region Fields

      [NonSerialized] private static readonly Regex WildcardMatchAll = new Regex(@"^(\*)+(\.\*+)+$", RegexOptions.IgnoreCase | RegexOptions.Compiled); // special case to recognize *.* or *.** etc
      [NonSerialized] private Regex _nameFilter;
      [NonSerialized] private string _searchPattern = Path.WildcardStarMatchAll;

      #endregion // Fields


      #region Constructor

      /// <summary>Initializes a new instance of the <see cref="FindFileSystemEntryInfo"/> class.</summary>
      /// <param name="transaction">The NTFS Kernel transaction, if used.</param>
      /// <param name="isFolder">if set to <c>true</c> the path is a folder.</param>
      /// <param name="path">The path.</param>
      /// <param name="searchPattern">The wildcard search pattern.</param>
      /// <param name="options">The enumeration options.</param>
      /// <param name="customFilters">The custom filters.</param>
      /// <param name="pathFormat">The format of the path.</param>
      /// <param name="typeOfT">The type of objects to be retrieved.</param>
      [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
      public FindFileSystemEntryInfo(KernelTransaction transaction, bool isFolder, string path, string searchPattern, DirectoryEnumerationOptions? options, DirectoryEnumerationFilters customFilters, PathFormat pathFormat, Type typeOfT)
      {
         if (null == options)
            throw new ArgumentNullException("options");


         Transaction = transaction;

         OriginalInputPath = path;

         InputPath = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

         IsRelativePath = !Path.IsPathRooted(OriginalInputPath, false);

         RelativeAbsolutePrefix = IsRelativePath ? InputPath.Replace(OriginalInputPath, string.Empty) : null;
         
         SearchPattern = searchPattern.TrimEnd(Path.TrimEndChars); // .NET behaviour.

         FileSystemObjectType = null;

         ContinueOnException = (options & DirectoryEnumerationOptions.ContinueOnException) != 0;

         AsLongPath = (options & DirectoryEnumerationOptions.AsLongPath) != 0;

         AsString = typeOfT == typeof(string);
         AsFileSystemInfo = !AsString && (typeOfT == typeof(FileSystemInfo) || typeOfT.BaseType == typeof(FileSystemInfo));

         LargeCache = (options & DirectoryEnumerationOptions.LargeCache) != 0 ? NativeMethods.UseLargeCache : NativeMethods.FIND_FIRST_EX_FLAGS.NONE;

         // Only FileSystemEntryInfo makes use of (8.3) AlternateFileName.
         FindExInfoLevel = AsString || AsFileSystemInfo || (options & DirectoryEnumerationOptions.BasicSearch) != 0 ? NativeMethods.FindexInfoLevel : NativeMethods.FINDEX_INFO_LEVELS.Standard;


         if (null != customFilters)
         {
            InclusionFilter = customFilters.InclusionFilter;

            RecursionFilter = customFilters.RecursionFilter;

            ErrorHandler = customFilters.ErrorFilter;

#if !NET35
            CancellationToken = customFilters.CancellationToken;
#endif
         }


         if (isFolder)
         {
            IsDirectory = true;

            Recursive = (options & DirectoryEnumerationOptions.Recursive) != 0 || null != RecursionFilter;

            SkipReparsePoints = (options & DirectoryEnumerationOptions.SkipReparsePoints) != 0;


            // Need folders or files to enumerate.
            if ((options & DirectoryEnumerationOptions.FilesAndFolders) == 0)
               options |= DirectoryEnumerationOptions.FilesAndFolders;
         }

         else
         {
            options &= ~DirectoryEnumerationOptions.Folders; // Remove enumeration of folders.
            options |= DirectoryEnumerationOptions.Files; // Add enumeration of files.
         }


         FileSystemObjectType = (options & DirectoryEnumerationOptions.FilesAndFolders) == DirectoryEnumerationOptions.FilesAndFolders

            // Folders and files (null).
            ? (bool?) null

            // Only folders (true) or only files (false).
            : (options & DirectoryEnumerationOptions.Folders) != 0;
      }

      #endregion // Constructor


      #region Properties

      /// <summary>Gets or sets the ability to return the object as a <see cref="FileSystemInfo"/> instance.</summary>
      /// <value><c>true</c> returns the object as a <see cref="FileSystemInfo"/> instance.</value>
      public bool AsFileSystemInfo { get; private set; }


      /// <summary>Gets or sets the ability to return the full path in long full path format.</summary>
      /// <value><c>true</c> returns the full path in long full path format, <c>false</c> returns the full path in regular path format.</value>
      public bool AsLongPath { get; private set; }


      /// <summary>Gets or sets the ability to return the object instance as a <see cref="string"/>.</summary>
      /// <value><c>true</c> returns the full path of the object as a <see cref="string"/></value>
      public bool AsString { get; private set; }


      /// <summary>Gets or sets the ability to skip on access errors.</summary>
      /// <value><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as ACLs protected directories or non-accessible reparse points.</value>
      public bool ContinueOnException { get; private set; }


      /// <summary>Gets the file system object type.</summary>
      /// <value>
      /// <c>null</c> = Return files and directories.
      /// <c>true</c> = Return only directories.
      /// <c>false</c> = Return only files.
      /// </value>
      public bool? FileSystemObjectType { get; private set; }


      /// <summary>Gets or sets if the path is an absolute or relative path.</summary>
      /// <value>Gets a value indicating whether the specified path string contains absolute or relative path information.</value>
      public bool IsRelativePath { get; private set; }

      
      /// <summary>Gets or sets the initial path to the folder.</summary>
      /// <value>The initial path to the file or folder in long path format.</value>
      public string OriginalInputPath { get; private set; }


      /// <summary>Gets or sets the path to the folder.</summary>
      /// <value>The path to the file or folder in long path format.</value>
      public string InputPath { get; private set; }


      /// <summary>Gets or sets the absolute full path prefix of the relative path.</summary>
      private string RelativeAbsolutePrefix { get; set; }

      
      /// <summary>Gets or sets a value indicating which <see cref="NativeMethods.FINDEX_INFO_LEVELS"/> to use.</summary>
      /// <value><c>true</c> indicates a folder object, <c>false</c> indicates a file object.</value>
      public bool IsDirectory { get; private set; }


      /// <summary>Uses a larger buffer for directory queries, which can increase performance of the find operation.</summary>
      /// <remarks>This value is not supported until Windows Server 2008 R2 and Windows 7.</remarks>
      public NativeMethods.FIND_FIRST_EX_FLAGS LargeCache { get; private set; }


      /// <summary>The FindFirstFileEx function does not query the short file name, improving overall enumeration speed.</summary>
      /// <remarks>This value is not supported until Windows Server 2008 R2 and Windows 7.</remarks>
      public NativeMethods.FINDEX_INFO_LEVELS FindExInfoLevel { get; private set; }


      /// <summary>Specifies whether the search should include only the current directory or should include all subdirectories.</summary>
      /// <value><c>true</c> to include all subdirectories.</value>
      public bool Recursive { get; private set; }


      /// <summary>Search for file system object-name using a pattern.</summary>
      /// <value>The path which has wildcard characters, for example, an asterisk (<see cref="Path.WildcardStarMatchAll"/>) or a question mark (<see cref="Path.WildcardQuestion"/>).</value>
      [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
      public string SearchPattern
      {
         get { return _searchPattern; }

         internal set
         {
            if (null == value)
               throw new ArgumentNullException("SearchPattern");

            _searchPattern = value;

            _nameFilter = _searchPattern == Path.WildcardStarMatchAll || WildcardMatchAll.IsMatch(_searchPattern)
               ? null
               : new Regex(string.Format(CultureInfo.InvariantCulture, "^{0}$", Regex.Escape(_searchPattern).Replace(@"\*", ".*").Replace(@"\?", ".")), RegexOptions.IgnoreCase | RegexOptions.Compiled);
         }
      }


      /// <summary><c>true</c> skips ReparsePoints, <c>false</c> will follow ReparsePoints.</summary>
      public bool SkipReparsePoints { get; private set; }


      /// <summary>Get or sets the KernelTransaction instance.</summary>
      /// <value>The transaction.</value>
      public KernelTransaction Transaction { get; private set; }


      /// <summary>Gets or sets the custom enumeration in/exclusion filter.</summary>
      /// <value>The method determining if the object should be in/excluded from the output or not.</value>
      public Predicate<FileSystemEntryInfo> InclusionFilter { get; private set; }


      /// <summary>Gets or sets the custom enumeration recursion filter.</summary>
      /// <value>The method determining if the directory should be recursively traversed or not.</value>
      public Predicate<FileSystemEntryInfo> RecursionFilter { get; private set; }


      /// <summary>Gets or sets the handler of errors that may occur.</summary>
      /// <value>The error handler method.</value>
      public ErrorHandler ErrorHandler { get; private set; }


#if !NET35
      /// <summary>Gets or sets the cancellation token to abort the enumeration.</summary>
      /// <value>A <see cref="CancellationToken"/> instance.</value>
      private CancellationToken CancellationToken { get; set; }
#endif

      #endregion // Properties


      #region Methods

      private SafeFindFileHandle FindFirstFile(string pathLp, out NativeMethods.WIN32_FIND_DATA win32FindData, out int lastError, bool suppressException = false)
      {
         lastError = (int) Win32Errors.NO_ERROR;

         var searchOption = null != FileSystemObjectType && (bool) FileSystemObjectType ? NativeMethods.FINDEX_SEARCH_OPS.SearchLimitToDirectories : NativeMethods.FINDEX_SEARCH_OPS.SearchNameMatch;

         var handle = FileSystemInfo.FindFirstFileNative(Transaction, pathLp, FindExInfoLevel, searchOption, LargeCache, out lastError, out win32FindData);


         if (!suppressException && !ContinueOnException)
         {
            if (null == handle)
            {
               switch ((uint) lastError)
               {
                  case Win32Errors.ERROR_FILE_NOT_FOUND: // FileNotFoundException.
                  case Win32Errors.ERROR_PATH_NOT_FOUND: // DirectoryNotFoundException.
                  case Win32Errors.ERROR_NOT_READY:      // DeviceNotReadyException: Floppy device or network drive not ready.

                     Directory.ExistsDriveOrFolderOrFile(Transaction, pathLp, IsDirectory, lastError, true, true);
                     break;
               }


               ThrowPossibleException((uint) lastError, pathLp);
            }
         }


         return handle;
      }


      private FileSystemEntryInfo NewFilesystemEntry(string pathLp, string fileName, NativeMethods.WIN32_FIND_DATA win32FindData)
      {
         var fullPath = (IsRelativePath ? pathLp.Replace(RelativeAbsolutePrefix, string.Empty) : pathLp) + fileName;

         return new FileSystemEntryInfo(win32FindData) {FullPath = fullPath};
      }


      private T NewFileSystemEntryType<T>(bool isFolder, FileSystemEntryInfo fsei, string fileName, string pathLp, NativeMethods.WIN32_FIND_DATA win32FindData)
      {
         // Determine yield, e.g. don't return files when only folders are requested and vice versa.

         if (null != FileSystemObjectType && (!(bool) FileSystemObjectType || !isFolder) && (!(bool) !FileSystemObjectType || isFolder))

            return (T) (object) null;


         // Determine yield from name filtering.

         if (null != fileName && !(null == _nameFilter || null != _nameFilter && _nameFilter.IsMatch(fileName)))

            return (T) (object) null;


         if (null == fsei)
            fsei = NewFilesystemEntry(pathLp, fileName, win32FindData);


         // Return object instance FullPath property as string, optionally in long path format.

         return AsString ? null == InclusionFilter || InclusionFilter(fsei) ? (T) (object) (AsLongPath ? fsei.LongFullPath : fsei.FullPath) : (T) (object) null


            // Make sure the requested file system object type is returned.
            // null = Return files and directories.
            // true = Return only directories.
            // false = Return only files.

            : null != InclusionFilter && !InclusionFilter(fsei)
               ? (T) (object) null

               // Return object instance of type FileSystemInfo.

               : AsFileSystemInfo
                  ? (T) (object) (fsei.IsDirectory

                     ? (FileSystemInfo) new DirectoryInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath) {EntryInfo = fsei}

                     : new FileInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath) {EntryInfo = fsei})

                  // Return object instance of type FileSystemEntryInfo.

                  : (T) (object) fsei;
      }


      private void ThrowPossibleException(uint lastError, string pathLp)
      {
         switch (lastError)
         {
            case Win32Errors.ERROR_NO_MORE_FILES:
               lastError = Win32Errors.NO_ERROR;
               break;


            case Win32Errors.ERROR_FILE_NOT_FOUND: // On files.
            case Win32Errors.ERROR_PATH_NOT_FOUND: // On folders.
            case Win32Errors.ERROR_NOT_READY:      // DeviceNotReadyException: Floppy device or network drive not ready.
               // MSDN: .NET 3.5+: DirectoryNotFoundException: Path is invalid, such as referring to an unmapped drive.
               // Directory.Delete()

               lastError = IsDirectory ? (int) Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_FILE_NOT_FOUND;
               break;


            //case Win32Errors.ERROR_DIRECTORY:
            //   // MSDN: .NET 3.5+: IOException: path is a file name.
            //   // Directory.EnumerateDirectories()
            //   // Directory.EnumerateFiles()
            //   // Directory.EnumerateFileSystemEntries()
            //   // Directory.GetDirectories()
            //   // Directory.GetFiles()
            //   // Directory.GetFileSystemEntries()
            //   break;

            //case Win32Errors.ERROR_ACCESS_DENIED:
            //   // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission.
            //   break;
         }


         if (lastError != Win32Errors.NO_ERROR)
         {
            var regularPath = Path.GetCleanExceptionPath(pathLp);

            // Pass control to the ErrorHandler when set.

            if (null == ErrorHandler || !ErrorHandler((int) lastError, new Win32Exception((int) lastError).Message, regularPath))
            {
               // When the ErrorHandler returns false, thrown the Exception.

               NativeError.ThrowException(lastError, regularPath);
            }
         }
      }


      private void VerifyInstanceType(NativeMethods.WIN32_FIND_DATA win32FindData)
      {
         var regularPath = Path.GetCleanExceptionPath(InputPath);

         var isFolder = File.IsDirectory(win32FindData.dwFileAttributes);

         if (IsDirectory)
         {
            if (!isFolder)
               throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_PATH_NOT_FOUND, string.Format(CultureInfo.InvariantCulture, Resources.Target_Directory_Is_A_File, regularPath)));
         }

         else if (isFolder)
            throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_FILE_NOT_FOUND, string.Format(CultureInfo.InvariantCulture, Resources.Target_File_Is_A_Directory, regularPath)));
      }


      /// <summary>Gets an enumerator that returns all of the file system objects that match both the wildcards that are in any of the directories to be searched and the custom predicate.</summary>
      /// <returns>An <see cref="IEnumerable{T}"/> instance: FileSystemEntryInfo, DirectoryInfo, FileInfo or string (full path).</returns>
      [SecurityCritical]
      public IEnumerable<T> Enumerate<T>()
      {
         // MSDN: Queue
         // Represents a first-in, first-out collection of objects.
         // The capacity of a Queue is the number of elements the Queue can hold.
         // As elements are added to a Queue, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize.
         // The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The growth factor is determined when the Queue is constructed.
         // The capacity of the Queue will always increase by a minimum value, regardless of the growth factor; a growth factor of 1.0 will not prevent the Queue from increasing in size.
         // If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Queue.
         // This constructor is an O(n) operation, where n is capacity.

         var dirs = new Queue<string>(NativeMethods.DefaultFileBufferSize);

         dirs.Enqueue(Path.AddTrailingDirectorySeparator(InputPath, false));


         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))

            while (dirs.Count > 0
#if !NET35
               && !CancellationToken.IsCancellationRequested
#endif
            )
            {
               int lastError;

               NativeMethods.WIN32_FIND_DATA win32FindData;


               // Removes the object at the beginning of your Queue.
               // The algorithmic complexity of this is O(1). It doesn't loop over elements.

               var pathLp = dirs.Dequeue();
               

               using (var handle = FindFirstFile(pathLp + Path.WildcardStarMatchAll, out win32FindData, out lastError))
               {
                  // When the handle is null and we are still here, it means the ErrorHandler is active.
                  // We hit an inaccessible folder, so break and continue with the next one.
                  if (null == handle)
                     continue;

                  do
                  {
                     if (lastError == (int) Win32Errors.ERROR_NO_MORE_FILES)
                     {
                        lastError = (int) Win32Errors.NO_ERROR;
                        continue;
                     }


                     // Skip reparse points here to cleanly separate regular directories from links.
                     if (SkipReparsePoints && (win32FindData.dwFileAttributes & FileAttributes.ReparsePoint) != 0)
                        continue;


                     var fileName = win32FindData.cFileName;

                     var isFolder = (win32FindData.dwFileAttributes & FileAttributes.Directory) != 0;

                     // Skip entries ".." and "."
                     if (isFolder && (fileName.Equals(Path.ParentDirectoryPrefix, StringComparison.Ordinal) || fileName.Equals(Path.CurrentDirectoryPrefix, StringComparison.Ordinal)))
                        continue;


                     var fsei = NewFilesystemEntry(pathLp, fileName, win32FindData);

                     var res = NewFileSystemEntryType<T>(isFolder, fsei, fileName, pathLp, win32FindData);


                     // If recursion is requested, add it to the queue for later traversal.
                     if (isFolder && Recursive && (null == RecursionFilter || RecursionFilter(fsei)))

                        dirs.Enqueue(Path.AddTrailingDirectorySeparator(pathLp + fileName, false));


                     // Codacy: When constraints have not been applied to restrict a generic type parameter to be a reference type, then a value type,
                     // such as a struct, could also be passed. In such cases, comparing the type parameter to null would always be false,
                     // because a struct can be empty, but never null. If a value type is truly what's expected, then the comparison should use default().
                     // If it's not, then constraints should be added so that no value type can be passed.

                     if (Equals(res, default(T)))
                        continue;


                     yield return res;

                  } while (
#if !NET35
                     !CancellationToken.IsCancellationRequested &&
#endif
                     NativeMethods.FindNextFile(handle, out win32FindData));


                  lastError = Marshal.GetLastWin32Error();

                  if (!ContinueOnException
#if !NET35
                      && !CancellationToken.IsCancellationRequested
#endif
                  )
                     ThrowPossibleException((uint) lastError, pathLp);
               }
            }
      }


      /// <summary>Gets a specific file system object.</summary>
      /// <returns>
      /// <para>The return type is based on C# inference. Possible return types are:</para>
      /// <para> <see cref="string"/>- (full path), <see cref="FileSystemInfo"/>- (<see cref="DirectoryInfo"/> or <see cref="FileInfo"/>), <see cref="FileSystemEntryInfo"/> instance</para>
      /// <para>or null in case an Exception is raised and <see cref="ContinueOnException"/> is <c>true</c>.</para>
      /// </returns>
      [SecurityCritical]
      public T Get<T>()
      {
         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
         {
            NativeMethods.WIN32_FIND_DATA win32FindData;
            var lastError = 0;

            // Not explicitly set to be a folder.

            if (!IsDirectory)
            {
               using (var handle = FindFirstFile(InputPath, out win32FindData, out lastError))
               {
                  if (null != handle)
                  {
                     if (!ContinueOnException)
                        VerifyInstanceType(win32FindData);
                  }

                  else
                     return (T) (object) null;


                  return NewFileSystemEntryType<T>((win32FindData.dwFileAttributes & FileAttributes.Directory) != 0, null, null, InputPath, win32FindData);
               }
            }


            using (var handle = FindFirstFile(InputPath, out win32FindData, out lastError, true))
            {
               if (null == handle)
               {
                  // InputPath might be a logical drive such as: "C:\", "D:\".

                  var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();

                  lastError = File.FillAttributeInfoCore(Transaction, Path.GetRegularPathCore(InputPath, GetFullPathOptions.None, false), ref attrs, false, true);

                  if (lastError != Win32Errors.NO_ERROR)
                  {
                     if (!ContinueOnException)
                     {
                        switch ((uint) lastError)
                        {
                           case Win32Errors.ERROR_FILE_NOT_FOUND: // FileNotFoundException.
                           case Win32Errors.ERROR_PATH_NOT_FOUND: // DirectoryNotFoundException.
                           case Win32Errors.ERROR_NOT_READY:      // DeviceNotReadyException: Floppy device or network drive not ready.
                           case Win32Errors.ERROR_BAD_NET_NAME:

                              Directory.ExistsDriveOrFolderOrFile(Transaction, InputPath, IsDirectory, lastError, true, true);
                              break;
                        }

                        ThrowPossibleException((uint) lastError, InputPath);
                     }

                     return (T) (object) null;
                  }


                  win32FindData = new NativeMethods.WIN32_FIND_DATA
                  {
                     cFileName = Path.CurrentDirectoryPrefix,
                     dwFileAttributes = attrs.dwFileAttributes,
                     ftCreationTime = attrs.ftCreationTime,
                     ftLastAccessTime = attrs.ftLastAccessTime,
                     ftLastWriteTime = attrs.ftLastWriteTime,
                     nFileSizeHigh = attrs.nFileSizeHigh,
                     nFileSizeLow = attrs.nFileSizeLow
                  };
               }


               if (!ContinueOnException)
                  VerifyInstanceType(win32FindData);
            }


            return NewFileSystemEntryType<T>((win32FindData.dwFileAttributes & FileAttributes.Directory) != 0, null, null, InputPath, win32FindData);
         }
      }

      #endregion // Methods
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.GetSizeCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Collections.ObjectModel;
using System.Linq;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Retrieves the size of all alternate data streams of the specified directory and it files.</summary>
      /// <returns>The size of all alternate data streams of the specified directory and its files.</returns>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The path to the directory.</param>
      /// <param name="sizeOfAllStreams"><c>true</c> to retrieve the size of all alternate data streams, <c>false</c> to get the size of the first stream.</param>
      /// <param name="recursive"><c>true</c> to include subdirectories.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static long GetSizeCore(KernelTransaction transaction, string path, bool sizeOfAllStreams, bool recursive, PathFormat pathFormat)
      {
         var streamSizes = new Collection<long>();

         var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);


         var enumOptions = (recursive ? DirectoryEnumerationOptions.Recursive : DirectoryEnumerationOptions.None) | DirectoryEnumerationOptions.SkipReparsePoints;

         if (sizeOfAllStreams)
         {
            enumOptions |= DirectoryEnumerationOptions.FilesAndFolders;

            streamSizes.Add(File.FindAllStreamsCore(transaction, pathLp));
         }

         else
            enumOptions |= DirectoryEnumerationOptions.Files;


         foreach (var fsei in EnumerateFileSystemEntryInfosCore<FileSystemEntryInfo>(null, transaction, pathLp, Path.WildcardStarMatchAll, null, enumOptions, null, PathFormat.LongFullPath))
         {
            // Although tempting, AlphaFS does not use the fsei.FileSize property.
            //
            // https://blogs.msdn.microsoft.com/oldnewthing/20111226-00/?p=8813/
            // "The directory-enumeration functions report the last-updated metadata, which may not correspond to the actual metadata if the directory entry is stale. 


            streamSizes.Add(sizeOfAllStreams ? File.FindAllStreamsCore(transaction, fsei.LongFullPath) : File.GetSizeCore(null, transaction, fsei.LongFullPath, false, PathFormat.LongFullPath));
         }


         return streamSizes.Sum();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo Junctions, Links/DirectoryInfo.CreateJunction.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public sealed partial class DirectoryInfo
   {
      /// <summary>[AlphaFS] Converts the <see cref="DirectoryInfo"/> instance into a directory junction instance (similar to CMD command: "MKLINK /J").</summary>
      /// <remarks>
      /// <para>&#160;</para>
      /// <para>The directory must be empty and reside on a local volume.</para>
      /// <para></para>
      /// <para></para>
      /// <para>&#160;</para>
      /// <para>MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,</para>
      /// <para>and a junction can link directories located on different local volumes on the same computer.</para>
      /// <para>Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotAReparsePointException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      [SecurityCritical]
      public void CreateJunction(string junctionPath)
      {
         UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, false, false, PathFormat.RelativePath));

         RefreshEntryInfo();
      }


      /// <summary>[AlphaFS] Converts the <see cref="DirectoryInfo"/> instance into a directory junction instance (similar to CMD command: "MKLINK /J").</summary>
      /// <remarks>
      /// <para>&#160;</para>
      /// <para>The directory must be empty and reside on a local volume.</para>
      /// <para></para>
      /// <para></para>
      /// <para>&#160;</para>
      /// <para>MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,</para>
      /// <para>and a junction can link directories located on different local volumes on the same computer.</para>
      /// <para>Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotAReparsePointException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public void CreateJunction(string junctionPath, PathFormat pathFormat)
      {
         UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, false, false, pathFormat));

         RefreshEntryInfo();
      }


      /// <summary>[AlphaFS] Converts the <see cref="DirectoryInfo"/> instance into a directory junction instance (similar to CMD command: "MKLINK /J").</summary>
      /// <remarks>
      /// <para>&#160;</para>
      /// <para>The directory must be empty and reside on a local volume.</para>
      /// <para></para>
      /// <para></para>
      /// <para>&#160;</para>
      /// <para>MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,</para>
      /// <para>and a junction can link directories located on different local volumes on the same computer.</para>
      /// <para>Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotAReparsePointException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      [SecurityCritical]
      public void CreateJunction(string junctionPath, bool overwrite)
      {
         UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, overwrite, false, PathFormat.RelativePath));

         RefreshEntryInfo();
      }


      /// <summary>[AlphaFS] Converts the <see cref="DirectoryInfo"/> instance into a directory junction instance (similar to CMD command: "MKLINK /J").</summary>
      /// <remarks>
      /// <para>&#160;</para>
      /// <para>The directory must be empty and reside on a local volume.</para>
      /// <para></para>
      /// <para></para>
      /// <para>&#160;</para>
      /// <para>MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,</para>
      /// <para>and a junction can link directories located on different local volumes on the same computer.</para>
      /// <para>Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotAReparsePointException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public void CreateJunction(string junctionPath, bool overwrite, PathFormat pathFormat)
      {
         UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, overwrite, false, pathFormat));

         RefreshEntryInfo();
      }


      /// <summary>[AlphaFS] Converts the <see cref="DirectoryInfo"/> instance into a directory junction instance (similar to CMD command: "MKLINK /J").</summary>
      /// <remarks>
      /// <para>&#160;</para>
      /// <para>The directory must be empty and reside on a local volume.</para>
      /// <para></para>
      /// <para></para>
      /// <para>&#160;</para>
      /// <para>MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,</para>
      /// <para>and a junction can link directories located on different local volumes on the same computer.</para>
      /// <para>Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotAReparsePointException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      /// <param name="copyTargetTimestamps"><c>true</c> to copy the target date and time stamps to the directory junction.</param>
      [SecurityCritical]
      public void CreateJunction(string junctionPath, bool overwrite, bool copyTargetTimestamps)
      {
         UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, overwrite, copyTargetTimestamps, PathFormat.RelativePath));

         RefreshEntryInfo();
      }


      /// <summary>[AlphaFS] Converts the <see cref="DirectoryInfo"/> instance into a directory junction instance (similar to CMD command: "MKLINK /J").</summary>
      /// <remarks>
      /// <para>&#160;</para>
      /// <para>The directory must be empty and reside on a local volume.</para>
      /// <para></para>
      /// <para></para>
      /// <para>&#160;</para>
      /// <para>MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,</para>
      /// <para>and a junction can link directories located on different local volumes on the same computer.</para>
      /// <para>Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotAReparsePointException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      /// <param name="copyTargetTimestamps"><c>true</c> to copy the target date and time stamps to the directory junction.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public void CreateJunction(string junctionPath, bool overwrite, bool copyTargetTimestamps, PathFormat pathFormat)
      {
         UpdateSourcePath(junctionPath, Directory.CreateJunctionCore(Transaction, junctionPath, LongFullName, overwrite, copyTargetTimestamps, pathFormat));

         RefreshEntryInfo();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.EnumerateFileIdBothDirectoryInfoCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Returns an enumerable collection of information about files in the directory handle specified.</summary>
      /// <returns>An IEnumerable of <see cref="FileIdBothDirectoryInfo"/> records for each file system entry in the specified diretory.</returns>    
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <remarks>
      ///   <para>Either use <paramref name="path"/> or <paramref name="safeFileHandle"/>, not both.</para>
      ///   <para>
      ///   The number of files that are returned for each call to GetFileInformationByHandleEx depends on the size of the buffer that is passed to the function.
      ///   Any subsequent calls to GetFileInformationByHandleEx on the same handle will resume the enumeration operation after the last file is returned.
      /// </para>
      /// </remarks>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="safeFileHandle">An open handle to the directory from which to retrieve information.</param>
      /// <param name="path">A path to the directory.</param>
      /// <param name="shareMode">The <see cref="FileShare"/> mode with which to open a handle to the directory.</param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as ACLs protected directories or non-accessible reparse points.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static IEnumerable<FileIdBothDirectoryInfo> EnumerateFileIdBothDirectoryInfoCore(KernelTransaction transaction, SafeFileHandle safeFileHandle, string path, FileShare shareMode, bool continueOnException, PathFormat pathFormat)
      {
         if (!NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message);


         var pathLp = path;

         var callerHandle = null != safeFileHandle;
         if (!callerHandle)
         {
            if (Utils.IsNullOrWhiteSpace(path))
               throw new ArgumentNullException("path");

            pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

            safeFileHandle = File.CreateFileCore(transaction, true, pathLp, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.ReadData, shareMode, true, false, PathFormat.LongFullPath);
         }


         try
         {
            if (!NativeMethods.IsValidHandle(safeFileHandle, Marshal.GetLastWin32Error(), !continueOnException))
               yield break;

            var fileNameOffset = (int) Marshal.OffsetOf(typeof(NativeMethods.FILE_ID_BOTH_DIR_INFO), "FileName");

            using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize))
            {
               while (true)
               {
                  var success = NativeMethods.GetFileInformationByHandleEx(safeFileHandle, NativeMethods.FILE_INFO_BY_HANDLE_CLASS.FILE_ID_BOTH_DIR_INFO, safeBuffer, (uint) safeBuffer.Capacity);

                  var lastError = Marshal.GetLastWin32Error();
                  if (!success)
                  {
                     switch ((uint) lastError)
                     {
                        case Win32Errors.ERROR_SUCCESS:
                        case Win32Errors.ERROR_NO_MORE_FILES:
                        case Win32Errors.ERROR_HANDLE_EOF:
                           yield break;

                        case Win32Errors.ERROR_MORE_DATA:
                           continue;

                        default:
                           NativeError.ThrowException(lastError, pathLp);

                           // Keep the compiler happy as we never get here.
                           yield break;
                     }
                  }
                  

                  var offset = 0;
                  NativeMethods.FILE_ID_BOTH_DIR_INFO fibdi;

                  do
                  {
                     fibdi = safeBuffer.PtrToStructure<NativeMethods.FILE_ID_BOTH_DIR_INFO>(offset);

                     var fileName = safeBuffer.PtrToStringUni(offset + fileNameOffset, (int) (fibdi.FileNameLength / UnicodeEncoding.CharSize));

                     offset += fibdi.NextEntryOffset;


                     if (File.IsDirectory(fibdi.FileAttributes) &&
                         (fileName.Equals(Path.CurrentDirectoryPrefix, StringComparison.Ordinal) ||
                          fileName.Equals(Path.ParentDirectoryPrefix, StringComparison.Ordinal)))
                        continue;


                     yield return new FileIdBothDirectoryInfo(fibdi, fileName);

                  } while (fibdi.NextEntryOffset != 0);
               }                           
            }
         }
         finally
         {
            // Handle is ours, dispose.
            if (!callerHandle && null != safeFileHandle && !safeFileHandle.IsClosed)
               safeFileHandle.Close();
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Security;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      internal static uint GetHighOrderDword(long highPart)
      {
         return (uint) ((highPart >> 32) & 0xFFFFFFFF);
      }


      internal static uint GetLowOrderDword(long lowPart)
      {
         return (uint) (lowPart & 0xFFFFFFFF);
      }


      internal static long LuidToLong(LUID luid)
      {
         var high = (ulong) luid.HighPart << 32;
         var low = (ulong) luid.LowPart & 0x00000000FFFFFFFF;

         return unchecked((long) (high | low));
      }


      internal static LUID LongToLuid(long lluid)
      {
         return new LUID {HighPart = (uint) (lluid >> 32), LowPart = (uint) (lluid & 0xFFFFFFFF)};
      }


      internal static long ToLong(uint highPart, uint lowPart)
      {
         return ((long) highPart << 32) | ((long) lowPart & 0xFFFFFFFF);
      }


      /// <summary>Check is the current handle is not null, not closed and not invalid.</summary>
      /// <param name="handle">The current handle to check.</param>
      /// <param name="throwException"><c>true</c> will throw an <exception cref="Resources.Handle_Is_Invalid"/>, <c>false</c> will not raise this exception..</param>
      /// <returns><c>true</c> on success, <c>false</c> otherwise.</returns>
      /// <exception cref="ArgumentException"/>
      internal static bool IsValidHandle(SafeHandle handle, bool throwException = true)
      {
         if (null == handle || handle.IsClosed || handle.IsInvalid)
         {
            CloseSafeHandle(handle);

            if (throwException)
               throw new ArgumentException(Resources.Handle_Is_Invalid, "handle");

            return false;
         }

         return true;
      }


      /// <summary>Check is the current handle is not null, not closed and not invalid.</summary>
      /// <param name="handle">The current handle to check.</param>
      /// <param name="lastError">The result of Marshal.GetLastWin32Error()</param>
      /// <param name="throwException"><c>true</c> will throw an <exception cref="Resources.Handle_Is_Invalid_Win32Error"/>, <c>false</c> will not raise this exception..</param>
      /// <returns><c>true</c> on success, <c>false</c> otherwise.</returns>
      /// <exception cref="ArgumentException"/>
      internal static bool IsValidHandle(SafeHandle handle, int lastError, bool throwException = true)
      {
         if (null == handle || handle.IsClosed || handle.IsInvalid)
         {
            CloseSafeHandle(handle);

            if (throwException)
               throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Handle_Is_Invalid_Win32Error, lastError), "handle");

            return false;
         }

         return true;
      }


      /// <summary>Check is the current handle is not null, not closed and not invalid.</summary>
      /// <param name="handle">The current handle to check.</param>
      /// <param name="lastError">The result of Marshal.GetLastWin32Error()</param>
      /// <param name="path">The path on which the Exception occurred.</param>
      /// <param name="throwException"><c>true</c> will throw an <exception cref="Resources.Handle_Is_Invalid_Win32Error"/>, <c>false</c> will not raise this exception..</param>
      /// <returns><c>true</c> on success, <c>false</c> otherwise.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="Exception"/>
      internal static bool IsValidHandle(SafeHandle handle, int lastError, string path, bool throwException = true)
      {
         if (null == handle || handle.IsClosed || handle.IsInvalid)
         {
            CloseSafeHandle(handle);

            if (throwException)
               NativeError.ThrowException(lastError, path);

            return false;
         }

         return true;
      }


      /// <summary>Check is the current handle is not null, not closed and not invalid.</summary>
      /// <param name="handle">The current handle to check.</param>
      /// <param name="lastError">The result of Marshal.GetLastWin32Error()</param>
      /// <param name="isFolder">When <c>true</c> indicates the source is a directory, <c>false</c> indicates a file and <c>null</c> specifies a physical device.</param>
      /// <param name="path">The path on which the Exception occurred.</param>
      /// <param name="throwException"><c>true</c> will throw an <exception cref="Resources.Handle_Is_Invalid_Win32Error"/>, <c>false</c> will not raise this exception..</param>
      /// <returns><c>true</c> on success, <c>false</c> otherwise.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="Exception"/>
      internal static bool CloseHandleAndPossiblyThrowException(SafeHandle handle, int lastError, bool? isFolder, string path, bool throwException = true)
      {
         if (null == handle || handle.IsClosed || handle.IsInvalid)
         {
            CloseSafeHandle(handle);

            if (throwException)
               NativeError.ThrowException(lastError, isFolder, path);

            return false;
         }

         return true;
      }


      internal static void CloseSafeHandle(SafeHandle handle)
      {
         if (null != handle && !handle.IsClosed)
            handle.Close();

         handle = null;
      }


      /// <summary>Controls whether the system will handle the specified types of serious errors or whether the process will handle them.</summary>
      /// <remarks>
      ///   Because the error mode is set for the entire process, you must ensure that multi-threaded applications do not set different error-
      ///   mode attributes. Doing so can lead to inconsistent error handling.
      /// </remarks>
      /// <remarks>Minimum supported client: Windows XP [desktop apps only].</remarks>
      /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only].</remarks>
      /// <param name="uMode">The mode.</param>
      /// <returns>The return value is the previous state of the error-mode bit attributes.</returns>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      private static extern ErrorMode SetErrorMode(ErrorMode uMode);


      /// <summary>Controls whether the system will handle the specified types of serious errors or whether the calling thread will handle them.</summary>
      /// <remarks>
      ///   Because the error mode is set for the entire process, you must ensure that multi-threaded applications do not set different error-
      ///   mode attributes. Doing so can lead to inconsistent error handling.
      /// </remarks>
      /// <remarks>Minimum supported client: Windows 7 [desktop apps only].</remarks>
      /// <remarks>Minimum supported server: Windows Server 2008 R2 [desktop apps only].</remarks>
      /// <param name="dwNewMode">The new mode.</param>
      /// <param name="lpOldMode">[out] The old mode.</param>
      /// <returns>The return value is the previous state of the error-mode bit attributes.</returns>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.Bool)]
      private static extern bool SetThreadErrorMode(ErrorMode dwNewMode, [MarshalAs(UnmanagedType.U4)] out ErrorMode lpOldMode);
   }
}


<|start_filename|>src/AlphaFS/Network/Enumerations/Connect.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>Used by function WNetUseConnection(); Set of bit flags describing the connection. This parameter can be any combination of the following values.</summary>
      [Flags]
      internal enum Connect
      {
         /// <summary>No Connect options are used.</summary>
         None = 0,

         /// <summary>This flag instructs the operating system to store the network resource connection. If this bit flag is set, the operating system automatically attempts to restore the connection when the user logs on. The system remembers only successful connections that redirect local devices. It does not remember connections that are unsuccessful or deviceless connections.</summary>
         UpdateProfile = 1,

         /// <summary>If this flag is set, the operating system may interact with the user for authentication purposes.</summary>
         Interactive = 8,

         /// <summary>This flag instructs the system not to use any default settings for user names or passwords without offering the user the opportunity to supply an alternative. This flag is ignored unless <see cref="Interactive"/> is also set.</summary>
         Prompt = 16,

         /// <summary>This flag forces the redirection of a local device when making the connection.</summary>
         Redirect = 128,

         ///// <summary>If this flag is set, the connection was made using a local device redirection. If the lpAccessName parameter points to a buffer, the local device name is copied to the buffer.</summary>
         //LocalDrive = 256,

         // <summary>If this flag is set, the operating system prompts the user for authentication using the command line instead of a graphical user interface (GUI). This flag is ignored unless <see cref="Interactive"/> is also set.</summary>
         //CommandLine = 2048,

         /// <summary>If this flag is set, and the operating system prompts for a credential, the credential should be saved by the credential manager. If the credential manager is disabled for the caller's logon session, or if the network provider does not support saving credentials, this flag is ignored. This flag is also ignored unless you set the "CommandLine" flag.</summary>
         SaveCredentialManager = 4096
      }
   }
}

<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.CreateFileCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Security;
using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Creates or opens a file, directory or I/O device.</summary>
      /// <returns>A <see cref="SafeFileHandle"/> that provides read/write access to the file or directory specified by <paramref name="path"/>.</returns>
      /// <remarks>
      ///   <para>To obtain a directory handle using CreateFile, specify the FILE_FLAG_BACKUP_SEMANTICS flag as part of dwFlagsAndAttributes.</para>
      ///   <para>The most commonly used I/O devices are as follows: file, file stream, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="Exception"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="isFolder">When <c>true</c> indicates the source is a directory, <c>false</c> indicates a file and <c>null</c> specifies a physical device.</param>
      /// <param name="path">The path and name of the file or directory to create.</param>
      /// <param name="attributes">One of the <see cref="ExtendedFileAttributes"/> values that describes how to create or overwrite the file or directory.</param>
      /// <param name="fileSecurity">A <see cref="FileSecurity"/> instance that determines the access control and audit security for the file or directory.</param>
      /// <param name="fileMode">A <see cref="FileMode"/> constant that determines how to open or create the file or directory.</param>
      /// <param name="fileSystemRights">A <see cref="FileSystemRights"/> constant that determines the access rights to use when creating access and audit rules for the file or directory.</param>
      /// <param name="fileShare">A <see cref="FileShare"/> constant that determines how the file or directory will be shared by processes.</param>
      /// <param name="checkPath"></param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as ACLs protected directories or non-accessible reparse points.</param>
      /// <param name="pathFormat">Indicates the format of the <paramref name="path"/> parameter.</param>
      [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")]
      [SecurityCritical]
      internal static SafeFileHandle CreateFileCore(KernelTransaction transaction, bool? isFolder, string path, ExtendedFileAttributes attributes, FileSecurity fileSecurity, FileMode fileMode, FileSystemRights fileSystemRights, FileShare fileShare, bool checkPath, bool continueOnException, PathFormat pathFormat)
      {
         if (checkPath && pathFormat == PathFormat.RelativePath)

            Path.CheckSupportedPathFormat(path, true, true);


         // When isFile == null, we're working with a device.
         // When opening a VOLUME or removable media drive (for example, a floppy disk drive or flash memory thumb drive),
         // the path string should be the following form: "\\.\X:"
         // Do not use a trailing backslash ('\'), which indicates the root.

         var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);


         // CreateFileXxx() does not support FileMode.Append mode.
         var isAppend = fileMode == FileMode.Append;
         if (isAppend)
         {
            fileMode = FileMode.OpenOrCreate;
            fileSystemRights |= FileSystemRights.AppendData;
         }


         if (null != fileSecurity)
            fileSystemRights |= (FileSystemRights) SECURITY_INFORMATION.UNPROTECTED_SACL_SECURITY_INFORMATION;


         using ((fileSystemRights & (FileSystemRights)SECURITY_INFORMATION.UNPROTECTED_SACL_SECURITY_INFORMATION) != 0 || (fileSystemRights & (FileSystemRights)SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION) != 0 ? new PrivilegeEnabler(Privilege.Security) : null)

         using (var securityAttributes = new Security.NativeMethods.SecurityAttributes(fileSecurity))
         {
            var safeHandle = transaction == null || !NativeMethods.IsAtLeastWindowsVista

               // CreateFile() / CreateFileTransacted()
               // 2013-01-13: MSDN confirms LongPath usage.

               ? NativeMethods.CreateFile(pathLp, fileSystemRights, fileShare, securityAttributes, fileMode, attributes, IntPtr.Zero)

               : NativeMethods.CreateFileTransacted(pathLp, fileSystemRights, fileShare, securityAttributes, fileMode, attributes, IntPtr.Zero, transaction.SafeHandle, IntPtr.Zero, IntPtr.Zero);


            var lastError = Marshal.GetLastWin32Error();

            NativeMethods.CloseHandleAndPossiblyThrowException(safeHandle, lastError, isFolder, path, !continueOnException);


            if (isAppend)
            {
               var success = NativeMethods.SetFilePointerEx(safeHandle, 0, IntPtr.Zero, SeekOrigin.End);

               lastError = Marshal.GetLastWin32Error();

               if (!success)
               {
                  NativeMethods.CloseHandleAndPossiblyThrowException(safeHandle, lastError, isFolder, path, !continueOnException);

                  return null;
               }
            }

            return safeHandle;
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path.GetRelativePath.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>[AlphaFS] Gets the relative path from the <paramref name="startPath"/> path to the end path.</summary>
      /// <param name="startPath">The absolute or relative folder path.</param>
      /// <param name="selectedPath">The absolute or relative path containing the directory or file.</param>
      /// <returns>The relative path containing the directory or file, from the <paramref name="startPath"/> path to the end path.</returns>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="UriFormatException"/>
      /// <exception cref="InvalidOperationException"/>
      public static string GetRelativePath(string startPath, string selectedPath)
      {
         if (string.IsNullOrEmpty(startPath))
            throw new ArgumentNullException("startPath");

         if (string.IsNullOrEmpty(selectedPath))
            throw new ArgumentNullException("selectedPath");


         var fromDirectories = startPath.Split(DirectorySeparatorChar);
         var toDirectories = selectedPath.Split(DirectorySeparatorChar);

         var fromLength = fromDirectories.Length;
         var toLength = toDirectories.Length;
         var length = Math.Min(fromLength, toLength);
         var lastCommonRoot = -1;


         // Find common path root.

         for (var index = 0; index < length; index++)
         {
            if (string.Compare(fromDirectories[index], toDirectories[index], StringComparison.OrdinalIgnoreCase) != 0)
               break;

            lastCommonRoot = index;
         }


         if (lastCommonRoot == -1)
            return selectedPath;

         lastCommonRoot++;


         // Assemble relative path.

         var relativePath = new StringBuilder();

         
         // Add the "..\" suffix.

         for (var index = lastCommonRoot; index < fromLength; index++)
         {
            if (fromDirectories[index].Length > 0)
               relativePath.Append(ParentDirectoryPrefix + DirectorySeparator);
         }


         // Add folders.

         toLength--;

         for (var index = lastCommonRoot; index < toLength; index++)

            relativePath.Append(toDirectories[index] + DirectorySeparator);


         relativePath.Append(toDirectories[toLength]);

         return relativePath.ToString();
      }


      ///// <summary>[AlphaFS] Gets the relative path from the <paramref name="startPath"/> path to the end path.</summary>
      ///// <param name="startPath">The absolute or relative folder path.</param>
      ///// <param name="selectedPath">The absolute or relative path containing the directory or file.</param>
      ///// <returns>The relative path from the <paramref name="startPath"/> path to the end path.</returns>
      ///// <exception cref="ArgumentNullException"/>
      ///// <exception cref="UriFormatException"/>
      ///// <exception cref="InvalidOperationException"/>
      //public static string GetRelativePath(string startPath, string selectedPath)
      //{
      //   if (string.IsNullOrEmpty(startPath))
      //      throw new ArgumentNullException("startPath");

      //   if (string.IsNullOrEmpty(selectedPath))
      //      throw new ArgumentNullException("selectedPath");


      //   if (IsPathRooted(startPath) && IsPathRooted(selectedPath))
      //   {
      //      if (string.Compare(GetPathRoot(startPath), GetPathRoot(selectedPath), CultureInfo.InvariantCulture, CompareOptions.IgnoreCase) != 0)
      //         return selectedPath;
      //   }


      //   var fromUri = new Uri(AddTrailingDirectorySeparator(startPath, false), UriKind.RelativeOrAbsolute);
      //   var toUri = new Uri(AddTrailingDirectorySeparator(selectedPath, false), UriKind.RelativeOrAbsolute);


      //   if (fromUri.IsAbsoluteUri && toUri.IsAbsoluteUri)
      //   {
      //      if (fromUri.Scheme != toUri.Scheme)
      //         return selectedPath;
      //   }


      //   var relativeUri = toUri.IsAbsoluteUri ? fromUri.MakeRelativeUri(toUri) : toUri;
      //   var relativePath = Uri.UnescapeDataString(relativeUri.ToString());


      //   if (toUri.IsAbsoluteUri && string.Equals(toUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
      //      relativePath = relativePath.Replace(AltDirectorySeparatorChar, DirectorySeparatorChar);


      //   return relativePath.TrimEnd(DirectorySeparatorChar, AltDirectorySeparatorChar);
      //}




      /// <summary>[AlphaFS] Gets the absolute path from the relative or absolute <paramref name="startPath"/> and the relative <paramref name="selectedPath"/>.</summary>
      /// <returns>The absolute path from the relative or absolute <paramref name="startPath"/> and the relative <paramref name="selectedPath"/>.</returns>
      /// <param name="startPath">The absolute folder path.</param>
      /// <param name="selectedPath">The selected path containing the directory or file.</param>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="UriFormatException"/>
      /// <exception cref="InvalidOperationException"/>
      public static string ResolveRelativePath(string startPath, string selectedPath)
      {
         return GetFullPath(Combine(IsPathRooted(startPath) ? startPath : DirectorySeparator + startPath, IsPathRooted(selectedPath) ? selectedPath : DirectorySeparator + selectedPath), GetFullPathOptions.FullCheck);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.CreateFileStreamCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.Win32.SafeHandles;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Security;
using System.Security.AccessControl;
using FileStream = System.IO.FileStream;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Creates or overwrites a file in the specified path.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The name of the file.</param>
      /// <param name="attributes">The <see cref="ExtendedFileAttributes"/> additional advanced options to create a file.</param>
      /// <param name="fileSecurity">A <see cref="FileSecurity"/> instance that determines the access control and audit security for the file.</param>
      /// <param name="mode">The <see cref="FileMode"/> option gives you more precise control over how you want to create a file.</param>
      /// <param name="access">The <see cref="FileAccess"/> allow you additionally specify to default read/write capability - just write, bypassing any cache.</param>
      /// <param name="share">The <see cref="FileShare"/> option controls how you would like to share created file with other requesters.</param>
      ///  <param name="pathFormat">Indicates the format of the <paramref name="path"/> parameter.</param>
      /// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
      /// <returns>A <see cref="FileStream"/> that provides read/write access to the file specified in path.</returns>      
      [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive")]
      [SecurityCritical]
      internal static FileStream CreateFileStreamCore(KernelTransaction transaction, string path, ExtendedFileAttributes attributes, FileSecurity fileSecurity, FileMode mode, FileAccess access, FileShare share, int bufferSize, PathFormat pathFormat)
      {
         SafeFileHandle safeHandle = null;

         try
         {
            safeHandle = CreateFileCore(transaction, false, path, attributes, fileSecurity, mode, (FileSystemRights) access, share, true, false, pathFormat);

            return new FileStream(safeHandle, access, bufferSize, (attributes & ExtendedFileAttributes.Overlapped) != 0);
         }
         catch
         {
            NativeMethods.IsValidHandle(safeHandle, false);

            throw;
         }
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/File_Create/File.Create.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class File_CreateTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void File_Create_LocalAndNetwork_Success()
      {
         File_Create(false);
         File_Create(true);
      }


      private void File_Create(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var file = tempRoot.RandomTxtFileFullPath;

#if NET35
            // MSDN: .NET 4+ Trailing spaces are removed from the end of the path parameter before deleting the directory.
            file += "\u3000"; // EMspace
#endif

            Console.WriteLine("Input File Path: [{0}]\n", file);


            long fileLength;
            var tenNumbers = "0123456789";
            var ten = tenNumbers.Length;

            using (var fs = Alphaleonis.Win32.Filesystem.File.Create(file))
            {
               // According to NotePad++, creates a file type: "ANSI", which is reported as: "Unicode (UTF-8)".
               fs.Write(UnitTestConstants.StringToByteArray(tenNumbers), 0, ten);

               fileLength = fs.Length;
            }


            Assert.IsTrue(System.IO.File.Exists(file), "File should exist.");

            Assert.IsTrue(fileLength == ten, "The file is: {0} bytes, but is expected to be: {1} bytes.", fileLength, ten);
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Network/WorkstationStatisticsInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Network
{
   /// <summary>Contains operating statistics for the Workstation service.</summary>
   [Serializable]
   public sealed class WorkstationStatisticsInfo : IEquatable<WorkstationStatisticsInfo>
   {
      #region Fields

      [NonSerialized] private NativeMethods.STAT_WORKSTATION_0 _workstationStat;

      #endregion // Fields


      #region Constructors

      /// <summary>Create a WorkstationStatisticsInfo instance from the local host.</summary>
      public WorkstationStatisticsInfo() : this(Environment.MachineName, null)
      {
      }


      /// <summary>Create a WorkstationStatisticsInfo instance from the specified host name.</summary>
      /// <param name="hostName">The host name.</param>

      public WorkstationStatisticsInfo(string hostName) : this(hostName, null)
      {
      }


      /// <summary>Create a ServerStatisticsInfo instance from the specified host name.</summary>
      internal WorkstationStatisticsInfo(string hostName, NativeMethods.STAT_WORKSTATION_0? workstationStat)
      {
         HostName = !Utils.IsNullOrWhiteSpace(hostName) ? hostName : Environment.MachineName;

         if (workstationStat.HasValue)
            _workstationStat = (NativeMethods.STAT_WORKSTATION_0) workstationStat;

         else
            Refresh();
      }

      #endregion // Constructors


      #region Properties

      /// <summary>The total number of bytes received by the workstation.</summary>
      public long BytesReceived
      {
         get { return _workstationStat.BytesReceived; }
      }


      /// <summary>The total number of bytes received by the workstation, formatted as a unit size.</summary>
      public string BytesReceivedUnitSize
      {
         get { return Utils.UnitSizeToText(BytesReceived); }
      }


      /// <summary>The total number of bytes transmitted by the workstation.</summary>
      public long BytesTransmitted
      {
         get { return _workstationStat.BytesTransmitted; }
      }


      /// <summary>The total number of bytes transmitted by the workstation, formatted as a unit size.</summary>
      public string BytesTransmittedUnitSize
      {
         get { return Utils.UnitSizeToText(BytesTransmitted); }
      }


      /// <summary>The total number of bytes that have been read by cache I/O requests.</summary>
      public long CacheReadBytesRequested
      {
         get { return _workstationStat.CacheReadBytesRequested; }
      }


      /// <summary>The total number of bytes that have been read by cache I/O requests, formatted as a unit size.</summary>
      public string CacheReadBytesRequestedUnitSize
      {
         get { return Utils.UnitSizeToText(CacheReadBytesRequested); }
      }


      /// <summary>The total number of bytes that have been written by cache I/O requests.</summary>
      public long CacheWriteBytesRequested
      {
         get { return _workstationStat.CacheWriteBytesRequested; }
      }


      /// <summary>The total number of bytes that have been written by cache I/O requests, formatted as a unit size.</summary>
      public string CacheWriteBytesRequestedUnitSize
      {
         get { return Utils.UnitSizeToText(CacheWriteBytesRequested); }
      }


      /// <summary>The total number of connections to servers supporting the PCNET dialect that have succeeded.</summary>
      public int CoreConnects
      {
         get { return (int) _workstationStat.CoreConnects; }
      }


      /// <summary>The number of current requests that have not been completed.</summary>
      public int CurrentCommands
      {
         get { return (int) _workstationStat.CurrentCommands; }
      }


      /// <summary>The total number of network operations that failed to complete.</summary>
      public int FailedCompletionOperations
      {
         get { return (int) _workstationStat.FailedCompletionOperations; }
      }


      /// <summary>The number of times the workstation attempted to create a session but failed.</summary>
      public int FailedSessions
      {
         get { return (int) _workstationStat.FailedSessions; }
      }


      /// <summary>The total number of failed network connections for the workstation.</summary>
      public int FailedUseCount
      {
         get { return (int) _workstationStat.FailedUseCount; }
      }


      /// <summary>The host name from where the statistics are gathered.</summary>
      public string HostName { get; private set; }


      /// <summary>The total number of network operations that failed to begin.</summary>
      public int InitiallyFailedOperations
      {
         get { return (int) _workstationStat.InitiallyFailedOperations; }
      }


      /// <summary>The total number of sessions that have expired on the workstation.</summary>
      public int HungSessions
      {
         get { return (int) _workstationStat.HungSessions; }
      }


      /// <summary>The total number of connections to servers supporting the LanManager 2.0 dialect that have succeeded.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lanman")]
      public int Lanman20Connects
      {
         get { return (int) _workstationStat.Lanman20Connects; }
      }


      /// <summary>The total number of connections to servers supporting the LanManager 2.1 dialect that have succeeded.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lanman")]
      public int Lanman21Connects
      {
         get { return (int) _workstationStat.Lanman21Connects; }
      }


      /// <summary>The total number of connections to servers supporting the NTLM dialect that have succeeded.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nt")]
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lanman")]
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Nt")]
      public int LanmanNtConnects
      {
         get { return (int) _workstationStat.LanmanNtConnects; }
      }


      /// <summary>The total number of read requests the workstation has sent to servers that are greater than twice the size of the server's negotiated buffer size.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
      public int LargeReadSmbs
      {
         get { return (int) _workstationStat.LargeReadSmbs; }
      }


      /// <summary>The total number of write requests the workstation has sent to servers that are greater than twice the size of the server's negotiated buffer size.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
      public int LargeWriteSmbs
      {
         get { return (int) _workstationStat.LargeWriteSmbs; }
      }


      /// <summary>The total number of network errors received by the workstation.</summary>
      public int NetworkErrors
      {
         get { return (int) _workstationStat.NetworkErrors; }
      }


      /// <summary>The total amount of bytes that have been read by disk I/O requests.</summary>
      public long NetworkReadBytesRequested
      {
         get { return _workstationStat.NetworkReadBytesRequested; }
      }


      /// <summary>The total amount of bytes that have been read by disk I/O requests, formatted as a unit size.</summary>
      public string NetworkReadBytesRequestedUnitSize
      {
         get { return Utils.UnitSizeToText(NetworkReadBytesRequested); }
      }


      /// <summary>The total number of bytes that have been written by disk I/O requests.</summary>
      public long NetworkWriteBytesRequested
      {
         get { return _workstationStat.NetworkWriteBytesRequested; }
      }


      /// <summary>The total number of bytes that have been written by disk I/O requests, formatted as a unit size.</summary>
      public string NetworkWriteBytesRequestedUnitSize
      {
         get { return Utils.UnitSizeToText(NetworkWriteBytesRequested); }
      }


      /// <summary>The total number of bytes that have been read by non-paging I/O requests.</summary>
      public long NonPagingReadBytesRequested
      {
         get { return _workstationStat.NonPagingReadBytesRequested; }
      }


      /// <summary>The total number of bytes that have been read by non-paging I/O requests, formatted as a unit size.</summary>
      public string NonPagingReadBytesRequestedUnitSize
      {
         get { return Utils.UnitSizeToText(NonPagingReadBytesRequested); }
      }


      /// <summary>The total number of bytes that have been written by non-paging I/O requests.</summary>
      public long NonPagingWriteBytesRequested
      {
         get { return _workstationStat.NonPagingWriteBytesRequested; }
      }


      /// <summary>The total number of bytes that have been written by non-paging I/O requests, formatted as a unit size.</summary>
      public string NonPagingWriteBytesRequestedUnitSize
      {
         get { return Utils.UnitSizeToText(NonPagingWriteBytesRequested); }
      }


      /// <summary>The total number of bytes that have been read by paging I/O requests.</summary>
      public long PagingReadBytesRequested
      {
         get { return _workstationStat.PagingReadBytesRequested; }
      }


      /// <summary>The total number of bytes that have been read by paging I/O requests, formatted as a unit size.</summary>
      public string PagingReadBytesRequestedUnitSize
      {
         get { return Utils.UnitSizeToText(PagingReadBytesRequested); }
      }


      /// <summary>The total number of bytes that have been written by paging I/O requests.</summary>
      public long PagingWriteBytesRequested
      {
         get { return _workstationStat.PagingWriteBytesRequested; }
      }


      /// <summary>The total number of bytes that have been written by paging I/O requests, formatted as a unit size.</summary>
      public string PagingWriteBytesRequestedUnitSize
      {
         get { return Utils.UnitSizeToText(PagingWriteBytesRequested); }
      }


      /// <summary>The total number of random access reads initiated by the workstation.</summary>
      public int RandomReadOperations
      {
         get { return (int) _workstationStat.RandomReadOperations; }
      }


      /// <summary>The total number of random access writes initiated by the workstation.</summary>
      public int RandomWriteOperations
      {
         get { return (int) _workstationStat.RandomWriteOperations; }
      }


      /// <summary>The total number of raw read requests made by the workstation that have been denied.</summary>
      public int RawReadsDenied
      {
         get { return (int) _workstationStat.RawReadsDenied; }
      }


      /// <summary>The total number of raw write requests made by the workstation that have been denied.</summary>
      public int RawWritesDenied
      {
         get { return (int) _workstationStat.RawWritesDenied; }
      }


      /// <summary>The total number of read operations initiated by the workstation.</summary>
      public int ReadOperations
      {
         get { return (int) _workstationStat.ReadOperations; }
      }


      /// <summary>The total number of read requests the workstation has sent to servers.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
      public int ReadSmbs
      {
         get { return (int) _workstationStat.ReadSmbs; }
      }


      /// <summary>The total number of connections that have failed.</summary>
      public int Reconnects
      {
         get { return (int) _workstationStat.Reconnects; }
      }


      /// <summary>The number of times the workstation was disconnected by a network server.</summary>
      public int ServerDisconnects
      {
         get { return (int) _workstationStat.ServerDisconnects; }
      }


      /// <summary>The total number of workstation sessions that were established.</summary>
      public int Sessions
      {
         get { return (int) _workstationStat.Sessions; }
      }


      /// <summary>The total number of read requests the workstation has sent to servers that are less than 1/4 of the size of the server's negotiated buffer size.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
      public int SmallReadSmbs
      {
         get { return (int) _workstationStat.SmallReadSmbs; }
      }


      /// <summary>The total number of write requests the workstation has sent to servers that are less than 1/4 of the size of the server's negotiated buffer size.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
      public int SmallWriteSmbs
      {
         get { return (int) _workstationStat.SmallWriteSmbs; }
      }


      /// <summary>The local time statistics collection started. This member also indicates when statistics for the workstations were last cleared.</summary>
      public DateTime StatisticsStartTime
      {
         get { return StatisticsStartTimeUtc.ToLocalTime(); }
      }


      /// <summary>The time statistics collection started. This member also indicates when statistics for the workstations were last cleared.</summary>
      public DateTime StatisticsStartTimeUtc
      {
         get { return DateTime.FromFileTimeUtc(_workstationStat.StatisticsStartTime); }
      }


      /// <summary>The total number of server message blocks (SMBs) received by the workstation.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
      public long SmbsReceived
      {
         get { return _workstationStat.SmbsReceived; }
      }


      /// <summary>The total number of SMBs transmitted by the workstation.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
      public long SmbsTransmitted
      {
         get { return _workstationStat.SmbsTransmitted; }
      }
      

      /// <summary>The total number of network connections established by the workstation.</summary>
      public int UseCount
      {
         get { return (int) _workstationStat.UseCount; }
      }


      /// <summary>The total number of write operations initiated by the workstation.</summary>
      public int WriteOperations
      {
         get { return (int) _workstationStat.WriteOperations; }
      }


      /// <summary>The total number of write requests the workstation has sent to servers.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
      public int WriteSmbs
      {
         get { return (int) _workstationStat.WriteSmbs; }
      }
      
      #endregion // Properties


      #region Methods

      /// <summary>Refreshes the state of the object.</summary>
      public void Refresh()
      {
         _workstationStat = Host.GetNetStatisticsNative<NativeMethods.STAT_WORKSTATION_0>(false, HostName);
      }


      /// <summary>Returns the local time when statistics collection started or when the statistics were last cleared.</summary>
      /// <returns>A string that represents this instance.</returns>
      public override string ToString()
      {
         return HostName;
      }


      /// <summary>Serves as a hash function for a particular type.</summary>
      /// <returns>A hash code for the current Object.</returns>
      public override int GetHashCode()
      {
         return Utils.CombineHashCodesOf(HostName, BytesTransmitted, StatisticsStartTime);
      }
      

      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="other">Another <see cref="WorkstationStatisticsInfo"/> instance to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public bool Equals(WorkstationStatisticsInfo other)
      {
         return null != other && GetType() == other.GetType() &&
                Equals(HostName, other.HostName) &&
                Equals(BytesTransmitted, other.BytesTransmitted) &&
                Equals(BytesReceived, other.BytesReceived) &&
                Equals(StatisticsStartTimeUtc, other.StatisticsStartTimeUtc);
      }


      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="obj">Another object to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public override bool Equals(object obj)
      {
         var other = obj as WorkstationStatisticsInfo;

         return null != other && Equals(other);
      }


      /// <summary>Implements the operator ==</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator ==(WorkstationStatisticsInfo left, WorkstationStatisticsInfo right)
      {
         return ReferenceEquals(left, null) && ReferenceEquals(right, null) ||
                !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right);
      }


      /// <summary>Implements the operator !=</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator !=(WorkstationStatisticsInfo left, WorkstationStatisticsInfo right)
      {
         return !(left == right);
      }

      #endregion // Methods
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File.AppendAllTextTransacted.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      #region .NET

      /// <summary>[AlphaFS] Appends the specified string to the file, creating the file if it does not already exist.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to append the specified string to.</param>
      /// <param name="contents">The string to append to the file.</param>
      [SecurityCritical]
      public static void AppendAllTextTransacted(KernelTransaction transaction, string path, string contents)
      {
         WriteAppendAllLinesCore(transaction, path, new[] {contents}, NativeMethods.DefaultFileEncoding, true, false, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Appends the specified string to the file, creating the file if it does not already exist.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to append the specified string to.</param>
      /// <param name="contents">The string to append to the file.</param>
      /// <param name="encoding">The character <see cref="Encoding"/> to use.</param>
      [SecurityCritical]
      public static void AppendAllTextTransacted(KernelTransaction transaction, string path, string contents, Encoding encoding)
      {
         WriteAppendAllLinesCore(transaction, path, new[] {contents}, encoding, true, false, PathFormat.RelativePath);
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Appends the specified string to the file, creating the file if it does not already exist.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to append the specified string to.</param>
      /// <param name="contents">The string to append to the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void AppendAllTextTransacted(KernelTransaction transaction, string path, string contents, PathFormat pathFormat)
      {
         WriteAppendAllLinesCore(transaction, path, new[] {contents}, NativeMethods.DefaultFileEncoding, true, false, pathFormat);
      }


      /// <summary>[AlphaFS] Appends the specified string to the file, creating the file if it does not already exist.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentOutOfRangeException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="SecurityException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to append the specified string to.</param>
      /// <param name="contents">The string to append to the file.</param>
      /// <param name="encoding">The character <see cref="Encoding"/> to use.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static void AppendAllTextTransacted(KernelTransaction transaction, string path, string contents, Encoding encoding, PathFormat pathFormat)
      {
         WriteAppendAllLinesCore(transaction, path, new[] {contents}, encoding, true, false, pathFormat);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_AnalyzeDirectoryInfoSecurity.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;

namespace AlphaFS.UnitTest
{
   public partial class DirectoryInfoTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AnalyzeDirectoryInfoSecurity_ShouldNotExist_LocalAndNetwork()
      {
         AnalyzeDirectoryInfoSecurity_ShouldNotExist(false);
         AnalyzeDirectoryInfoSecurity_ShouldNotExist(true);
      }


      private void AnalyzeDirectoryInfoSecurity_ShouldNotExist(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.CreateDirectory();

            Console.WriteLine("Input Directory Path: [{0}]", folder.FullName);


            SetSecuritySystem(folder.FullName);

            var dirsec = new System.IO.DirectoryInfo(folder.FullName + @"\inherited").GetAccessControl();

            var accessRules = dirsec.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

            UnitTestConstants.Dump(dirsec);

            Assert.IsFalse(HasLocalAces(accessRules), "Local access rules are found, but it is not expected.");

            


            folder = tempRoot.CreateDirectory();

            Console.WriteLine("\nInput Directory Path: [{0}]", folder.FullName);

            SetSecurityAlpha(folder.FullName);

            dirsec = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder.FullName + @"\inherited").GetAccessControl();

            accessRules = dirsec.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

            UnitTestConstants.Dump(dirsec);

            Assert.IsFalse(HasLocalAces(accessRules), "Local access rules are found, but it is not expected.");
         }

         Console.WriteLine();
      }

      
      private static void SetSecurityAlpha(string directory)
      {
         if (System.IO.Directory.Exists(directory))
            System.IO.Directory.Delete(directory, true);

         Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(directory);
         Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(System.IO.Path.Combine(directory, "inherited"));


         var testDirInfo = new Alphaleonis.Win32.Filesystem.DirectoryInfo(directory);

         var ds = testDirInfo.GetAccessControl(System.Security.AccessControl.AccessControlSections.Access);

         ds.SetAccessRuleProtection(true, false);

         ds.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null), System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ContainerInherit | System.Security.AccessControl.InheritanceFlags.ObjectInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow));

         testDirInfo.SetAccessControl(ds);
      }


      private static void SetSecuritySystem(string directory)
      {
         if (System.IO.Directory.Exists(directory))
            System.IO.Directory.Delete(directory, true);

         System.IO.Directory.CreateDirectory(directory);
         System.IO.Directory.CreateDirectory(System.IO.Path.Combine(directory, "inherited"));


         var testDirInfo = new System.IO.DirectoryInfo(directory);

         var ds = testDirInfo.GetAccessControl(System.Security.AccessControl.AccessControlSections.Access);

         ds.SetAccessRuleProtection(true, false);

         ds.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null), System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ContainerInherit | System.Security.AccessControl.InheritanceFlags.ObjectInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow));

         testDirInfo.SetAccessControl(ds);
      }
      

      private static bool HasLocalAces(System.Security.AccessControl.AuthorizationRuleCollection rules)
      {
         return null != rules.Cast<System.Security.AccessControl.AccessRule>().FirstOrDefault(a => !a.IsInherited);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetRelativePathResolveRelativePath.cs<|end_filename|>
﻿/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class PathTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Path_GetRelativePathResolveRelativePath_LocalAndNetwork_Success()
      {
         AlphaFS_Path_GetRelativePathResolveRelativePath(false);
         AlphaFS_Path_GetRelativePathResolveRelativePath(true);
      }


      private void AlphaFS_Path_GetRelativePathResolveRelativePath(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var sysDrive = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.SysDrive) : UnitTestConstants.SysDrive;
            
            string[] relativePaths =
            {
               // fso = Folder or file.

               @"a\b\c",
               @"a\fso",
               @"..\..\fso",
               @"..\b\c",

               @"a\b\c",
               @"b\fso",
               @"b\fso",
               @"a\b\c",

               @"a\b\c",
               @"fso",
               @"fso",
               @"a\b\c",

               @"\a\b\",
               @"\",
               @"..\..\",
               @"a\b\",


               sysDrive + @"\a",
               sysDrive + @"\fso",
               @"..\fso",
               @"..\a",

               sysDrive + @"\a",
               sysDrive + @"\a\fso",
               @"fso",
               @"..\a",

               sysDrive + @"\a",
               sysDrive + @"\a\b\fso",
               @"b\fso",
               @"..\..\a",

               sysDrive + @"\a",
               sysDrive + @"\a\b\c\fso",
               @"b\c\fso",
               @"..\..\..\a",

               sysDrive + @"\a",
               sysDrive + @"\b\fso",
               @"..\b\fso",
               @"..\..\a",

               sysDrive + @"\a",
               sysDrive + @"\b\c\fso",
               @"..\b\c\fso",
               @"..\..\..\a",


               sysDrive + @"\a\b",
               sysDrive + @"\a\fso",
               @"..\fso",
               @"..\b",
            
               sysDrive + @"\a\b",
               sysDrive + @"\a",
               @"..\a",
               @"b",
            
               sysDrive + @"\a\b",
               sysDrive + @"\x\y\fso",
               @"..\..\x\y\fso",
               @"..\..\..\a\b",

               sysDrive + @"\a\b\",
               sysDrive + @"\",
               @"..\..\",
               @"a\b\",


               sysDrive + @"\a\b\c",
               sysDrive + @"\a\fso",
               @"..\..\fso",
               @"..\b\c",
            
               sysDrive + @"\a\b\c",
               sysDrive + @"\a\x\fso",
               @"..\..\x\fso",
               @"..\..\b\c",
            
               sysDrive + @"\a\b\c",
               sysDrive + @"\a\x\y\fso",
               @"..\..\x\y\fso",
               @"..\..\..\b\c",
            
               sysDrive + @"\a\b\c",
               sysDrive + @"\fso",
               @"..\..\..\fso",
               @"..\a\b\c",


               tempRoot.Directory.FullName + @"\",
               tempRoot.Directory.FullName + @"\",
               string.Empty,
               string.Empty,


               tempRoot.Directory.FullName,
               tempRoot.Directory.FullName,
               tempRoot.Directory.Name,
               tempRoot.Directory.Name
            };


            var totalPaths = relativePaths.Length;
         
            for (var i = 0; i < totalPaths; i += 4)
            {
               var current = relativePaths[0 + i];
               var selected = relativePaths[1 + i];
               var shouldBeCurrent = relativePaths[2 + i];
               var shouldBeSelected = relativePaths[3 + i];

               var relative = Alphaleonis.Win32.Filesystem.Path.GetRelativePath(current, selected);
               var absolute = Alphaleonis.Win32.Filesystem.Path.ResolveRelativePath(current, selected);

               Console.WriteLine("\tCurrent : [{0}]", current);
               Console.WriteLine("\tSelected: [{0}]", selected);
               Console.WriteLine("\tRelative: [{0}]", relative);


               var verify = System.IO.Path.IsPathRooted(current) && current[0] != Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar;

               if (verify)
               {
                  Console.WriteLine("\tAbsolute: [{0}]", absolute);

                  Assert.AreEqual(selected, absolute, "The absolute paths do not match, but are expected to.");
               }

               Console.WriteLine();

               Assert.AreEqual(shouldBeCurrent, relative, "The relative paths do not match, but are expected to.");


               relative = Alphaleonis.Win32.Filesystem.Path.GetRelativePath(selected, current);
               absolute = Alphaleonis.Win32.Filesystem.Path.ResolveRelativePath(selected, current);

               Console.WriteLine("\t  Current : [{0}]", selected);
               Console.WriteLine("\t  Selected: [{0}]", current);
               Console.WriteLine("\t  Relative: [{0}]", relative);


               verify = System.IO.Path.IsPathRooted(selected) && selected[0] != Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar;

               if (verify)
               {
                  Console.WriteLine("\t  Absolute: [{0}]", absolute);

                  Assert.AreEqual(current, absolute, "The absolute paths do not match, but are expected to.");
               }


               Assert.AreEqual(shouldBeSelected, relative, "The relative paths do not match, but are expected to.");


               Console.WriteLine();
            }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.SMB.EnumerateDrives.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Filesystem;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>Enumerates drives from the local host.</summary>
      /// <returns><see cref="IEnumerable{String}"/> drives from the local host.</returns>
      /// <exception cref="NetworkInformationException"/>
      [SecurityCritical]
      public static IEnumerable<DriveInfo> EnumerateDrives()
      {
         return EnumerateDrives(Environment.MachineName, false);
      }


      /// <summary>Enumerates local drives from the specified host.</summary>
      /// <returns><see cref="IEnumerable{String}"/> drives from the specified host.</returns>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="host">The DNS or NetBIOS name of the remote server. <c>null</c> refers to the local host.</param>
      [SecurityCritical]
      public static IEnumerable<DriveInfo> EnumerateDrives(string host)
      {
         return EnumerateDrivesCore(host, false)

            .Select(drive => string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", Path.UncPrefix, host,

               Path.DirectorySeparator, drive[0], Path.NetworkDriveSeparator)).Select(uncDrive => new DriveInfo(uncDrive));
      }


      /// <summary>Enumerates local drives from the specified host.</summary>
      /// <returns><see cref="IEnumerable{String}"/> drives from the specified host.</returns>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="host">The DNS or NetBIOS name of the remote server. <c>null</c> refers to the local host.</param>
      /// <param name="continueOnException">
      ///   <para><c>true</c> suppress any Exception that might be thrown as a result from a failure,</para>
      ///   <para>such as unavailable resources.</para>
      /// </param>
      [SecurityCritical]
      public static IEnumerable<DriveInfo> EnumerateDrives(string host, bool continueOnException)
      {
         return EnumerateDrivesCore(host, continueOnException)

            .Select(drive => string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", Path.UncPrefix, host,

               Path.DirectorySeparator, drive[0], Path.NetworkDriveSeparator)).Select(uncDrive => new DriveInfo(uncDrive));
      }




      /// <summary>Enumerates local drives from the specified host.</summary>
      /// <returns><see cref="IEnumerable{String}"/> drives from the specified host.</returns>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="host">The DNS or NetBIOS name of the remote server. <c>null</c> refers to the local host.</param>
      /// <param name="continueOnException">
      ///   <para><c>true</c> suppress any Exception that might be thrown as a result from a failure,</para>
      ///   <para>such as unavailable resources.</para>
      /// </param>
      [SecurityCritical]
      internal static IEnumerable<string> EnumerateDrivesCore(string host, bool continueOnException)
      {
         return EnumerateNetworkObjectCore(new FunctionData {EnumType = 1}, (string structure, SafeGlobalMemoryBufferHandle buffer) => structure,

            (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resume) =>
            {
               // When host == null, the local computer is used.
               // However, the resulting Host property will be empty.
               // So, explicitly state Environment.MachineName to prevent this.
               // Furthermore, the UNC prefix: \\ is not required and always removed.
               var stripUnc = Utils.IsNullOrWhiteSpace(host) ? Environment.MachineName : Path.GetRegularPathCore(host, GetFullPathOptions.CheckInvalidPathChars, false).Replace(Path.UncPrefix, string.Empty);

               return NativeMethods.NetServerDiskEnum(stripUnc, 0, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resume);

            }, continueOnException);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetSuffixedDirectoryName.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class PathTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Path_GetSuffixedDirectoryName_LocalAndNetwork_Success()
      {
         AlphaFS_Path_GetSuffixedDirectoryName(false);
         AlphaFS_Path_GetSuffixedDirectoryName(true);
      }


      private void AlphaFS_Path_GetSuffixedDirectoryName(bool isNetwork)
      {
         UnitTestConstants.PrintUnitTestHeader(isNetwork);

         var neDir = "Non-Existing Directory";

         var windowsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
         var system32Folder = Environment.SystemDirectory + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator;


         var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, neDir);
         if (isNetwork)
         {
            fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath);
            windowsFolder = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(windowsFolder);
            system32Folder = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(system32Folder);
         }

         var suffixedDirectoryName = Alphaleonis.Win32.Filesystem.Path.GetSuffixedDirectoryName(fullPath);

         Console.WriteLine("Full Path               : " + fullPath);
         Console.WriteLine("GetSuffixedDirectoryName: " + suffixedDirectoryName);
         
         Assert.IsTrue(suffixedDirectoryName.Equals(system32Folder, StringComparison.OrdinalIgnoreCase));




         fullPath = System.IO.Path.Combine(fullPath, "Non-Existing file.txt");
         neDir = System.IO.Path.Combine(Environment.SystemDirectory, neDir) + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator;
         if (isNetwork)
         {
            fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath);
            neDir = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(neDir);
         }

         suffixedDirectoryName = Alphaleonis.Win32.Filesystem.Path.GetSuffixedDirectoryName(fullPath);

         Console.WriteLine("\nFull Path               : " + fullPath);
         Console.WriteLine("GetSuffixedDirectoryName: " + suffixedDirectoryName);

         Assert.IsTrue(suffixedDirectoryName.Equals(neDir, StringComparison.OrdinalIgnoreCase));




         fullPath = Environment.SystemDirectory;
         if (isNetwork)
            fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath);

         suffixedDirectoryName = Alphaleonis.Win32.Filesystem.Path.GetSuffixedDirectoryName(fullPath);

         Console.WriteLine("\nFull Path               : " + fullPath);
         Console.WriteLine("GetSuffixedDirectoryName: " + suffixedDirectoryName);

         Assert.AreEqual(windowsFolder, suffixedDirectoryName.TrimEnd(Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar));




         fullPath = UnitTestConstants.SysDrive + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator;
         if (isNetwork)
            fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath);

         suffixedDirectoryName = Alphaleonis.Win32.Filesystem.Path.GetSuffixedDirectoryNameWithoutRoot(fullPath);

         Console.WriteLine("\nFull Path               : " + fullPath);
         Console.WriteLine("GetSuffixedDirectoryName: " + suffixedDirectoryName);

         Assert.AreEqual(null, suffixedDirectoryName);


         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.DefineDosDevice.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Defines, redefines, or deletes MS-DOS device names.</summary>
      /// <param name="deviceName">An MS-DOS device name string specifying the device the function is defining, redefining, or deleting.</param>
      /// <param name="targetPath">An MS-DOS path that will implement this device.</param>
      [SecurityCritical]
      public static void DefineDosDevice(string deviceName, string targetPath)
      {
         DefineDosDeviceCore(true, deviceName, targetPath, DosDeviceAttributes.None, false);
      }

      /// <summary>[AlphaFS] Defines, redefines, or deletes MS-DOS device names.</summary>
      /// <param name="deviceName">
      ///   An MS-DOS device name string specifying the device the function is defining, redefining, or deleting.
      /// </param>
      /// <param name="targetPath">
      ///   &gt;An MS-DOS path that will implement this device. If <paramref name="deviceAttributes"/> parameter has the
      ///   <see cref="DosDeviceAttributes.RawTargetPath"/> flag specified, <paramref name="targetPath"/> is used as-is.
      /// </param>
      /// <param name="deviceAttributes">
      ///   The controllable aspects of the DefineDosDevice function, <see cref="DosDeviceAttributes"/> flags which will be combined with the
      ///   default.
      /// </param>      
      [SecurityCritical]
      public static void DefineDosDevice(string deviceName, string targetPath, DosDeviceAttributes deviceAttributes)
      {
         DefineDosDeviceCore(true, deviceName, targetPath, deviceAttributes, false);
      }




      /// <summary>Defines, redefines, or deletes MS-DOS device names.</summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="isDefine">
      ///   <c>true</c> defines a new MS-DOS device. <c>false</c> deletes a previously defined MS-DOS device.
      /// </param>
      /// <param name="deviceName">
      ///   An MS-DOS device name string specifying the device the function is defining, redefining, or deleting.
      /// </param>
      /// <param name="targetPath">
      ///   A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the
      ///   <see cref="DosDeviceAttributes.RawTargetPath"/> flag is specified, in which case this string is a path string.
      /// </param>
      /// <param name="deviceAttributes">
      ///   The controllable aspects of the DefineDosDevice function, <see cref="DosDeviceAttributes"/> flags which will be combined with the
      ///   default.
      /// </param>
      /// <param name="exactMatch">
      ///   Only delete MS-DOS device on an exact name match. If <paramref name="exactMatch"/> is <c>true</c>,
      ///   <paramref name="targetPath"/> must be the same path used to create the mapping.
      /// </param>
      [SecurityCritical]
      internal static void DefineDosDeviceCore(bool isDefine, string deviceName, string targetPath, DosDeviceAttributes deviceAttributes, bool exactMatch)
      {
         if (Utils.IsNullOrWhiteSpace(deviceName))
            throw new ArgumentNullException("deviceName");

         if (isDefine)
         {
            // targetPath is allowed to be null.

            // In no case is a trailing backslash ("\") allowed.
            deviceName = Path.GetRegularPathCore(deviceName, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars, false);

            using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
            {
               var success = NativeMethods.DefineDosDevice(deviceAttributes, deviceName, targetPath);

               var lastError = Marshal.GetLastWin32Error();
               if (!success)
                  NativeError.ThrowException(lastError, deviceName, targetPath);
            }
         }

         else
         {
            // A pointer to a path string that will implement this device.
            // The string is an MS-DOS path string unless the DDD_RAW_TARGET_PATH flag is specified, in which case this string is a path string.

            if (exactMatch && !Utils.IsNullOrWhiteSpace(targetPath))
               deviceAttributes = deviceAttributes | DosDeviceAttributes.ExactMatchOnRemove | DosDeviceAttributes.RawTargetPath;

            // Remove the MS-DOS device name. First, get the name of the Windows NT device
            // from the symbolic link and then delete the symbolic link from the namespace.

            DefineDosDevice(deviceName, targetPath, deviceAttributes);
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;

#if !NET35
using System.Threading;
#endif

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>[AlphaFS] Represents the method that will handle an error raised during retrieving file system entries.</summary>
   /// <returns><c>true</c>, if the error has been fully handled and the caller may proceed, 
   /// <param name="errorCode">The error code.</param>
   /// <param name="errorMessage">The error message.</param>
   /// <param name="pathProcessed">The faulty path being processed.</param>
   /// <c>false</c> otherwise, in which case the caller will throw the corresponding exception.</returns>   
   public delegate bool ErrorHandler(int errorCode, string errorMessage, string pathProcessed);


   /// <summary>[AlphaFS] Specifies a set of custom filters to be used with enumeration methods of <see cref="Directory"/>, e.g., <see cref="Directory.EnumerateDirectories(string)"/>, <see cref="Directory.EnumerateFiles(string)"/>, or <see cref="Directory.EnumerateFileSystemEntries(string)"/>.</summary>
   /// <remarks>
   /// <see cref="DirectoryEnumerationFilters"/> allows scenarios in which files/directories being 
   /// enumerated by the methods of <see cref="Directory"/> class are accepted only if 
   /// they match the search pattern, attributes (see <see cref="DirectoryEnumerationOptions.SkipReparsePoints"/>),
   /// and optionally also the custom criteria tested in the method whose delegate is specified in <see cref="InclusionFilter"/>. 
   /// These criteria could be, e.g., file size exceeding some threshold, pathname matches a compex regular expression, etc.
   /// If the enumeration process is set to be recursive (see <see cref="DirectoryEnumerationOptions.Recursive"/>) and <see cref="RecursionFilter"/>
   /// is specified, the directory is traversed recursively only if it matches the custom criteria in <see cref="RecursionFilter"/> 
   /// method. This allows, for example, custom handling of junctions and symbolic links, e.g., detection of cycles.
   /// If any error occurs during the enumeration and the enumeration process is not set to ignore errors
   /// (see <see cref="DirectoryEnumerationOptions.ContinueOnException"/>), an exception is thrown unless
   /// the error is handled (filtered out) by the method specified in <see cref="ErrorFilter"/> (if specified).
   /// The method may, for example, consume the error by reporting it in a log, so that the enumeration continues
   /// as in the case of <see cref="DirectoryEnumerationOptions.ContinueOnException"/> option but the user will be informed about errors.
   /// </remarks>
   public class DirectoryEnumerationFilters
   {
      /// <summary>Gets or sets the filter that returns <c>true</c> if the input file system entry should be included in the enumeration.</summary>
      /// <value>The delegate to a filtering method.</value>      
      public Predicate<FileSystemEntryInfo> InclusionFilter { get; set; }


      /// <summary>Gets or sets the filter that returns <c>true</c> if the input directory should be recursively traversed.</summary>
      /// <value>The delegate to a filtering method.</value>
      public Predicate<FileSystemEntryInfo> RecursionFilter { get; set; }


      /// <summary>Gets or sets the filter that returns <c>true</c> if the input error should not be thrown.</summary>
      /// <value>The delegate to a filtering method.</value>
      public ErrorHandler ErrorFilter { get; set; }


      /// <summary>The number of retries, excluding the first attempt. Default is <c>0</c>.</summary>
      public int ErrorRetry { get; set; }


      /// <summary>The wait time in seconds between retries. Default is <c>10</c> seconds.</summary>
      public int ErrorRetryTimeout { get; set; }


#if !NET35
      /// <summary>Gets or sets the cancellation token to abort the enumeration.</summary>
      /// <value>A <see cref="CancellationToken"/> instance.</value>
      public CancellationToken CancellationToken { get; set; }
#endif
   }
}


<|start_filename|>src/AlphaFS/Resources.Designer.cs<|end_filename|>
﻿//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Alphaleonis.Win32 {
    using System;
    
    
    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {
        
        private static global::System.Resources.ResourceManager resourceMan;
        
        private static global::System.Globalization.CultureInfo resourceCulture;
        
        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }
        
        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AlphaFS.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }
        
        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Buffer is not large enough for the requested operation..
        /// </summary>
        internal static string Buffer_Not_Large_Enough {
            get {
                return ResourceManager.GetString("Buffer_Not_Large_Enough", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Cannot create directory..
        /// </summary>
        internal static string Cannot_Create_Directory {
            get {
                return ResourceManager.GetString("Cannot_Create_Directory", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Cannot determine Copy or Move action..
        /// </summary>
        internal static string Cannot_Determine_Copy_Or_Move {
            get {
                return ResourceManager.GetString("Cannot_Determine_Copy_Or_Move", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Destination buffer not large enough for the requested operation..
        /// </summary>
        internal static string Destination_Buffer_Not_Large_Enough {
            get {
                return ResourceManager.GetString("Destination_Buffer_Not_Large_Enough", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The directory is not a mount point: [{0}].
        /// </summary>
        internal static string Directory_Is_Not_A_MountPoint {
            get {
                return ResourceManager.GetString("Directory_Is_Not_A_MountPoint", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Incorrectly implemented function attempting to generate exception from successful operation.
        ///.
        /// </summary>
        internal static string Exception_From_Successful_Operation {
            get {
                return ResourceManager.GetString("Exception_From_Successful_Operation", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The specified file is hidden: [{0}].
        /// </summary>
        internal static string File_Is_Hidden {
            get {
                return ResourceManager.GetString("File_Is_Hidden", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The file or directory already exists.
        /// </summary>
        internal static string File_Or_Directory_Already_Exists {
            get {
                return ResourceManager.GetString("File_Or_Directory_Already_Exists", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Failed to get the current WindowsIdentity..
        /// </summary>
        internal static string GetCurrentWindowsIdentityFailed {
            get {
                return ResourceManager.GetString("GetCurrentWindowsIdentityFailed", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Cannot add and remove trailing DirectorySeparator simultaneously..
        /// </summary>
        internal static string GetFullPathOptions_Add_And_Remove_DirectorySeparator_Invalid {
            get {
                return ResourceManager.GetString("GetFullPathOptions_Add_And_Remove_DirectorySeparator_Invalid", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The handle is closed..
        /// </summary>
        internal static string Handle_Is_Closed {
            get {
                return ResourceManager.GetString("Handle_Is_Closed", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The handle is invalid..
        /// </summary>
        internal static string Handle_Is_Invalid {
            get {
                return ResourceManager.GetString("Handle_Is_Invalid", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The handle is invalid. Win32Error: [{0}].
        /// </summary>
        internal static string Handle_Is_Invalid_Win32Error {
            get {
                return ResourceManager.GetString("Handle_Is_Invalid_Win32Error", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Creating hard-links on non-NTFS partitions is not supported..
        /// </summary>
        internal static string HardLinks_Not_Supported {
            get {
                return ResourceManager.GetString("HardLinks_Not_Supported", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Illegal characters: [{0}] in path..
        /// </summary>
        internal static string Illegal_Characters_In_Path {
            get {
                return ResourceManager.GetString("Illegal_Characters_In_Path", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to An attempt to set an invalid file attribute failed..
        /// </summary>
        internal static string Invalid_File_Attribute {
            get {
                return ResourceManager.GetString("Invalid_File_Attribute", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The data present in the reparse point buffer is invalid.
        /// </summary>
        internal static string Invalid_Reparse_Data {
            get {
                return ResourceManager.GetString("Invalid_Reparse_Data", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Invalid stream name..
        /// </summary>
        internal static string Invalid_Stream_Name {
            get {
                return ResourceManager.GetString("Invalid_Stream_Name", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Invalid Subpath.
        /// </summary>
        internal static string Invalid_Subpath {
            get {
                return ResourceManager.GetString("Invalid_Subpath", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Invalid transaction request..
        /// </summary>
        internal static string Invalid_Transaction_Request {
            get {
                return ResourceManager.GetString("Invalid_Transaction_Request", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Argument must be a drive letter: &quot;C&quot;, RootDir: &quot;C:\&quot; or UNC path: &quot;\\server\share&quot;.
        /// </summary>
        internal static string InvalidDriveLetterArgument {
            get {
                return ResourceManager.GetString("InvalidDriveLetterArgument", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The target directory of the directory junction must be on the same local drive..
        /// </summary>
        internal static string Junction_And_Target_Must_Be_On_The_Same_Drive {
            get {
                return ResourceManager.GetString("Junction_And_Target_Must_Be_On_The_Same_Drive", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to MoveOptions.CopyAllowed is not allowed when using the MoveOptions.DelayUntilReboot flag..
        /// </summary>
        internal static string MoveOptionsDelayUntilReboot_Not_Allowed_With_MoveOptionsCopyAllowed {
            get {
                return ResourceManager.GetString("MoveOptionsDelayUntilReboot_Not_Allowed_With_MoveOptionsCopyAllowed", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to MoveOptions.DelayUntilReboot is not allowed when using a network path..
        /// </summary>
        internal static string MoveOptionsDelayUntilReboot_Not_Allowed_With_NetworkPath {
            get {
                return ResourceManager.GetString("MoveOptionsDelayUntilReboot_Not_Allowed_With_NetworkPath", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Count cannot be negative..
        /// </summary>
        internal static string Negative_Count {
            get {
                return ResourceManager.GetString("Negative_Count", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Destination offset cannot be negative..
        /// </summary>
        internal static string Negative_Destination_Offset {
            get {
                return ResourceManager.GetString("Negative_Destination_Offset", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Length cannot be negative..
        /// </summary>
        internal static string Negative_Length {
            get {
                return ResourceManager.GetString("Negative_Length", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Lock length cannot be negative..
        /// </summary>
        internal static string Negative_Lock_Length {
            get {
                return ResourceManager.GetString("Negative_Lock_Length", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Offset cannot be negative..
        /// </summary>
        internal static string Negative_Offset {
            get {
                return ResourceManager.GetString("Negative_Offset", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Network path is not allowed for directory junction: [{0}].
        /// </summary>
        internal static string Network_Path_Not_Allowed {
            get {
                return ResourceManager.GetString("Network_Path_Not_Allowed", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to No drive letters available..
        /// </summary>
        internal static string No_Drive_Letters_Available {
            get {
                return ResourceManager.GetString("No_Drive_Letters_Available", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to This stream does not support seeking..
        /// </summary>
        internal static string No_Stream_Seeking_Support {
            get {
                return ResourceManager.GetString("No_Stream_Seeking_Support", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Argument is not a valid Volume GUID..
        /// </summary>
        internal static string Not_A_Valid_Guid {
            get {
                return ResourceManager.GetString("Not_A_Valid_Guid", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Path is a zero-length string or contains only white space..
        /// </summary>
        internal static string Path_Is_Zero_Length_Or_Only_White_Space {
            get {
                return ResourceManager.GetString("Path_Is_Zero_Length_Or_Only_White_Space", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Privilege name cannot be empty..
        /// </summary>
        internal static string Privilege_Name_Cannot_Be_Empty {
            get {
                return ResourceManager.GetString("Privilege_Name_Cannot_Be_Empty", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Incomplete header read..
        /// </summary>
        internal static string Read_Incomplete_Header {
            get {
                return ResourceManager.GetString("Read_Incomplete_Header", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Invalid security descriptor returned from system..
        /// </summary>
        internal static string Returned_Invalid_Security_Descriptor {
            get {
                return ResourceManager.GetString("Returned_Invalid_Security_Descriptor", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Source offset and length outside the bounds of the array.
        /// </summary>
        internal static string Source_OffsetAndLength_Outside_Bounds {
            get {
                return ResourceManager.GetString("Source_OffsetAndLength_Outside_Bounds", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The target directory is a file, not a directory: [{0}].
        /// </summary>
        internal static string Target_Directory_Is_A_File {
            get {
                return ResourceManager.GetString("Target_Directory_Is_A_File", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The target file is a directory, not a file: [{0}].
        /// </summary>
        internal static string Target_File_Is_A_Directory {
            get {
                return ResourceManager.GetString("Target_File_Is_A_Directory", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Transaction already aborted..
        /// </summary>
        internal static string Transaction_Already_Aborted {
            get {
                return ResourceManager.GetString("Transaction_Already_Aborted", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Transaction already committed..
        /// </summary>
        internal static string Transaction_Already_Committed {
            get {
                return ResourceManager.GetString("Transaction_Already_Committed", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Invalid transaction object..
        /// </summary>
        internal static string Transaction_Invalid {
            get {
                return ResourceManager.GetString("Transaction_Invalid", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Transaction not active..
        /// </summary>
        internal static string Transaction_Not_Active {
            get {
                return ResourceManager.GetString("Transaction_Not_Active", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Transaction not requested..
        /// </summary>
        internal static string Transaction_Not_Requested {
            get {
                return ResourceManager.GetString("Transaction_Not_Requested", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Transactional conflict..
        /// </summary>
        internal static string Transactional_Conflict {
            get {
                return ResourceManager.GetString("Transactional_Conflict", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to Network share path should match the format: \\server\share.
        /// </summary>
        internal static string UNC_Path_Should_Match_Format {
            get {
                return ResourceManager.GetString("UNC_Path_Should_Match_Format", resourceCulture);
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The given path&apos;s format is not supported: [{0}].
        /// </summary>
        internal static string Unsupported_Path_Format {
            get {
                return ResourceManager.GetString("Unsupported_Path_Format", resourceCulture);
            }
        }
    }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Gets the drive letter from an MS-DOS device name. For example: "\Device\HarddiskVolume2" returns "C:\".</summary>
      /// <param name="deviceName">An MS-DOS device name.</param>
      /// <returns>The drive letter from an MS-DOS device name.</returns>
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Nt")]
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nt")]
      public static string GetDriveNameForNtDeviceName(string deviceName)
      {
         return (from drive in Directory.EnumerateLogicalDrivesCore(false, false)

            where drive.DosDeviceName.Equals(deviceName, StringComparison.OrdinalIgnoreCase)

            select drive.Name).FirstOrDefault();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CreateSubdirectoryCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Security;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Filesystem
{
   public sealed partial class DirectoryInfo
   {
      /// <summary>Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class.</summary>
      /// <returns>The last directory specified in path as an <see cref="DirectoryInfo"/> object.</returns>
      /// <remarks>
      /// Any and all directories specified in path are created, unless some part of path is invalid.
      /// The path parameter specifies a directory path, not a file path.
      /// If the subdirectory already exists, this method does nothing.
      /// </remarks>
      /// <param name="path">The specified path. This cannot be a different disk volume or Universal Naming Convention (UNC) name.</param>
      /// <param name="templatePath">The path of the directory to use as a template when creating the new directory.</param>
      /// <param name="directorySecurity">The <see cref="DirectorySecurity"/> security to apply.</param>
      /// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
      [SecurityCritical]
      private DirectoryInfo CreateSubdirectoryCore(string path, string templatePath, ObjectSecurity directorySecurity, bool compress)
      {
         var pathLp = Path.CombineCore(false, LongFullName, path);

         var templatePathLp = null == templatePath ? null : Path.GetExtendedLengthPathCore(Transaction, templatePath, PathFormat.RelativePath, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);


         if (string.Compare(LongFullName, 0, pathLp, 0, LongFullName.Length, StringComparison.OrdinalIgnoreCase) != 0)

            throw new ArgumentException(Resources.Invalid_Subpath, "path");


         return Directory.CreateDirectoryCore(false, Transaction, pathLp, templatePathLp, directorySecurity, compress, PathFormat.LongFullPath);
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Associates a volume with a Drive letter or a directory on another volume.</summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="volumeMountPoint">
      ///   The user-mode path to be associated with the volume. This may be a Drive letter (for example, "X:\")
      ///   or a directory on another volume (for example, "Y:\MountX\").
      /// </param>
      /// <param name="volumeGuid">A <see cref="string"/> containing the volume <see cref="Guid"/>.</param>      
      [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")]
      [SecurityCritical]
      public static void SetVolumeMountPoint(string volumeMountPoint, string volumeGuid)
      {
         if (Utils.IsNullOrWhiteSpace(volumeMountPoint))
            throw new ArgumentNullException("volumeMountPoint");

         if (Utils.IsNullOrWhiteSpace(volumeGuid))
            throw new ArgumentNullException("volumeGuid");

         if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase))
            throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid");


         volumeMountPoint = Path.GetFullPathCore(null, false, volumeMountPoint, GetFullPathOptions.AsLongPath | GetFullPathOptions.AddTrailingDirectorySeparator | GetFullPathOptions.FullCheck);


         // This string must be of the form "\\?\Volume{GUID}\"
         volumeGuid = Path.AddTrailingDirectorySeparator(volumeGuid, false);


         // ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
         {
            // SetVolumeMountPoint()
            // 2014-01-29: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

            // The string must end with a trailing backslash.
            var success = NativeMethods.SetVolumeMountPoint(volumeMountPoint, volumeGuid);

            var lastError = Marshal.GetLastWin32Error();
            if (!success)
            {
               // If the lpszVolumeMountPoint parameter contains a path to a mounted folder,
               // GetLastError returns ERROR_DIR_NOT_EMPTY, even if the directory is empty.

               if (lastError != Win32Errors.ERROR_DIR_NOT_EMPTY)
                  NativeError.ThrowException(lastError, volumeGuid);
            }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.GetCompressedSizeCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Retrieves the actual number of bytes of disk storage used to store a
      ///   specified file as part of a transaction. If the file is located on a volume that supports compression and the file is compressed,
      ///   the value obtained is the compressed size of the specified file. If the file is located on a volume that supports sparse files and
      ///   the file is a sparse file, the value obtained is the sparse size of the specified file.
      /// </summary>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path"><para>The name of the file.</para></param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>The actual number of bytes of disk storage used to store the specified file.</returns>      
      [SecurityCritical]
      internal static long GetCompressedSizeCore(KernelTransaction transaction, string path, PathFormat pathFormat)
      {
         if (pathFormat != PathFormat.LongFullPath && Utils.IsNullOrWhiteSpace(path))
            throw new ArgumentNullException("path");

         var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

         uint fileSizeHigh;
         var fileSizeLow = null == transaction || !NativeMethods.IsAtLeastWindowsVista

            // GetCompressedFileSize() / GetCompressedFileSizeTransacted()
            // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
            // 2017-05-30: GetCompressedFileSize() MSDN confirms LongPath usage: Starting with Windows 10, version 1607

            ? NativeMethods.GetCompressedFileSize(pathLp, out fileSizeHigh)

            : NativeMethods.GetCompressedFileSizeTransacted(pathLp, out fileSizeHigh, transaction.SafeHandle);

         var lastError = Marshal.GetLastWin32Error();


         // If the function fails, and lpFileSizeHigh is NULL, the return value is INVALID_FILE_SIZE.

         if (fileSizeLow == Win32Errors.ERROR_INVALID_FILE_SIZE && fileSizeHigh == 0)

            NativeError.ThrowException(lastError, pathLp);


         return NativeMethods.ToLong(fileSizeHigh, fileSizeLow);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Path Class/AlphaFS_Path.LocalToUnc.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class PathTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Path_LocalToUnc_Success()
      {
         UnitTestConstants.PrintUnitTestHeader(false);
         
         var sysDrive = UnitTestConstants.SysDrive;
         var windowsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
         var backslash = Alphaleonis.Win32.Filesystem.Path.DirectorySeparator;
         var hostName = Environment.MachineName + backslash + sysDrive[0] + Alphaleonis.Win32.Filesystem.Path.NetworkDriveSeparator;
         var uncPrefix = Alphaleonis.Win32.Filesystem.Path.UncPrefix;
         var uncLongPrefix = Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix;
         

         string[] localToUncPaths =
         {
            sysDrive, 
            uncPrefix + hostName,
            uncLongPrefix + hostName,

            sysDrive + backslash,
            uncPrefix + hostName + backslash,
            uncLongPrefix + hostName + backslash,

            windowsFolder,
            uncPrefix + hostName + backslash + System.IO.Path.GetFileName(windowsFolder),
            uncLongPrefix + hostName + backslash + System.IO.Path.GetFileName(windowsFolder),

            windowsFolder + backslash + "TempPath" + backslash,
            uncPrefix + hostName + backslash + System.IO.Path.GetFileName(windowsFolder) + backslash + "TempPath" + backslash,
            uncLongPrefix + hostName + backslash + System.IO.Path.GetFileName(windowsFolder) + backslash + "TempPath" + backslash
         };


         var totalPaths = localToUncPaths.Length;
         
         for (var i = 0; i < totalPaths; i += 3)
         {
            var localPath = localToUncPaths[0 + i];
            var shouldBeUncPath = localToUncPaths[1 + i];
            var shouldBeUncLongPath = localToUncPaths[2 + i];

            var uncPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(localPath);
            var uncLongPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(localPath, Alphaleonis.Win32.Filesystem.GetFullPathOptions.AsLongPath);

            Console.WriteLine("\tLocal Path   : [{0}]", localPath);
            Console.WriteLine("\tUNC Path     : [{0}]", uncPath);
            Console.WriteLine("\tUNC Long Path: [{0}]", uncLongPath);


            Assert.AreEqual(shouldBeUncPath, uncPath, "The UNC paths do not match, but are expected to.");

            Assert.AreEqual(shouldBeUncLongPath, uncLongPath, "The UNC paths do not match, but are expected to.");


            if (i % 2 != 0)
               Assert.IsTrue(uncPath.EndsWith(backslash), "The UNC path does not end with a " + backslash + " but is expected to.");


            Console.WriteLine();
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.WNet.ConnectTo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Security;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>Creates a connection to a network resource.</summary>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="remoteName">A network resource to connect to, for example: \\server or \\server\share.</param>
      [SecurityCritical]
      public static void ConnectTo(string remoteName)
      {
         ConnectDisconnectCore(new ConnectDisconnectArguments {RemoteName = remoteName});
      }

      
      /// <summary>Creates a connection to a network resource.</summary>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="remoteName">A network resource to connect to, for example: \\server or \\server\share.</param>
      /// <param name="userName">
      ///   The user name for making the connection. If <paramref name="userName"/> is <c>null</c>, the function uses the default
      ///   user name. (The user context for the process provides the default user name)
      /// </param>
      /// <param name="password">
      ///   The password to be used for making the network connection. If <paramref name="password"/> is <c>null</c>, the function
      ///   uses the current default password associated with the user specified by <paramref name="userName"/>.
      /// </param>
      /// <param name="prompt"><c>true</c> always pops-up an authentication dialog box.</param>
      /// <param name="updateProfile"><c>true</c> successful network resource connections will be saved.</param>
      /// <param name="saveCredentials">
      ///   When the operating system prompts for a credential, the credential should be saved by the credential manager when true.
      /// </param>
      [SecurityCritical]
      public static void ConnectTo(string remoteName, string userName, string password, bool prompt, bool updateProfile, bool saveCredentials)
      {
         ConnectDisconnectCore(new ConnectDisconnectArguments
         {
            RemoteName = remoteName,
            UserName = userName,
            Password = password,
            Prompt = prompt,
            UpdateProfile = updateProfile,
            SaveCredentials = saveCredentials
         });
      }

      
      /// <summary>Creates a connection to a network resource.</summary>
      /// <param name="remoteName">A network resource to connect to, for example: \\server or \\server\share.</param>
      /// <param name="credentials">An instance of <see cref="NetworkCredential"/> which provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.</param>
      /// <param name="prompt"><c>true</c> always pops-up an authentication dialog box.</param>
      /// <param name="updateProfile"><c>true</c> successful network resource connections will be saved.</param>
      /// <param name="saveCredentials">When the operating system prompts for a credential, the credential should be saved by the credential manager when true.</param>
      ///
      /// <exception cref="NetworkInformationException"/>
      [SecurityCritical]
      public static void ConnectTo(string remoteName, NetworkCredential credentials, bool prompt, bool updateProfile, bool saveCredentials)
      {
         ConnectDisconnectCore(new ConnectDisconnectArguments
         {
            RemoteName = remoteName,
            Credential = credentials,
            Prompt = prompt,
            UpdateProfile = updateProfile,
            SaveCredentials = saveCredentials
         });
      }

      
      /// <summary>Creates a connection to a network resource.</summary>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="winOwner">Handle to a window that the provider of network resources can use as an owner window for dialog boxes.</param>
      /// <param name="remoteName">A network resource to connect to, for example: \\server or \\server\share.</param>
      /// <param name="userName">
      ///   The user name for making the connection. If <paramref name="userName"/> is <c>null</c>, the function uses the default
      ///   user name. (The user context for the process provides the default user name)
      /// </param>
      /// <param name="password">
      ///   The password to be used for making the network connection. If <paramref name="password"/> is <c>null</c>, the function
      ///   uses the current default password associated with the user specified by <paramref name="userName"/>.
      /// </param>
      /// <param name="prompt"><c>true</c> always pops-up an authentication dialog box.</param>
      /// <param name="updateProfile"><c>true</c> successful network resource connections will be saved.</param>
      /// <param name="saveCredentials">When the operating system prompts for a credential, the credential should be saved by the credential manager when true.</param>
      [SecurityCritical]
      public static void ConnectTo(IntPtr winOwner, string remoteName, string userName, string password, bool prompt, bool updateProfile, bool saveCredentials)
      {
         ConnectDisconnectCore(new ConnectDisconnectArguments
         {
            WinOwner = winOwner,
            RemoteName = remoteName,
            UserName = userName,
            Password = password,
            Prompt = prompt,
            UpdateProfile = updateProfile,
            SaveCredentials = saveCredentials
         });
      }

      
      /// <summary>Creates a connection to a network resource.</summary>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="winOwner">Handle to a window that the provider of network resources can use as an owner window for dialog boxes.</param>
      /// <param name="remoteName">A network resource to connect to, for example: \\server or \\server\share.</param>
      /// <param name="credentials">An instance of <see cref="NetworkCredential"/> which provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.</param>
      /// <param name="prompt"><c>true</c> always pops-up an authentication dialog box.</param>
      /// <param name="updateProfile"><c>true</c> successful network resource connections will be saved.</param>
      /// <param name="saveCredentials">When the operating system prompts for a credential, the credential should be saved by the credential manager when true.</param>
      [SecurityCritical]
      public static void ConnectTo(IntPtr winOwner, string remoteName, NetworkCredential credentials, bool prompt, bool updateProfile, bool saveCredentials)
      {
         ConnectDisconnectCore(new ConnectDisconnectArguments
         {
            WinOwner = winOwner,
            RemoteName = remoteName,
            Credential = credentials,
            Prompt = prompt,
            UpdateProfile = updateProfile,
            SaveCredentials = saveCredentials
         });
      }
   }
}


<|start_filename|>src/AlphaFS/Network/DfsInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Filesystem;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Network
{
   /// <summary>Contains information about a Distributed File System (DFS) root or link. This class cannot be inherited.
   /// <para>This structure contains the name, status, GUID, time-out, number of targets, and information about each target of the root or link.</para>
   /// </summary>
   [Serializable]
   [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")]
   public sealed class DfsInfo
   {
      #region Constructor

      /// <summary>Initializes a new instance of the <see cref="DfsInfo"/> class which acts as a wrapper for a DFS root or link target.</summary>
      public DfsInfo()
      {
      }

      /// <summary>Initializes a new instance of the <see cref="DfsInfo"/> class, which acts as a wrapper for a DFS root or link target.</summary>
      /// <param name="structure">An initialized <see cref="NativeMethods.DFS_INFO_9"/> instance.</param>
      internal DfsInfo(NativeMethods.DFS_INFO_9 structure)
      {
         Comment = structure.Comment;
         EntryPath = structure.EntryPath;
         State = structure.State;
         Timeout = structure.Timeout;
         Guid = structure.Guid;
         MetadataSize = structure.MetadataSize;
         PropertyFlags = structure.PropertyFlags;
         SecurityDescriptor = structure.pSecurityDescriptor;

         if (structure.NumberOfStorages > 0)
         {
            var typeOfStruct = typeof (NativeMethods.DFS_STORAGE_INFO_1);
            var sizeOfStruct = Marshal.SizeOf(typeOfStruct);

            for (int i = 0; i < structure.NumberOfStorages; i++)
               _storageInfoCollection.Add(new DfsStorageInfo((NativeMethods.DFS_STORAGE_INFO_1) Marshal.PtrToStructure(new IntPtr(structure.Storage.ToInt64() + i*sizeOfStruct), typeOfStruct)));
         }
      }

      #endregion // Constructor

      #region Methods

      /// <summary>Returns the Universal Naming Convention (UNC) path of the DFS root or link.</summary>
      /// <returns>A string that represents this instance.</returns>
      public override string ToString()
      {
         return EntryPath;
      }

      #endregion // Methods

      #region Properties

      private DirectoryInfo _directoryInfo;

      /// <summary>The <see cref="DirectoryInfo"/> instance of the DFS root or link.</summary>
      public DirectoryInfo DirectoryInfo
      {
         get { return _directoryInfo ?? (_directoryInfo = new DirectoryInfo(null, EntryPath, PathFormat.FullPath)); }
      }

      /// <summary>The comment of the DFS root or link.</summary>
      public string Comment { get; internal set; }

      /// <summary>The Universal Naming Convention (UNC) path of the DFS root or link.</summary>
      public string EntryPath { get; internal set; }

      /// <summary>Specifies the GUID of the DFS root or link.</summary>
      public Guid Guid { get; internal set; }


      private readonly List<DfsStorageInfo> _storageInfoCollection = new List<DfsStorageInfo>();

      /// <summary>The collection of DFS targets of the DFS root or link.</summary>
      public IEnumerable<DfsStorageInfo> StorageInfoCollection
      {
         get { return _storageInfoCollection; }
      }

      /// <summary>An <see cref="DfsVolumeStates"/> enum that specifies a set of bit flags that describe the DFS root or link.</summary>
      public DfsVolumeStates State { get; internal set; }

      //DfsVolumeStates flavorBits = (structure3.State & (DfsVolumeStates) DfsNamespaceFlavors.All);
      //If (flavorBits == DFS_VOLUME_FLAVOR_STANDALONE)     // Namespace is stand-alone DFS.
      //else if (flavorBits == DFS_VOLUME_FLAVOR_AD_BLOB)   // Namespace is AD Blob.
      //else StateBits = (Flavor & DFS_VOLUME_STATES)        // Unknown flavor.
      // StateBits can be one of the following: 
      //  (DFS_VOLUME_STATE_OK, DFS_VOLUME_STATE_INCONSISTENT, 
      //   DFS_VOLUME_STATE_OFFLINE or DFS_VOLUME_STATE_ONLINE)
      //State = flavorBits | structure3.State;

      /// <summary>Specifies the time-out, in seconds, of the DFS root or link.</summary>
      public long Timeout { get; internal set; }

      /// <summary>Specifies a set of flags that describe specific properties of a DFS namespace, root, or link.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags")]
      public DfsPropertyFlags PropertyFlags { get; internal set; }
      
      /// <summary>For domain-based DFS namespaces, this member specifies the size of the corresponding Active Directory data blob, in bytes.
      /// For stand-alone DFS namespaces, this field specifies the size of the metadata stored in the registry,
      /// including the key names and value names, in addition to the specific data items associated with them. This field is valid for DFS roots only.
      /// </summary>
      public long MetadataSize { get; internal set; }


      /// <summary>Pointer to a SECURITY_DESCRIPTOR structure that specifies a self-relative security descriptor to be associated with the DFS link's reparse point.
      /// This field is valid for DFS links only.
      /// </summary>
      public IntPtr SecurityDescriptor { get; internal set; }
      
      #endregion // Properties
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.DeleteVolumeMountPoint.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Deletes a Drive letter or mounted folder.</summary>
      /// <remarks>Deleting a mounted folder does not cause the underlying directory to be deleted.</remarks>
      /// <remarks>
      ///   If the <paramref name="volumeMountPoint"/> parameter is a directory that is not a mounted folder, the function does nothing. The
      ///   directory is not deleted.
      /// </remarks>
      /// <remarks>
      ///   It's not an error to attempt to unmount a volume from a volume mount point when there is no volume actually mounted at that volume
      ///   mount point.
      /// </remarks>
      /// <param name="volumeMountPoint">The Drive letter or mounted folder to be deleted. For example, X:\ or Y:\MountX\.</param>      
      [SecurityCritical]
      public static void DeleteVolumeMountPoint(string volumeMountPoint)
      {
         DeleteVolumeMountPointCore(null, volumeMountPoint, false, false, PathFormat.RelativePath);
      }




      /// <summary>Deletes a Drive letter or mounted folder.
      /// <remarks>
      ///   <para>It's not an error to attempt to unmount a volume from a volume mount point when there is no volume actually mounted at that volume mount point.</para>
      ///   <para>Deleting a mounted folder does not cause the underlying directory to be deleted.</para>
      /// </remarks>
      /// </summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="NotSupportedException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="volumeMountPoint">The Drive letter or mounted folder to be deleted. For example, X:\ or Y:\MountX\.</param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      /// <param name="continueIfJunction"><c>true</c> suppress an exception due to this mount point being a Junction.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void DeleteVolumeMountPointCore(KernelTransaction transaction, string volumeMountPoint, bool continueOnException, bool continueIfJunction, PathFormat pathFormat)
      {
         if (pathFormat != PathFormat.LongFullPath)
            Path.CheckSupportedPathFormat(volumeMountPoint, true, true);

         volumeMountPoint = Path.GetExtendedLengthPathCore(transaction, volumeMountPoint, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator);


         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
         {
            // DeleteVolumeMountPoint()
            // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

            // A trailing backslash is required.
            var success = NativeMethods.DeleteVolumeMountPoint(Path.AddTrailingDirectorySeparator(volumeMountPoint, false));

            var lastError = Marshal.GetLastWin32Error();
            if (!success && !continueOnException)
            {
               if (lastError == Win32Errors.ERROR_INVALID_PARAMETER && continueIfJunction)
                  return;

               if (lastError == Win32Errors.ERROR_FILE_NOT_FOUND)
                  lastError = (int)Win32Errors.ERROR_PATH_NOT_FOUND;

               NativeError.ThrowException(lastError, volumeMountPoint);
            }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.IsSameVolume.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Determines whether the volume of two file system objects is the same, by comparing their serial numbers.</summary>
      /// <param name="path1">The first filesystem object with full path information.</param>
      /// <param name="path2">The second file system object with full path information.</param>
      /// <returns><c>true</c> if both filesytem objects reside on the same volume, <c>false</c> otherwise.</returns>
      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      [SecurityCritical]
      public static bool IsSameVolume(string path1, string path2)
      {
         try
         {
            var volInfo1 = new VolumeInfo(GetVolumePathName(path1), true, true);
            var volInfo2 = new VolumeInfo(GetVolumePathName(path2), true, true);

            return volInfo1.SerialNumber.Equals(volInfo2.SerialNumber) || volInfo1.Guid.Equals(volInfo2.Guid, StringComparison.OrdinalIgnoreCase);
         }
         catch { }

         return false;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory.GetProperties.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   partial class DirectoryTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_GetProperties_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_GetProperties(false);
         AlphaFS_Directory_GetProperties(true);
      }


      private void AlphaFS_Directory_GetProperties(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5);

            Console.WriteLine("Aggregated properties of file system objects from Directory: [{0}]\n", folder);


            var props = Alphaleonis.Win32.Filesystem.Directory.GetProperties(folder.FullName, Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.FilesAndFolders | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive);


            var total = props["Total"];
            var file = props["File"];
            var size = props["Size"];
            var cnt = 0;

            foreach (var key in props.Keys)
               Console.WriteLine("\t\t#{0:000}\t{1, -17} = [{2}]", ++cnt, key, props[key]);


            Assert.AreEqual(60, total, "The number of file system objects does not match, but it is expected.");

            Assert.AreEqual(30, file, "The number of files does not match, but it is expected.");

            Assert.AreNotEqual(0, size, "The total file system objects size is zero, which is not expected.");
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize/AlphaFS_File.GetSize_AllStreams.cs<|end_filename|>
﻿/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   partial class SizeTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_File_GetSize_AllStreams_LocalAndNetwork_Success()
      {
         AlphaFS_File_GetSize_AllStreams(false);
         AlphaFS_File_GetSize_AllStreams(true);
      }
      

      private void AlphaFS_File_GetSize_AllStreams(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var file = tempRoot.CreateFile();

            Console.WriteLine("Input File Path: [{0:N0} bytes ({1})] [{2}]\n", file.Length, Alphaleonis.Utils.UnitSizeToText(file.Length), file.FullName);


            var totalStreams = new Random(DateTime.UtcNow.Millisecond).Next(0, 10);
            var allStreamsSize = 0;
            var streamsCount = 0;

            for (var i = 0; i < totalStreams; i++)
            {
               var streamName = file.FullName + ":myStream" + i;

               var streamText = new string('X', new Random(DateTime.UtcNow.Millisecond).Next(0, 5 * UnitTestConstants.OneMebibyte));

               allStreamsSize += streamText.Length;
               streamsCount++;

               Console.WriteLine("\tAdd stream: [{0:N0} bytes ({1})] [{2}]", streamText.Length, Alphaleonis.Utils.UnitSizeToText(streamText.Length), streamName);


               // Create alternate data streams.
               // Because of the colon, you must supply a full path and use PathFormat.FullPath or PathFormat.LongFullPath,
               // to prevent a: "NotSupportedException: path is in an invalid format." exception.

               Alphaleonis.Win32.Filesystem.File.WriteAllText(streamName, streamText, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);
            }


            Console.WriteLine("\n\tTotal added Stream count: [{0}] size: [{1:N0} bytes ({2})]", streamsCount, allStreamsSize, Alphaleonis.Utils.UnitSizeToText(allStreamsSize));


            var fileSizeWithStreams = Alphaleonis.Win32.Filesystem.File.GetSize(file.FullName, true);

            Console.WriteLine("\n\tTotal File size + {0} streams: [{1:N0} bytes ({2})]", streamsCount, fileSizeWithStreams, Alphaleonis.Utils.UnitSizeToText(fileSizeWithStreams));

            Assert.AreEqual(file.Length + allStreamsSize, fileSizeWithStreams, "The file sizes do not match, but it is expected.");
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/UnitTest Utility/Dump.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;

namespace AlphaFS.UnitTest
{
   public static partial class UnitTestConstants
   {
      /// <summary>Shows the Object's available Properties and Values.</summary>
      public static void Dump(object obj, bool indent = false)
      {
         if (null == obj)
         {
            Console.WriteLine("\n\t\tNothing to dump because the instance is null.");
            return;
         }


         var allProperties = TypeDescriptor.GetProperties(obj).Sort().Cast<PropertyDescriptor>().Where(descriptor => null != descriptor).ToArray();


         // Determine widest property name, for layout.
         var width = allProperties.Select(prop => prop.Name.Length).Concat(new[] {0}).Max();

         var count = 0;
         var template = "\t{0}#{1:000}\t{2, " + -width + "} = [{3}]";

         Console.WriteLine("\n\t{0}Instance: [{1}]\n", indent ? "\t" : "", obj.GetType().FullName);


         foreach (var descriptor in allProperties)
            try
            {
               Console.WriteLine(template, indent ? "\t" : string.Empty, ++count, descriptor.Name, Write(descriptor.GetValue(obj)) ?? "NULL");
            }
            catch (Exception ex)
            {
               Console.WriteLine(template, indent ? "\t" : string.Empty, ++count, descriptor.Name, ex.Message.Replace(Environment.NewLine, "  "));
            }
      }


      private static string Write(object value)
      {
         if (null == value)
            return null;

         if (value is string)
            return value as string;


         long number;
         if (long.TryParse(value.ToString(), out number))
            return number.ToString("N0", CultureInfo.CurrentCulture);


         var objectType = value as IEnumerable;

         if (null == objectType)
            return value.ToString();


         var sb = new StringBuilder();

         foreach (var objectValue in objectType)
            sb.Append(objectValue + ", ");

         return sb.ToString().TrimEnd(',', ' ');
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo CopyToMoveTo/DirectoryInfo.MoveTo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public sealed partial class DirectoryInfo
   {
      #region .NET

      /// <summary>Moves a <see cref="DirectoryInfo"/> instance and its contents to a new path.</summary>
      /// <remarks>
      ///   <para>Use this method to prevent overwriting of an existing directory by default.</para>
      ///   <para>This method does not work across disk volumes.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">
      ///   <para>The name and path to which to move this directory.</para>
      ///   <para>The destination cannot be another disk volume or a directory with the identical name.</para>
      ///   <para>It can be an existing directory to which you want to add this directory as a subdirectory.</para>
      /// </param>
      [SecurityCritical]
      public void MoveTo(string destinationPath)
      {
         string destinationPathLp;

         CopyToMoveToCore(destinationPath, false, null, MoveOptions.None, null, null, null, out destinationPathLp, PathFormat.RelativePath);

         UpdateSourcePath(destinationPath, destinationPathLp);
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Moves a <see cref="DirectoryInfo"/> instance and its contents to a new path.</summary>
      /// <remarks>
      ///   <para>Use this method to prevent overwriting of an existing directory by default.</para>
      ///   <para>This method does not work across disk volumes.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>A new <see cref="DirectoryInfo"/> instance if the directory was completely moved.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">
      ///   <para>The name and path to which to move this directory.</para>
      ///   <para>The destination cannot be another disk volume or a directory with the identical name.</para>
      ///   <para>It can be an existing directory to which you want to add this directory as a subdirectory.</para>
      /// </param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public DirectoryInfo MoveTo(string destinationPath, PathFormat pathFormat)
      {
         string destinationPathLp;

         CopyToMoveToCore(destinationPath, false, null, MoveOptions.None, null, null, null, out destinationPathLp, pathFormat);

         UpdateSourcePath(destinationPath, destinationPathLp);

         return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath);
      }


      /// <summary>[AlphaFS] Moves a <see cref="DirectoryInfo"/> instance and its contents to a new path, <see cref="MoveOptions"/> can be specified.</summary>
      /// <remarks>
      ///   <para>Use this method to allow or prevent overwriting of an existing directory.</para>
      ///   <para>This method does not work across disk volumes unless <paramref name="moveOptions"/> contains <see cref="MoveOptions.CopyAllowed"/>.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>A new <see cref="DirectoryInfo"/> instance if the directory was completely moved.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">
      ///   <para>The name and path to which to move this directory.</para>
      ///   <para>The destination cannot be another disk volume unless <paramref name="moveOptions"/> contains <see cref="MoveOptions.CopyAllowed"/>, or a directory with the identical name.</para>
      ///   <para>It can be an existing directory to which you want to add this directory as a subdirectory.</para>
      /// </param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public DirectoryInfo MoveTo(string destinationPath, MoveOptions moveOptions)
      {
         string destinationPathLp;

         CopyToMoveToCore(destinationPath, false, null, moveOptions, null, null, null, out destinationPathLp, PathFormat.RelativePath);

         UpdateSourcePath(destinationPath, destinationPathLp);

         return null != destinationPathLp ? new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath) : null;
      }


      /// <summary>[AlphaFS] Moves a <see cref="DirectoryInfo"/> instance and its contents to a new path, <see cref="MoveOptions"/> can be specified.</summary>
      /// <remarks>
      ///   <para>Use this method to allow or prevent overwriting of an existing directory.</para>
      ///   <para>This method does not work across disk volumes unless <paramref name="moveOptions"/> contains <see cref="MoveOptions.CopyAllowed"/>.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>A new <see cref="DirectoryInfo"/> instance if the directory was completely moved.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">
      ///   <para>The name and path to which to move this directory.</para>
      ///   <para>The destination cannot be another disk volume unless <paramref name="moveOptions"/> contains <see cref="MoveOptions.CopyAllowed"/>, or a directory with the identical name.</para>
      ///   <para>It can be an existing directory to which you want to add this directory as a subdirectory.</para>
      /// </param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public DirectoryInfo MoveTo(string destinationPath, MoveOptions moveOptions, PathFormat pathFormat)
      {
         string destinationPathLp;

         CopyToMoveToCore(destinationPath, false, null, moveOptions, null, null, null, out destinationPathLp, pathFormat);

         UpdateSourcePath(destinationPath, destinationPathLp);

         return null != destinationPathLp ? new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath) : null;
      }


      /// <summary>[AlphaFS] Moves a <see cref="DirectoryInfo"/> instance and its contents to a new path, <see cref="MoveOptions"/> can be specified,
      /// and the possibility of notifying the application of its progress through a callback function.
      /// </summary>
      /// <remarks>
      ///   <para>Use this method to allow or prevent overwriting of an existing directory.</para>
      ///   <para>This method does not work across disk volumes unless <paramref name="moveOptions"/> contains <see cref="MoveOptions.CopyAllowed"/>.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>A <see cref="CopyMoveResult"/> class with details of the Move action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">
      ///   <para>The name and path to which to move this directory.</para>
      ///   <para>The destination cannot be another disk volume unless <paramref name="moveOptions"/> contains <see cref="MoveOptions.CopyAllowed"/>, or a directory with the identical name.</para>
      ///   <para>It can be an existing directory to which you want to add this directory as a subdirectory.</para>
      /// </param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the directory has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         // Reject DelayUntilReboot.
         if ((moveOptions & MoveOptions.DelayUntilReboot) != 0)
            throw new ArgumentException("The DelayUntilReboot flag is invalid for this method.", "moveOptions");

         string destinationPathLp;

         var cmr = CopyToMoveToCore(destinationPath, false, null, moveOptions, null, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath);

         UpdateSourcePath(destinationPath, destinationPathLp);

         return cmr;
      }


      /// <summary>[AlphaFS] Moves a <see cref="DirectoryInfo"/> instance and its contents to a new path, <see cref="MoveOptions"/> can be specified,
      ///   <para>and the possibility of notifying the application of its progress through a callback function.</para>
      /// </summary>
      /// <remarks>
      ///   <para>Use this method to allow or prevent overwriting of an existing directory.</para>
      ///   <para>This method does not work across disk volumes unless <paramref name="moveOptions"/> contains <see cref="MoveOptions.CopyAllowed"/>.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>A <see cref="CopyMoveResult"/> class with details of the Move action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="destinationPath">
      ///   <para>The name and path to which to move this directory.</para>
      ///   <para>The destination cannot be another disk volume unless <paramref name="moveOptions"/> contains <see cref="MoveOptions.CopyAllowed"/>, or a directory with the identical name.</para>
      ///   <para>It can be an existing directory to which you want to add this directory as a subdirectory.</para>
      /// </param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the directory has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         // Reject DelayUntilReboot.
         if ((moveOptions & MoveOptions.DelayUntilReboot) != 0)
            throw new ArgumentException("The DelayUntilReboot flag is invalid for this method.", "moveOptions");

         string destinationPathLp;

         var cmr = CopyToMoveToCore(destinationPath, false, null, moveOptions, null, progressHandler, userProgressData, out destinationPathLp, pathFormat);

         UpdateSourcePath(destinationPath, destinationPathLp);

         return cmr;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory.GetCurrentDirectory.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>
      /// Gets the current working directory of the application.
      /// <para>
      ///   MSDN: Multithreaded applications and shared library code should not use the GetCurrentDirectory function and should avoid using relative path names.
      ///   The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,
      ///   therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.
      ///   <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,
      ///   for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
      ///   <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
      /// </para>
      /// </summary>
      /// <returns>The path of the current working directory without a trailing directory separator.</returns>
      [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate"), SecurityCritical]
      public static string GetCurrentDirectory()
      {
         var nameBuffer = new StringBuilder(NativeMethods.MaxPathUnicode);

         // GetCurrentDirectory()
         // 2016-09-29: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
         // 2017-05-30: MSDN confirms LongPath usage: Starting with Windows 10, version 1607
         // 2018-01-15: MSDN confirmation is gone?

         var folderNameLength = NativeMethods.GetCurrentDirectory((uint) nameBuffer.Capacity, nameBuffer);
         var lastError = Marshal.GetLastWin32Error();

         if (folderNameLength == 0)
            NativeError.ThrowException(lastError);

         if (folderNameLength > NativeMethods.MaxPathUnicode)
            throw new PathTooLongException(string.Format(CultureInfo.InvariantCulture, "Path is greater than {0} characters: {1}", NativeMethods.MaxPathUnicode, folderNameLength));

         return nameBuffer.ToString();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File CopyMove/File.ValidateFileOrDirectoryMoveArguments.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      internal static CopyMoveArguments ValidateFileOrDirectoryMoveArguments(CopyMoveArguments cma, bool driveChecked, bool isFolder)
      {
         string unusedSourcePathLp;
         string unusedDestinationPathLp;

         return ValidateFileOrDirectoryMoveArguments(cma, driveChecked, isFolder, cma.SourcePath, cma.DestinationPath, out unusedSourcePathLp, out unusedDestinationPathLp);
      }


      /// <summary>Validates and updates the file/directory copy/move arguments and updates them accordingly. This happens only once per <see cref="CopyMoveArguments"/> instance.</summary>
      private static CopyMoveArguments ValidateFileOrDirectoryMoveArguments(CopyMoveArguments cma, bool driveChecked, bool isFolder, string sourcePath, string destinationPath, out string sourcePathLp, out string destinationPathLp)
      {
         sourcePathLp = sourcePath;
         destinationPathLp = destinationPath;
         
         if (cma.PathsChecked)
            return cma;


         cma.IsCopy = IsCopyAction(cma);

         if (!cma.IsCopy)
            cma.DelayUntilReboot = VerifyDelayUntilReboot(sourcePath, cma.MoveOptions, cma.PathFormat);


         if (cma.PathFormat != PathFormat.LongFullPath)
         {
            if (null == sourcePath)
               throw new ArgumentNullException("sourcePath");
            
            // File Move action: destinationPath is allowed to be null when MoveOptions.DelayUntilReboot is specified.

            if (!cma.DelayUntilReboot && null == destinationPath)
               throw new ArgumentNullException("destinationPath");
            

            if (sourcePath.Trim().Length == 0)
               throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "sourcePath");

            if (null != destinationPath && destinationPath.Trim().Length == 0)
               throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "destinationPath");


            // MSDN: .NET3.5+: IOException: The sourceDirName and destDirName parameters refer to the same file or directory.
            // Do not use StringComparison.OrdinalIgnoreCase to allow renaming a folder with different casing.

            if (sourcePath.Equals(destinationPath, StringComparison.Ordinal))
               NativeError.ThrowException(Win32Errors.ERROR_SAME_DRIVE, destinationPath);


            if (!driveChecked)
            {
               // Check for local or network drives, such as: "C:" or "\\server\c$" (but not for "\\?\GLOBALROOT\").
               if (!sourcePath.StartsWith(Path.GlobalRootPrefix, StringComparison.OrdinalIgnoreCase))
                  Directory.ExistsDriveOrFolderOrFile(cma.Transaction, sourcePath, isFolder, (int) Win32Errors.NO_ERROR, true, false);


               // File Move action: destinationPath is allowed to be null when MoveOptions.DelayUntilReboot is specified.
               if (!cma.DelayUntilReboot)
                  Directory.ExistsDriveOrFolderOrFile(cma.Transaction, destinationPath, isFolder, (int) Win32Errors.NO_ERROR, true, false);
            }


            // MSDN: .NET 4+ Trailing spaces are removed from the end of the path parameters before moving the directory.
            // TrimEnd() is also applied for AlphaFS implementation of method Directory.Copy(), .NET does not have this method.

            const GetFullPathOptions fullPathOptions = GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator;


            sourcePathLp = Path.GetExtendedLengthPathCore(cma.Transaction, sourcePath, cma.PathFormat, fullPathOptions);

            if (isFolder || !cma.IsCopy)
               cma.SourcePathLp = sourcePathLp;


            // When destinationPath is null, the file/folder needs to be removed on Computer startup.

            cma.DeleteOnStartup = cma.DelayUntilReboot && null == destinationPath;
            
            if (!cma.DeleteOnStartup)
            {
               Path.CheckSupportedPathFormat(destinationPath, true, true);

               destinationPathLp = Path.GetExtendedLengthPathCore(cma.Transaction, destinationPath, cma.PathFormat, fullPathOptions);


               if (isFolder || !cma.IsCopy)
               {
                  cma.DestinationPathLp = destinationPathLp;

                  // Process Move action options, possible fallback to Copy action.

                  if (!cma.IsCopy)
                     cma = Directory.ValidateMoveAction(cma);
               }


               if (cma.IsCopy)
               {
                  cma.CopyTimestamps = HasCopyTimestamps(cma.CopyOptions);

                  if (cma.CopyTimestamps)

                     // Remove the AlphaFS flag since it is unknown to the native Win32 CopyFile/MoveFile functions.

                     cma.CopyOptions &= ~CopyOptions.CopyTimestamp;
               }
            }


            // Setup callback function for progress notifications.

            if (null == cma.Routine && null != cma.ProgressHandler)
            {
               cma.Routine = (totalFileSize, totalBytesTransferred, streamSize, streamBytesTransferred, streamNumber, callbackReason, sourceFile, destinationFile, data) =>

                     cma.ProgressHandler(totalFileSize, totalBytesTransferred, streamSize, streamBytesTransferred, (int) streamNumber, callbackReason, cma.UserProgressData);
            }


            cma.PathFormat = PathFormat.LongFullPath;

            cma.PathsChecked = true;
         }
         

         return cma;
      }
   }
}


<|start_filename|>src/AlphaFS/Security/Native Other/TOKEN.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;

namespace Alphaleonis.Win32.Security
{
   internal static partial class NativeMethods
   {
      /// <summary>[AlphaFS] Access rights for access-token objects.</summary>
      [Flags]
      internal enum TOKEN : uint
      {
         /// <summary>Required to attach a primary token to a process. The SE_ASSIGNPRIMARYTOKEN_NAME privilege is also required to accomplish this task.</summary>
         TOKEN_ASSIGN_PRIMARY = 1,

         /// <summary>Required to duplicate an access token.</summary>
         TOKEN_DUPLICATE = 2,

         /// <summary>Required to attach an impersonation access token to a process.</summary>
         TOKEN_IMPERSONATE = 4,

         /// <summary>Required to query an access token.</summary>
         TOKEN_QUERY = 8,

         /// <summary>Required to query the source of an access token.</summary>
         TOKEN_QUERY_SOURCE = 16,

         /// <summary>Required to enable or disable the privileges in an access token.</summary>
         TOKEN_ADJUST_PRIVILEGES = 32,

         /// <summary>Required to adjust the attributes of the groups in an access token.</summary>
         TOKEN_ADJUST_GROUPS = 64,

         /// <summary>Required to change the default owner, primary group, or DACL of an access token.</summary>
         TOKEN_ADJUST_DEFAULT = 128,

         /// <summary>Required to adjust the session ID of an access token. The SE_TCB_NAME privilege is required.</summary>
         TOKEN_ADJUST_SESSIONID = 256,

         /// <summary>Combines STANDARD_RIGHTS_READ and TOKEN_QUERY.</summary>
         TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY,

         /// <summary>Combines all possible access rights for a token.</summary>
         TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
                            TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.CopyMoveCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Security;
using System.Threading;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      // Symbolic Link Effects on File Systems Functions: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365682(v=vs.85).aspx


      /// <summary>Copy/move a Non-/Transacted file or directory including its children to a new location, <see cref="CopyOptions"/> or <see cref="MoveOptions"/> can be specified,
      /// and the possibility of notifying the application of its progress through a callback function.
      /// </summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file, unless
      ///   <paramref name="cma.MoveOptions"/> contains <see cref="MoveOptions.ReplaceExisting"/>.</para>
      ///   <para>This Move method works across disk volumes, and it does not throw an exception if the
      ///   source and destination are the same. </para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into
      ///   that directory, you get an IOException.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with the status of the Copy or Move action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
      [SecurityCritical]
      internal static CopyMoveResult CopyMoveCore(bool retry, CopyMoveArguments cma, bool driveChecked, bool isFolder, string sourceFilePath, string destinationFilePath, CopyMoveResult copyMoveResult)
      {
         #region Setup

         cma = ValidateFileOrDirectoryMoveArguments(cma, driveChecked, false, sourceFilePath, destinationFilePath, out sourceFilePath, out destinationFilePath);


         var copyMoveRes = copyMoveResult ?? new CopyMoveResult(cma, isFolder, sourceFilePath, destinationFilePath);

         var isSingleFileAction = null == copyMoveResult && copyMoveRes.IsFile;


         var attempts = 1;

         var retryTimeout = 0;

         var errorFilter = null != cma.DirectoryEnumerationFilters && null != cma.DirectoryEnumerationFilters.ErrorFilter ? cma.DirectoryEnumerationFilters.ErrorFilter : null;

         if (retry)
         {
            if (null != errorFilter)
            {
               attempts += cma.DirectoryEnumerationFilters.ErrorRetry;

               retryTimeout = cma.DirectoryEnumerationFilters.ErrorRetryTimeout;
            }

            else
            {
               if (cma.Retry <= 0)
                  cma.Retry = 2;

               if (cma.RetryTimeout <= 0)
                  cma.RetryTimeout = 10;

               attempts += cma.Retry;

               retryTimeout = cma.RetryTimeout;
            }
         }


         // Calling start on a running Stopwatch is a no-op.
         copyMoveRes.Stopwatch.Start();

         #endregion // Setup


         while (attempts-- > 0)
         {
            // MSDN: If this flag is set to TRUE during the copy/move operation, the operation is canceled.
            // Otherwise, the copy/move operation will continue to completion.
            bool cancel;

            copyMoveRes.ErrorCode = (int) Win32Errors.NO_ERROR;

            copyMoveRes.IsCanceled = false;

            int lastError;

            
            if (!cma.DelayUntilReboot)
            {
               // Ensure the file's parent directory exists.

               var parentFolder = Directory.GetParentCore(cma.Transaction, destinationFilePath, PathFormat.LongFullPath);

               if (null != parentFolder)
                  parentFolder.Create();
            }


            if (CopyMoveNative(cma, !cma.IsCopy, sourceFilePath, destinationFilePath, out cancel, out lastError))
            {
               // We take an extra hit by getting the file size for a single file Copy or Move action.

               if (isSingleFileAction)

                  copyMoveRes.TotalBytes = GetSizeCore(null, cma.Transaction, destinationFilePath, true, PathFormat.LongFullPath);


               if (!isFolder)
               {
                  copyMoveRes.TotalFiles++;

                  // Only set timestamps for files.

                  if (cma.CopyTimestamps)

                     CopyTimestampsCore(cma.Transaction, false, sourceFilePath, destinationFilePath, false, PathFormat.LongFullPath);
               }
               
               break;
            }


            // The Copy/Move action failed or is canceled.

            copyMoveRes.ErrorCode = lastError;

            copyMoveRes.IsCanceled = cancel;

            
            // Report the Exception back to the caller.
            if (null != errorFilter)
            {
               var continueCopyMove = errorFilter(lastError, new Win32Exception(lastError).Message, Path.GetCleanExceptionPath(destinationFilePath));

               if (!continueCopyMove)
               {
                  copyMoveRes.IsCanceled = true;
                  break;
               }
            }


            if (!cancel)
            {
               if (retry)
                  copyMoveRes.Retries++;

               retry = attempts > 0 && retryTimeout > 0;


               // Remove any read-only/hidden attribute, which might also fail.

               RestartMoveOrThrowException(retry, lastError, isFolder, !cma.IsCopy, cma, sourceFilePath, destinationFilePath);

               if (retry)
               {
                  if (null != errorFilter && null != cma.DirectoryEnumerationFilters.CancellationToken)
                  {
                     if (cma.DirectoryEnumerationFilters.CancellationToken.WaitHandle.WaitOne(retryTimeout * 1000))
                     {
                        copyMoveRes.IsCanceled = true;
                        break;
                     }
                  }

                  else
                     using (var waitEvent = new ManualResetEvent(false))
                        waitEvent.WaitOne(retryTimeout * 1000);
               }
            }
         }

         
         if (isSingleFileAction)
            copyMoveRes.Stopwatch.Stop();

         copyMoveResult = copyMoveRes;

         return copyMoveResult;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_FolderWithSpaceAsName.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class EnumerationTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_EnumerateFileSystemEntryInfos_FolderWithSpaceAsName_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_EnumerateFileSystemEntryInfos_FolderWithSpaceAsName(false);
         AlphaFS_Directory_EnumerateFileSystemEntryInfos_FolderWithSpaceAsName(true);
      }


      private void AlphaFS_Directory_EnumerateFileSystemEntryInfos_FolderWithSpaceAsName(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            const int maxFso = 5;
            const int expectedFso = 12;

            var folder = tempRoot.CreateRandomizedAttributesTree(maxFso);
            
            Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName);
            

            for (var i = 0; i < maxFso; i++)
            {
               var spaceFolder = folder.FullName + @"\" + new string(' ', i + 1) + @"\" + "no_void";

               Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(spaceFolder, Alphaleonis.Win32.Filesystem.PathFormat.LongFullPath);
            }
            

            var countNamedFolders = 0;
            var countSpaceFolders = 0;

            foreach (var fsei in Alphaleonis.Win32.Filesystem.Directory.EnumerateFileSystemEntryInfos<Alphaleonis.Win32.Filesystem.FileSystemInfo>(folder.FullName))
            {
               var path = fsei.FullName;

               Console.WriteLine("\tDirectory: [{0}]", path);


               if (char.IsWhiteSpace(path[path.Length - 1]))
               {
                  countSpaceFolders++;
                  Assert.IsTrue(fsei.Exists);
               }

               else
                  countNamedFolders++;
            }


            Assert.AreEqual(expectedFso, countNamedFolders + countSpaceFolders);
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Safe Handles/SafeEncryptedFileRawHandle.cs<|end_filename|>
using System;
using System.Security;
using Microsoft.Win32.SafeHandles;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Represents a wrapper class for a handle used by the OpenEncryptedFileRaw Win32 API functions.</summary>
   [SecurityCritical]
   internal sealed class SafeEncryptedFileRawHandle : SafeHandleZeroOrMinusOneIsInvalid
   {
      /// <summary>Constructor that prevents a default instance of this class from being created.</summary>
      private SafeEncryptedFileRawHandle() : base(true)
      {
      }


      /// <summary>Initializes a new instance of the <see cref="SafeEncryptedFileRawHandle"/> class.</summary>
      /// <param name="handle">The handle.</param>
      /// <param name="callerHandle"><c>true</c> to reliably release the handle during the finalization phase; <c>false</c> to prevent reliable release (not recommended).</param>
      public SafeEncryptedFileRawHandle(IntPtr handle, bool callerHandle) : base(callerHandle)
      {
         SetHandle(handle);
      }

      
      /// <summary>When overridden in a derived class, executes the code required to free the handle.</summary>
      /// <returns>
      /// <c>true</c> if the handle is released successfully; otherwise, in the event of a catastrophic failure,
      /// <c>false</c>. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant.
      /// </returns>
      protected override bool ReleaseHandle()
      {
         NativeMethods.CloseEncryptedFileRaw(handle);

         return true;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_And_Delete_CreatesStructureWithoutFiles.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class Directory_CreateDirectoryTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void Directory_CreateDirectory_And_Delete_CreatesStructureWithoutFiles_LocalAndNetwork_Success()
      {
         Directory_CreateDirectory_And_Delete_CreatesStructureWithoutFiles(false);
         Directory_CreateDirectory_And_Delete_CreatesStructureWithoutFiles(true);
      }


      private void Directory_CreateDirectory_And_Delete_CreatesStructureWithoutFiles(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.Directory.FullName;

            Console.WriteLine("Input Directory Path: [{0}]\n", folder);


            // Directory depth level.
            var level = new Random().Next(10, 500);

#if NET35
            // MSDN: .NET 4+ Trailing spaces are removed from the end of the path parameter before deleting the directory.
            folder += "\u3000"; // EMspace
#endif

            var root = folder;

            for (var i = 0; i < level; i++)
            {
               var isEven = i % 2 == 0;
               root = System.IO.Path.Combine(root, (isEven ? "Level-" : "Lëvél-") + (i + 1) + (isEven ? "-subFolder" : "-sübFôldér"));
            }

            Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(root);

            Console.WriteLine("\tCreated directory structure: Depth: [{0}], path length: [{1}] characters.", level.ToString(), root.Length.ToString());
            Console.WriteLine();

            Console.WriteLine("\t{0}", root);
            Console.WriteLine();

            Assert.IsTrue(Alphaleonis.Win32.Filesystem.Directory.Exists(root), "The directory does not exists, but is expected to.");


            Alphaleonis.Win32.Filesystem.Directory.Delete(folder, true);

            Assert.IsFalse(System.IO.Directory.Exists(folder), "The directory exists, but is expected not to.");
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Junctions, Links/File.CreateHardLink.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      #region Obsolete

      /// <summary>[AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file. This function is only supported on the NTFS file system, and only for files, not directories.</summary>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="fileName">The name of the new file. This parameter cannot specify the name of a directory.</param>
      /// <param name="existingFileName">The name of the existing file. This parameter cannot specify the name of a directory.</param>      
      [Obsolete("Use CreateHardLink method.")]
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlink")]
      [SecurityCritical]
      public static void CreateHardlink(string fileName, string existingFileName)
      {
         CreateHardLinkCore(null, fileName, existingFileName, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file. This function is only supported on the NTFS file system, and only for files, not directories.</summary>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="fileName">The name of the new file. This parameter cannot specify the name of a directory.</param>
      /// <param name="existingFileName">The name of the existing file. This parameter cannot specify the name of a directory.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>      
      [Obsolete("Use CreateHardLink method.")]
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlink")]
      [SecurityCritical]
      public static void CreateHardlink(string fileName, string existingFileName, PathFormat pathFormat)
      {
         CreateHardLinkCore(null, fileName, existingFileName, pathFormat);
      }

      #endregion // Obsolete


      /// <summary>[AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file. This function is only supported on the NTFS file system, and only for files, not directories.</summary>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="fileName">The name of the new file. This parameter cannot specify the name of a directory.</param>
      /// <param name="existingFileName">The name of the existing file. This parameter cannot specify the name of a directory.</param>      
      [SecurityCritical]
#pragma warning disable CS3005 // Identifier differing only in case is not CLS-compliant
      public static void CreateHardLink(string fileName, string existingFileName)
#pragma warning restore CS3005 // Identifier differing only in case is not CLS-compliant
      {
         CreateHardLinkCore(null, fileName, existingFileName, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Establishes a hard link (similar to CMD command: "MKLINK /H") between an existing file and a new file. This function is only supported on the NTFS file system, and only for files, not directories.</summary>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="fileName">The name of the new file. This parameter cannot specify the name of a directory.</param>
      /// <param name="existingFileName">The name of the existing file. This parameter cannot specify the name of a directory.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>      
      [SecurityCritical]
#pragma warning disable CS3005 // Identifier differing only in case is not CLS-compliant
      public static void CreateHardLink(string fileName, string existingFileName, PathFormat pathFormat)
#pragma warning restore CS3005 // Identifier differing only in case is not CLS-compliant
      {
         CreateHardLinkCore(null, fileName, existingFileName, pathFormat);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Path Class/Path.GetFullPath/AlphaFS_Path.GetFullPath_WithTrailingDotOrSpace.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class PathTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Path_GetFullPath_WithTrailingDotOrSpace_LocalAndNetwork_Success()
      {
         AlphaFS_Path_GetFullPath_WithTrailingDotOrSpace(false);
         AlphaFS_Path_GetFullPath_WithTrailingDotOrSpace(true);
      }


      private void AlphaFS_Path_GetFullPath_WithTrailingDotOrSpace(bool isNetwork)
      {
         UnitTestConstants.PrintUnitTestHeader(isNetwork);
         
         const string characterDot = ".";
         const string characterSpace = " ";
         var tempPathDot = "Path-with-trailing-dot-" + characterDot;
         var tempPathSpace = "Path-with-trailing-space-" + characterSpace;


         Console.WriteLine("Input Path (with dot)  : [{0}]", tempPathDot);
         Console.WriteLine("Input Path (with space): [{0}]", tempPathSpace);




         // By default, trailing dot or space is removed.
         var fileDot = Alphaleonis.Win32.Filesystem.Path.GetFullPath(tempPathDot);
         var fileSpace = Alphaleonis.Win32.Filesystem.Path.GetFullPath(tempPathSpace);
         if (isNetwork)
         {
            fileDot = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fileDot);
            fileSpace = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fileSpace);
         }
         Console.WriteLine();
         Console.WriteLine("Path (without dot)  : [{0}]", fileDot);
         Console.WriteLine("Path (without space): [{0}]", fileSpace);

         Assert.IsFalse(fileDot.EndsWith(characterDot), "The path has a trailing dot, but is expected not to.");
         Assert.IsFalse(fileSpace.EndsWith(characterSpace), "The path has a trailing space, but is expected not to.");




         fileDot = Alphaleonis.Win32.Filesystem.Path.GetFullPath(tempPathDot, Alphaleonis.Win32.Filesystem.GetFullPathOptions.KeepDotOrSpace);
         fileSpace = Alphaleonis.Win32.Filesystem.Path.GetFullPath(tempPathSpace, Alphaleonis.Win32.Filesystem.GetFullPathOptions.KeepDotOrSpace);
         if (isNetwork)
         {
            fileDot = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fileDot);
            fileSpace = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fileSpace);
         }
         Console.WriteLine();
         Console.WriteLine("Path (with dot)  : [{0}]", fileDot);
         Console.WriteLine("Path (with space): [{0}]", fileSpace);

         Assert.IsTrue(fileDot.EndsWith(characterDot), "The path does not have a trailing dot, but is expected to.");
         Assert.IsTrue(fileSpace.EndsWith(characterSpace), "The path does not have a trailing space, but is expected to.");

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Security/CRC/Crc32.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 *
 * 
 * Copyright (c) <NAME>.  All rights reserved.
 * AlphaFS has written permission from the author to include the CRC code.
 */

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;

namespace Alphaleonis.Win32.Security
{
   /// <summary>Implements a 32-bit CRC hash algorithm compatible with Zip etc.</summary>
   /// <remarks>
   ///   Crc32 should only be used for backward compatibility with older file formats and algorithms.
   ///   It is not secure enough for new applications. If you need to call multiple times for the same data
   ///   either use the HashAlgorithm interface or remember that the result of one Compute call needs to be ~ (XOR)
   ///   before being passed in as the seed for the next Compute call.
   /// </remarks>
   [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Crc")]
   internal sealed class Crc32 : HashAlgorithm
   {
      private const uint DefaultPolynomial = 0xedb88320u;
      private const uint DefaultSeed = 0xffffffffu;

      private uint m_hash;
      private readonly uint m_seed;
      private readonly uint[] m_table;
      private static uint[] s_defaultTable;
      

      /// <summary>Initializes a new instance of Crc32.</summary>
      public Crc32() : this(DefaultPolynomial, DefaultSeed)
      {
      }


      /// <summary>Initializes a new instance of Crc32.</summary>
      /// <param name="polynomial">The polynomial.</param>
      /// <param name="seed">The seed.</param>
      private Crc32(uint polynomial, uint seed)
      {
         m_table = InitializeTable(polynomial);
         m_seed = seed;
         m_hash = seed;
      }


      /// <summary>Initializes an implementation of the <see cref="T:System.Security.Cryptography.HashAlgorithm"/> class.</summary>
      public override void Initialize()
      {
         m_hash = m_seed;
      }


      /// <summary>When overridden in a derived class, routes data written to the object into the hash algorithm for computing the hash.</summary>
      /// <param name="array">The input to compute the hash code for..</param>
      /// <param name="ibStart">The offset into the byte array from which to begin using data.</param>
      /// <param name="cbSize">The number of bytes in the byte array to use as data.</param>
      protected override void HashCore(byte[] array, int ibStart, int cbSize)
      {
         m_hash = CalculateHash(m_table, m_hash, array, ibStart, cbSize);
      }


      /// <summary>Finalizes the hash computation after the last data is processed by the cryptographic stream object.</summary>
      /// <returns>This method finalizes any partial computation and returns the correct hash value for the data stream.</returns>
      protected override byte[] HashFinal()
      {
         var hashBuffer = UInt32ToBigEndianBytes(~m_hash);
         HashValue = hashBuffer;
         return hashBuffer;
      }


      /// <summary>Gets the size, in bits, of the computed hash code.</summary>
      /// <value>The size, in bits, of the computed hash code.</value>
      public override int HashSize
      {
         get { return 32; }
      }


      /// <summary>Initializes the table.</summary>
      /// <returns>The table.</returns>
      /// <param name="polynomial">The polynomial.</param>
      private static uint[] InitializeTable(uint polynomial)
      {
         if (polynomial == DefaultPolynomial && s_defaultTable != null)
            return s_defaultTable;

         var createTable = new uint[256];

         for (var i = 0; i < 256; i++)
         {
            var entry = (uint) i;

            for (var j = 0; j < 8; j++)
               entry = (entry & 1) == 1 ? (entry >> 1) ^ polynomial : entry >> 1;

            createTable[i] = entry;
         }

         if (polynomial == DefaultPolynomial)
            s_defaultTable = createTable;

         return createTable;
      }


      /// <summary>Calculates the hash.</summary>
      /// <returns>The calculated hash.</returns>
      /// <param name="table">The table.</param>
      /// <param name="seed">The seed.</param>
      /// <param name="buffer">The buffer.</param>
      /// <param name="start">The start.</param>
      /// <param name="size">The size.</param>
      private static uint CalculateHash(uint[] table, uint seed, IList<byte> buffer, int start, int size)
      {
         var hash = seed;

         for (var i = start; i < start + size; i++)
            hash = (hash >> 8) ^ table[buffer[i] ^ hash & 0xff];

         return hash;
      }


      /// <summary>Int 32 to big endian bytes.</summary>
      /// <returns>A byte[].</returns>
      /// <param name="uint32">The second uint 3.</param>
      private static byte[] UInt32ToBigEndianBytes(uint uint32)
      {
         var result = BitConverter.GetBytes(uint32);

         if (BitConverter.IsLittleEndian)
            Array.Reverse(result);

         return result;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Other/FINDEX_SEARCH_OPS.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      /// <summary>FINDEX_SEARCH_OPS Enumeration - Defines values that are used with the FindFirstFileEx function to specify the type of filtering to perform.</summary>
      /// <remarks>
      ///   <para>Minimum supported client: Windows XP [desktop apps | Windows Store apps]</para>
      ///   <para>Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps]</para>
      /// </remarks>
      internal enum FINDEX_SEARCH_OPS
      {
         /// <summary>The search for a file that matches a specified file name.
         /// <para>The lpSearchFilter parameter of FindFirstFileEx must be NULL when this search operation is used.</para>
         /// </summary>
         SearchNameMatch = 0,

         /// <summary>This is an advisory flag. If the file system supports directory filtering,
         /// <para>the function searches for a file that matches the specified name and is also a directory.</para> 
         /// <para>If the file system does not support directory filtering, this flag is silently ignored.</para>
         /// <para>&#160;</para>
         /// <remarks>
         /// <para>The lpSearchFilter parameter of the FindFirstFileEx function must be NULL when this search value is used.</para>
         /// <para>If directory filtering is desired, this flag can be used on all file systems,</para>
         /// <para>but because it is an advisory flag and only affects file systems that support it,</para>
         /// <para>the application must examine the file attribute data stored in the lpFindFileData parameter</para>
         /// <para>of the FindFirstFileEx function to determine whether the function has returned a handle to a directory.</para>
         /// </remarks>
         /// </summary>
         SearchLimitToDirectories = 1,

         /// <summary>This filtering type is not available.</summary>
         /// <remarks>For more information, see Device Interface Classes.</remarks>
         SearchLimitToDevices = 2
      }
   }
}

<|start_filename|>src/AlphaFS/Network/Host Class/Host.SMB.GetShareInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Globalization;
using System.Net.NetworkInformation;
using System.Security;
using Alphaleonis.Win32.Filesystem;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>Retrieves information about the Server Message Block (SMB) share as defined on the specified host.</summary>
      /// <returns>A <see cref="ShareInfo"/> class, or <c>null</c> on failure or when not available, and <paramref name="continueOnException"/> is <c>true</c>.</returns>
      /// <param name="uncPath">The share in the format: \\host\share.</param>
      /// <param name="continueOnException"><c>true</c> to suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public static ShareInfo GetShareInfo(string uncPath, bool continueOnException)
      {
         var unc = GetHostShareFromPath(uncPath);
         return GetShareInfoCore(ShareInfoLevel.Info503, unc[0], unc[1], continueOnException);
      }

      
      /// <summary>Retrieves information about the Server Message Block (SMB) share as defined on the specified host.</summary>
      /// <returns>A <see cref="ShareInfo"/> class, or <c>null</c> on failure or when not available, and <paramref name="continueOnException"/> is <c>true</c>.</returns>
      /// <param name="shareLevel">One of the <see cref="ShareInfoLevel"/> options.</param>
      /// <param name="uncPath">The share in the format: \\host\share.</param>
      /// <param name="continueOnException"><c>true</c> to suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public static ShareInfo GetShareInfo(ShareInfoLevel shareLevel, string uncPath, bool continueOnException)
      {
         var unc = GetHostShareFromPath(uncPath);
         return GetShareInfoCore(shareLevel, unc[0], unc[1], continueOnException);
      }

      
      /// <summary>Retrieves information about the Server Message Block (SMB) share as defined on the specified host.</summary>
      /// <returns>A <see cref="ShareInfo"/> class, or <c>null</c> on failure or when not available, and <paramref name="continueOnException"/> is <c>true</c>.</returns>
      /// <param name="host">The DNS or NetBIOS name of the specified host.</param>
      /// <param name="share">The name of the Server Message Block (SMB) share.</param>
      /// <param name="continueOnException"><c>true</c> to suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public static ShareInfo GetShareInfo(string host, string share, bool continueOnException)
      {
         return GetShareInfoCore(ShareInfoLevel.Info503, host, share, continueOnException);
      }

      
      /// <summary>Retrieves information about the Server Message Block (SMB) share as defined on the specified host.</summary>
      /// <returns>A <see cref="ShareInfo"/> class, or <c>null</c> on failure or when not available, and <paramref name="continueOnException"/> is <c>true</c>.</returns>
      /// <param name="shareLevel">One of the <see cref="ShareInfoLevel"/> options.</param>
      /// <param name="host">A string that specifies the DNS or NetBIOS name of the specified <paramref name="host"/>.</param>
      /// <param name="share">A string that specifies the name of the Server Message Block (SMB) share.</param>
      /// <param name="continueOnException"><c>true</c> to suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public static ShareInfo GetShareInfo(ShareInfoLevel shareLevel, string host, string share, bool continueOnException)
      {
         return GetShareInfoCore(shareLevel, host, share, continueOnException);
      }




      /// <summary>Gets the <see cref="ShareInfo"/> structure of a Server Message Block (SMB) share.</summary>
      /// <returns>A <see cref="ShareInfo"/> class, or <c>null</c> on failure or when not available, and <paramref name="continueOnException"/> is <c>true</c>.</returns>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="shareLevel">One of the <see cref="ShareInfoLevel"/> options.</param>
      /// <param name="host">A string that specifies the DNS or NetBIOS name of the specified <paramref name="host"/>.</param>
      /// <param name="share">A string that specifies the name of the Server Message Block (SMB) share.</param>
      /// <param name="continueOnException"><c>true</c> to suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      internal static ShareInfo GetShareInfoCore(ShareInfoLevel shareLevel, string host, string share, bool continueOnException)
      {
         if (Utils.IsNullOrWhiteSpace(share))
            return null;


         // When host == null, the local computer is used.
         // However, the resulting OpenResourceInfo.Host property will be empty.
         // So, explicitly state Environment.MachineName to prevent this.
         // Furthermore, the UNC prefix: \\ is not required and always removed.
         var stripUnc = Utils.IsNullOrWhiteSpace(host) ? Environment.MachineName : Path.GetRegularPathCore(host, GetFullPathOptions.CheckInvalidPathChars, false).Replace(Path.UncPrefix, string.Empty);

         var fallback = false;


         startNetShareGetInfo:

         SafeGlobalMemoryBufferHandle safeBuffer;

         uint structureLevel = Convert.ToUInt16(shareLevel, CultureInfo.InvariantCulture);
         var lastError = NativeMethods.NetShareGetInfo(stripUnc, share, structureLevel, out safeBuffer);

         using (safeBuffer)
         {
            switch (lastError)
            {
               case Win32Errors.NERR_Success:
                  switch (shareLevel)
                  {
                     case ShareInfoLevel.Info1005:
                        return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure<NativeMethods.SHARE_INFO_1005>(0))
                        {
                           NetFullPath = Path.CombineCore(false, Path.UncPrefix + stripUnc, share)
                        };


                     case ShareInfoLevel.Info503:
                        return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure<NativeMethods.SHARE_INFO_503>(0));


                     case ShareInfoLevel.Info2:
                        return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure<NativeMethods.SHARE_INFO_2>(0));


                     case ShareInfoLevel.Info1:
                        return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure<NativeMethods.SHARE_INFO_1>(0));
                  }

                  break;


               // Observed when SHARE_INFO_503 is requested, but not supported/possible.
               // Fall back on SHARE_INFO_2 structure and try again.
               case Win32Errors.RPC_X_BAD_STUB_DATA:


               case Win32Errors.ERROR_ACCESS_DENIED:
                  if (!fallback && shareLevel != ShareInfoLevel.Info2)
                  {
                     shareLevel = ShareInfoLevel.Info2;
                     fallback = true;
                     goto startNetShareGetInfo;
                  }

                  break;


               default:
                  if (!continueOnException)
                     throw new NetworkInformationException((int) lastError);

                  break;
            }


            return null;
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File CopyMove/File.Move.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      #region .NET

      /// <summary>Moves a specified file to a new location, providing the option to specify a new file name.
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// </summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      [SecurityCritical]
      public static void Move(string sourcePath, string destinationPath)
      {
         CopyMoveCore(false, new CopyMoveArguments
         {
            MoveOptions = MoveOptions.CopyAllowed

         }, false, false, sourcePath, destinationPath, null);
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            MoveOptions = MoveOptions.CopyAllowed,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// </summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, int retry, int retryTimeout)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            MoveOptions = MoveOptions.CopyAllowed

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, int retry, int retryTimeout, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            MoveOptions = MoveOptions.CopyAllowed,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            MoveOptions = MoveOptions.CopyAllowed,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            MoveOptions = MoveOptions.CopyAllowed,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            MoveOptions = MoveOptions.CopyAllowed,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            MoveOptions = MoveOptions.CopyAllowed,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }




      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the file is to be moved. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            MoveOptions = moveOptions

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the file is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            MoveOptions = moveOptions,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the file is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            MoveOptions = moveOptions

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the file is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            MoveOptions = moveOptions,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the file is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            MoveOptions = moveOptions,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the file is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            MoveOptions = moveOptions,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the file is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            MoveOptions = moveOptions,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns>
      /// <remarks>
      ///   <para>This method works across disk volumes.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an <see cref="IOException"/>.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The name of the file to move.</param>
      /// <param name="destinationPath">The new path for the file.</param>
      /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the file is to be moved. This parameter can be <c>null</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been moved. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            MoveOptions = moveOptions,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CopyMoveDirectoryCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Collections.Generic;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      [SecurityCritical]
      internal static void CopyMoveDirectoryCore(bool retry, CopyMoveArguments cma, CopyMoveResult copyMoveResult)
      {
         var dirs = new Queue<string>(NativeMethods.DefaultFileBufferSize);

         dirs.Enqueue(cma.SourcePathLp);


         while (dirs.Count > 0)
         {
            var srcLp = dirs.Dequeue();

            // TODO 2018-01-09: Not 100% yet with local + UNC paths.
            var dstLp = srcLp.ReplaceIgnoreCase(cma.SourcePathLp, cma.DestinationPathLp);
            

            // Traverse the source folder, processing files and folders.
            // No recursion is applied; a Queue is used instead.

            foreach (var fseiSource in EnumerateFileSystemEntryInfosCore<FileSystemEntryInfo>(null, cma.Transaction, srcLp, Path.WildcardStarMatchAll, null, null, cma.DirectoryEnumerationFilters, PathFormat.LongFullPath))
            {
               var fseiSourcePath = fseiSource.LongFullPath;

               var fseiDestinationPath = Path.CombineCore(false, dstLp, fseiSource.FileName);

               if (fseiSource.IsDirectory)
               {
                  CreateDirectoryCore(true, cma.Transaction, fseiDestinationPath, null, null, false, PathFormat.LongFullPath);

                  copyMoveResult.TotalFolders++;

                  dirs.Enqueue(fseiSourcePath);
               }

               else
               {
                  // File count is done in File.CopyMoveCore method.

                  File.CopyMoveCore(retry, cma, true, false, fseiSourcePath, fseiDestinationPath, copyMoveResult);

                  if (copyMoveResult.IsCanceled)
                  {
                     // Break while loop.
                     dirs.Clear();

                     // Break foreach loop.
                     break;
                  }
                  

                  if (copyMoveResult.ErrorCode == Win32Errors.NO_ERROR)
                  {
                     copyMoveResult.TotalBytes += fseiSource.FileSize;

                     if (cma.EmulateMove)
                        File.DeleteFileCore(cma.Transaction, fseiSourcePath, true, fseiSource.Attributes, PathFormat.LongFullPath);
                  }
               }
            }
         }


         if (!copyMoveResult.IsCanceled && copyMoveResult.ErrorCode == Win32Errors.NO_ERROR)
         {
            if (cma.CopyTimestamps)
               CopyFolderTimestamps(cma);

            if (cma.EmulateMove)
               DeleteDirectoryCore(cma.Transaction, null, cma.SourcePathLp, true, true, true, PathFormat.LongFullPath);
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path.GetFullPath.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      #region .NET

      /// <summary>Returns the absolute path for the specified path string.</summary>
      /// <returns>The fully qualified location of path, such as "C:\MyFile.txt".</returns>
      /// <remarks>
      /// <para>GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file.</para>
      /// <para>It also calculates the address of the file name portion of the full path and file name.</para>
      /// <para>&#160;</para>
      /// <para>This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume.</para>
      /// <para>The .NET Framework does not support direct access to physical disks through paths that are device names, such as <c>\\.\PhysicalDrive0</c>.</para>
      /// <para>&#160;</para>
      /// <para>MSDN: Multithreaded applications and shared library code should not use the GetFullPathName function and</para>
      /// <para>should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,</para>
      /// <para>therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.</para>
      /// <para>This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread,</para>
      /// <para>for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
      /// <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
      /// </remarks>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <param name="path">The file or directory for which to obtain absolute path information.</param>
      [SecurityCritical]
      public static string GetFullPath(string path)
      {
         return GetFullPathCore(null, true, path, GetFullPathOptions.None);
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Returns the absolute path for the specified path string.</summary>
      /// <returns>The fully qualified location of path, such as "C:\MyFile.txt".</returns>
      /// <remarks>
      /// <para>GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file.</para>
      /// <para>It also calculates the address of the file name portion of the full path and file name.</para>
      /// <para>&#160;</para>
      /// <para>This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume.</para>
      /// <para>The .NET Framework does not support direct access to physical disks through paths that are device names, such as <c>\\.\PhysicalDrive0</c>.</para>
      /// <para>&#160;</para>
      /// <para>MSDN: Multithreaded applications and shared library code should not use the GetFullPathName function and</para>
      /// <para>should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,</para>
      /// <para>therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.</para>
      /// <para>This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread,</para>
      /// <para>for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
      /// <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
      /// </remarks>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <param name="path">The file or directory for which to obtain absolute path information.</param>
      /// <param name="options">Options for controlling the full path retrieval.</param>
      [SecurityCritical]
      public static string GetFullPath(string path, GetFullPathOptions options)
      {
         return GetFullPathCore(null, true, path, options);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingFile.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class FileInfoTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void FileInfo_InitializeInstance_ExistingFile_LocalAndNetwork_Success()
      {
         FileInfo_InitializeInstance_ExistingFile(false);
         FileInfo_InitializeInstance_ExistingFile(true);
      }


      private void FileInfo_InitializeInstance_ExistingFile(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var file = tempRoot.CreateFile();

            Console.WriteLine("Input File Path: [{0}]", file);

            var alphaFSFileInfo = new Alphaleonis.Win32.Filesystem.FileInfo(file.FullName);

            using (file.Create())
               CompareFileInfos(file, alphaFSFileInfo, true);
         }

         Console.WriteLine();
      }


      private void CompareFileInfos(System.IO.FileInfo expected, Alphaleonis.Win32.Filesystem.FileInfo actual, bool exists)
      {
         if (expected == null || actual == null)
            Assert.AreEqual(expected, actual, "The two FileInfo instances are not the same, but are expected to be.");

         UnitTestConstants.Dump(expected);
         Console.WriteLine();
         UnitTestConstants.Dump(actual);


         if (exists)
            Assert.IsTrue(expected.Exists && actual.Exists, "The file does not exist, but is expected to.");
         else
            Assert.IsFalse(expected.Exists && actual.Exists, "The file exists, but is expected not to.");


         var cnt = -1;
         while (cnt != 15)
         {
            cnt++;
            // Compare values of both instances.
            switch (cnt)
            {
               case 0:
                  Assert.AreEqual(expected.Attributes, actual.Attributes, "The property Attributes is not the same, but is expected to.");
                  break;
               case 1:
                  Assert.AreEqual(expected.CreationTime, actual.CreationTime, "The property CreationTime is not the same, but is expected to.");
                  break;
               case 2:
                  Assert.AreEqual(expected.CreationTimeUtc, actual.CreationTimeUtc, "The property CreationTimeUtc is not the same, but is expected to.");
                  break;

               // Need .ToString() here since the object types are obviously not the same.
               case 3:
                  Assert.AreEqual(expected.Directory.ToString(), actual.Directory.ToString(), "The property Directory is not the same, but is expected to.");
                  break;

               case 4:
                  Assert.AreEqual(expected.DirectoryName, actual.DirectoryName, "The property DirectoryName is not the same, but is expected to.");
                  break;
               case 5:
                  Assert.AreEqual(expected.Exists, actual.Exists, "The property Exists is not the same, but is expected to.");
                  break;
               case 6:
                  Assert.AreEqual(expected.Extension, actual.Extension, "The property Extension is not the same, but is expected to.");
                  break;
               case 7:
                  Assert.AreEqual(expected.FullName, actual.FullName, "The property FullName is not the same, but is expected to.");
                  break;
               case 8:
                  Assert.AreEqual(expected.IsReadOnly, actual.IsReadOnly, "The property IsReadOnly is not the same, but is expected to.");
                  break;
               case 9:
                  Assert.AreEqual(expected.LastAccessTime, actual.LastAccessTime, "The property LastAccessTime is not the same, but is expected to.");
                  break;
               case 10:
                  Assert.AreEqual(expected.LastAccessTimeUtc, actual.LastAccessTimeUtc, "The property LastAccessTimeUtc is not the same, but is expected to.");
                  break;
               case 11:
                  Assert.AreEqual(expected.LastWriteTime, actual.LastWriteTime, "The property LastWriteTime is not the same, but is expected to.");
                  break;
               case 12:
                  Assert.AreEqual(expected.LastWriteTimeUtc, actual.LastWriteTimeUtc, "The property LastWriteTimeUtc is not the same, but is expected to.");
                  break;
               case 13:
                  if (exists)
                     Assert.AreEqual(expected.Length, actual.Length, "The property Length is not the same, but is expected to.");
                  break;
               case 14:
                  Assert.AreEqual(expected.Name, actual.Name, "The property Name is not the same, but is expected to.");
                  break;
            }
         }
      }
   }
}


<|start_filename|>docs/theme/alphaleonis/styles/main.css<|end_filename|>
svg#logo:hover path#bg {
  fill: #61ace6; 
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.SetAccessControlCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
using Alphaleonis.Win32.Security;
using Microsoft.Win32.SafeHandles;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>[AlphaFS] Applies access control list (ACL) entries described by a <see cref="FileSecurity"/>/<see cref="DirectorySecurity"/> object to the specified file or directory.</summary>
      /// <remarks>Use either <paramref name="path"/> or <paramref name="handle"/>, not both.</remarks>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <param name="path">A file or directory to add or remove access control list (ACL) entries from. This parameter This parameter may be <c>null</c>.</param>
      /// <param name="handle">A <see cref="SafeFileHandle"/> to add or remove access control list (ACL) entries from. This parameter This parameter may be <c>null</c>.</param>
      /// <param name="objectSecurity">A <see cref="FileSecurity"/>/<see cref="DirectorySecurity"/> object that describes an ACL entry to apply to the file or directory described by the <paramref name="path"/>/<paramref name="handle"/> parameter.</param>
      /// <param name="includeSections">One or more of the <see cref="AccessControlSections"/> values that specifies the type of access control list (ACL) information to set.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
      [SecurityCritical]
      internal static void SetAccessControlCore(string path, SafeFileHandle handle, ObjectSecurity objectSecurity, AccessControlSections includeSections, PathFormat pathFormat)
      {
         if (pathFormat == PathFormat.RelativePath)
            Path.CheckSupportedPathFormat(path, true, true);

         if (objectSecurity == null)
            throw new ArgumentNullException("objectSecurity");


         var managedDescriptor = objectSecurity.GetSecurityDescriptorBinaryForm();

         using (var safeBuffer = new SafeGlobalMemoryBufferHandle(managedDescriptor.Length))
         {
            var pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars);

            safeBuffer.CopyFrom(managedDescriptor, 0, managedDescriptor.Length);

            SECURITY_DESCRIPTOR_CONTROL control;
            uint revision;


            var success = Security.NativeMethods.GetSecurityDescriptorControl(safeBuffer, out control, out revision);

            var lastError = Marshal.GetLastWin32Error();
            if (!success)
               NativeError.ThrowException(lastError, pathLp);


            PrivilegeEnabler privilegeEnabler = null;

            try
            {
               var securityInfo = SECURITY_INFORMATION.None;
               var pDacl = IntPtr.Zero;

               if ((includeSections & AccessControlSections.Access) != 0)
               {
                  bool daclDefaulted, daclPresent;


                  success = Security.NativeMethods.GetSecurityDescriptorDacl(safeBuffer, out daclPresent, out pDacl, out daclDefaulted);

                  lastError = Marshal.GetLastWin32Error();
                  if (!success)
                     NativeError.ThrowException(lastError, pathLp);


                  if (daclPresent)
                  {
                     securityInfo |= SECURITY_INFORMATION.DACL_SECURITY_INFORMATION;
                     securityInfo |= (control & SECURITY_DESCRIPTOR_CONTROL.SE_DACL_PROTECTED) != 0 ? SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION : SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION;
                  }
               }


               var pSacl = IntPtr.Zero;

               if ((includeSections & AccessControlSections.Audit) != 0)
               {
                  bool saclDefaulted, saclPresent;


                  success = Security.NativeMethods.GetSecurityDescriptorSacl(safeBuffer, out saclPresent, out pSacl, out saclDefaulted);

                  lastError = Marshal.GetLastWin32Error();
                  if (!success)
                     NativeError.ThrowException(lastError, pathLp);
                  
                  
                  if (saclPresent)
                  {
                     securityInfo |= SECURITY_INFORMATION.SACL_SECURITY_INFORMATION;
                     securityInfo |= (control & SECURITY_DESCRIPTOR_CONTROL.SE_SACL_PROTECTED) != 0 ? SECURITY_INFORMATION.PROTECTED_SACL_SECURITY_INFORMATION : SECURITY_INFORMATION.UNPROTECTED_SACL_SECURITY_INFORMATION;

                     privilegeEnabler = new PrivilegeEnabler(Privilege.Security);
                  }
               }


               var pOwner = IntPtr.Zero;

               if ((includeSections & AccessControlSections.Owner) != 0)
               {
                  bool ownerDefaulted;


                  success = Security.NativeMethods.GetSecurityDescriptorOwner(safeBuffer, out pOwner, out ownerDefaulted);

                  lastError = Marshal.GetLastWin32Error();
                  if (!success)
                     NativeError.ThrowException(lastError, pathLp);


                  if (pOwner != IntPtr.Zero)
                     securityInfo |= SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION;
               }


               var pGroup = IntPtr.Zero;

               if ((includeSections & AccessControlSections.Group) != 0)
               {
                  bool groupDefaulted;


                  success = Security.NativeMethods.GetSecurityDescriptorGroup(safeBuffer, out pGroup, out groupDefaulted);

                  lastError = Marshal.GetLastWin32Error();
                  if (!success)
                     NativeError.ThrowException(lastError, pathLp);


                  if (pGroup != IntPtr.Zero)
                     securityInfo |= SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION;
               }




               if (!Utils.IsNullOrWhiteSpace(pathLp))
               {
                  // SetNamedSecurityInfo()
                  // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

                  lastError = (int) Security.NativeMethods.SetNamedSecurityInfo(pathLp, SE_OBJECT_TYPE.SE_FILE_OBJECT, securityInfo, pOwner, pGroup, pDacl, pSacl);

                  if (lastError != Win32Errors.ERROR_SUCCESS)
                     NativeError.ThrowException(lastError, pathLp);
               }

               else
               {
                  if (NativeMethods.IsValidHandle(handle))
                  {
                     lastError = (int) Security.NativeMethods.SetSecurityInfo(handle, SE_OBJECT_TYPE.SE_FILE_OBJECT, securityInfo, pOwner, pGroup, pDacl, pSacl);

                     if (lastError != Win32Errors.ERROR_SUCCESS)
                        NativeError.ThrowException(lastError);
                  }
               }
            }
            finally
            {
               if (null != privilegeEnabler)
                  privilegeEnabler.Dispose();
            }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Security/Native Methods/NativeMethods.LocalFree.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Security
{
   internal static partial class NativeMethods
   {
      /// <summary>Frees the specified local memory object and invalidates its handle.</summary>
      /// <returns>
      /// If the function succeeds, the return value is <c>null</c>.
      /// If the function fails, the return value is equal to a handle to the local memory object. To get extended error information, call GetLastError.
      /// </returns>
      /// <remarks>SetLastError is set to <c>false</c>.</remarks>
      /// <remarks>
      /// Note  The local functions have greater overhead and provide fewer features than other memory management functions.
      /// New applications should use the heap functions unless documentation states that a local function should be used.
      /// For more information, see Global and Local Functions.
      /// </remarks>
      /// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      internal static extern IntPtr LocalFree(IntPtr hMem);
   }
}

<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_FileToMappedDriveLetter.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class MoveTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_Move_FileToMappedDriveLetter_LocalAndNetwork_Success()
      {
         // Do not pass isNetwork, as to always use UnitTestConstants.TempPath

         using (var tempRoot = new TemporaryDirectory())
         {
            var srcFileName = "Src file.log";
            var dstFileName = "Dst file.log";

            var srcFile = System.IO.Path.Combine(tempRoot.Directory.FullName, srcFileName);


            var drive = Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter() + @":\";

            var share = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempRoot.CreateDirectory().FullName);

            var dstFile = System.IO.Path.Combine(drive, dstFileName);
            

            try
            {
               Alphaleonis.Win32.Network.Host.ConnectDrive(drive, share);

               Console.WriteLine("Mapped drive [{0}] to [{1}]\n", drive, share);


               System.IO.File.AppendAllText(srcFile, new string('*', new Random().Next(1, 1024)));

               var srcFileSize = new System.IO.FileInfo(srcFile).Length;

               const Alphaleonis.Win32.Filesystem.MoveOptions options = Alphaleonis.Win32.Filesystem.MoveOptions.CopyAllowed | Alphaleonis.Win32.Filesystem.MoveOptions.WriteThrough | Alphaleonis.Win32.Filesystem.MoveOptions.ReplaceExisting;

               Console.WriteLine("Src File Path: [{0}]", srcFile);
               Console.WriteLine("Dst File Path: [{0}]", dstFile);


               var cmr = Alphaleonis.Win32.Filesystem.Directory.Move(srcFile, dstFile, options);

               UnitTestConstants.Dump(cmr);


               Assert.IsFalse(System.IO.Directory.Exists(dstFile));

               Assert.IsTrue(System.IO.File.Exists(dstFile));

               Assert.AreEqual(srcFileSize, new System.IO.FileInfo(dstFile).Length);


               Assert.IsTrue(cmr.IsCopy);
               Assert.IsTrue(cmr.IsEmulatedMove);

               Assert.IsTrue(cmr.IsFile);
               Assert.IsFalse(cmr.IsDirectory);

               Assert.IsFalse(cmr.IsCanceled);
               Assert.AreEqual(0, cmr.TotalFolders);
               Assert.AreEqual(1, cmr.TotalFiles);
            }
            finally
            {
               Alphaleonis.Win32.Network.Host.DisconnectDrive(drive);
            }
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Methods/NativeMethods.EncryptedFileRaw.cs<|end_filename|>
﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   internal partial class NativeMethods
   {
      /// <summary>Opens an encrypted file in order to backup (export) or restore (import) the file.</summary>
      /// <returns>If the function succeeds, it returns ERROR_SUCCESS.</returns>
      /// <returns>If the function fails, it returns a nonzero error code defined in WinError.h. You can use FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic text description of the error.</returns>
      /// <remarks>Minimum supported client: Windows XP Professional [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
      /// <param name="lpFileName">The name of the file to be opened.</param>
      /// <param name="ulFlags">The operation to be performed.</param>
      /// <param name="pvContext">[out] The address of a context block that must be presented in subsequent calls to
      /// ReadEncryptedFileRaw, WriteEncryptedFileRaw, or CloseEncryptedFileRaw.</param>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode, EntryPoint = "OpenEncryptedFileRawW"), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint OpenEncryptedFileRaw([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, EncryptedFileRawMode ulFlags, out SafeEncryptedFileRawHandle pvContext);


      /// <summary>Closes an encrypted file after a backup or restore operation, and frees associated system resources.</summary>
      /// <remarks>Minimum supported client: Windows XP Professional [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
      /// <param name="pvContext">A pointer to a system-defined context block. The OpenEncryptedFileRaw function returns the context block.</param>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      internal static extern void CloseEncryptedFileRaw(IntPtr pvContext);


      /// <summary>Backs up (export) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is intended to implement backup and restore functionality, while maintaining files in their encrypted state.</summary>
      /// <returns>If the function succeeds, it returns ERROR_SUCCESS.</returns>
      /// <returns>If the function fails, it returns a nonzero error code defined in WinError.h. You can use FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic text description of the error.</returns>
      /// <remarks>Minimum supported client: Windows XP Professional [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule"), SuppressUnmanagedCodeSecurity]
      [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint ReadEncryptedFileRaw([MarshalAs(UnmanagedType.FunctionPtr)] EncryptedFileRawExportCallback pfExportCallback, IntPtr pvCallbackContext, SafeEncryptedFileRawHandle pvContext);


      /// <summary>Restores (import) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is intended to implement backup and restore functionality, while maintaining files in their encrypted state.</summary>
      /// <returns>If the function succeeds, it returns ERROR_SUCCESS.</returns>
      /// <returns>If the function fails, it returns a nonzero error code defined in WinError.h. You can use FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic text description of the error.</returns>
      /// <remarks>Minimum supported client: Windows XP Professional [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint WriteEncryptedFileRaw([MarshalAs(UnmanagedType.FunctionPtr)] EncryptedFileRawImportCallback pfExportCallback, IntPtr pvCallbackContext, SafeEncryptedFileRawHandle pvContext);


      [SuppressUnmanagedCodeSecurity]
      internal delegate int EncryptedFileRawExportCallback(IntPtr pbData, IntPtr pvCallbackContext, uint ulLength);

      [SuppressUnmanagedCodeSecurity]
      internal delegate int EncryptedFileRawImportCallback(IntPtr pbData, IntPtr pvCallbackContext, ref uint ulLength);
   }
}


<|start_filename|>src/AlphaFS/Security/SecurityAttributes.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Security
{
   internal static partial class NativeMethods
   {
      /// <summary>Class used to represent the SECURITY_ATTRIBUTES native Win32 structure.
      /// The SECURITY_ATTRIBUTES structure contains the security descriptor for an object and specifies whether the handle retrieved by specifying this structure is inheritable.
      /// This structure provides security settings for objects created by various functions, such as CreateFile, CreatePipe, CreateProcess, RegCreateKeyEx, or RegSaveKeyEx.
      /// </summary>
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      internal sealed class SecurityAttributes : IDisposable
      {
         // Removing the StructLayout attribute results in errors.


         [MarshalAs(UnmanagedType.U4)]
         private int _length;

         private readonly SafeGlobalMemoryBufferHandle _securityDescriptor;


         public SecurityAttributes(ObjectSecurity securityDescriptor)
         {
            var safeBuffer = ToUnmanagedSecurityAttributes(securityDescriptor);

            _length = safeBuffer.Capacity;
            _securityDescriptor = safeBuffer;
         }


         public SecurityAttributes(ObjectSecurity securityDescriptor, bool inheritHandle) : this(securityDescriptor)
         {
            InheritHandle = inheritHandle;
         }


         public bool InheritHandle { get; set; }


         /// <summary>Marshals an ObjectSecurity instance to unmanaged memory.</summary>
         /// <returns>A safe handle containing the marshalled security descriptor.</returns>
         /// <param name="securityDescriptor">The security descriptor.</param>
         [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
         private static SafeGlobalMemoryBufferHandle ToUnmanagedSecurityAttributes(ObjectSecurity securityDescriptor)
         {
            if (null == securityDescriptor)
               return new SafeGlobalMemoryBufferHandle();


            var src = securityDescriptor.GetSecurityDescriptorBinaryForm();
            var safeBuffer = new SafeGlobalMemoryBufferHandle(src.Length);

            try
            {
               safeBuffer.CopyFrom(src, 0, src.Length);
               return safeBuffer;
            }
            catch
            {
               safeBuffer.Close();
               throw;
            }
         }


         public void Dispose()
         {
            if (null != _securityDescriptor && !_securityDescriptor.IsClosed)
               _securityDescriptor.Close();
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.DFS.EnumerateDfsLinks.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Net.NetworkInformation;
using System.Security;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>Enumerates the DFS Links from a DFS namespace.</summary>
      /// <returns><see cref="IEnumerable{DfsInfo}"/> of DFS namespaces.</returns>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="dfsName">The Universal Naming Convention (UNC) path of a DFS root or link.</param>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")]
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "dfs")]
      [SecurityCritical]
      public static IEnumerable<DfsInfo> EnumerateDfsLinks(string dfsName)
      {
         if (!Filesystem.NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message);


         if (Utils.IsNullOrWhiteSpace(dfsName))
            throw new ArgumentNullException("dfsName");


         var fd = new FunctionData();

         return EnumerateNetworkObjectCore(fd, (NativeMethods.DFS_INFO_9 structure, SafeGlobalMemoryBufferHandle buffer) => new DfsInfo(structure),

            (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle1) =>
            {
               totalEntries = 0;

               return NativeMethods.NetDfsEnum(dfsName, 9, prefMaxLen, out buffer, out entriesRead, out resumeHandle1);

            }, false);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory.CreateDirectoryTransacted.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Security;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>[AlphaFS] Creates all directories and subdirectories in the specified path unless they already exist.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path)
      {
         return CreateDirectoryCore(false, transaction, path, null, null, false, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates all the directories in the specified path, applying the specified Windows security.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
      {
         return CreateDirectoryCore(false, transaction, path, null, null, false, pathFormat);
      }


      /// <summary>[AlphaFS] Creates all the directories in the specified path, applying the specified Windows security.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, bool compress)
      {
         return CreateDirectoryCore(false, transaction, path, null, null, compress, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates all the directories in the specified path, applying the specified Windows security.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, bool compress, PathFormat pathFormat)
      {
         return CreateDirectoryCore(false, transaction, path, null, null, compress, pathFormat);
      }


      /// <summary>[AlphaFS] Creates all the directories in the specified path, unless the already exist, applying the specified Windows security.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="directorySecurity">The access control to apply to the directory.</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, DirectorySecurity directorySecurity)
      {
         return CreateDirectoryCore(false, transaction, path, null, directorySecurity, false, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates all the directories in the specified path, applying the specified Windows security.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="directorySecurity">The access control to apply to the directory.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, DirectorySecurity directorySecurity, PathFormat pathFormat)
      {
         return CreateDirectoryCore(false, transaction, path, null, directorySecurity, false, pathFormat);
      }


      /// <summary>[AlphaFS] Creates all the directories in the specified path, applying the specified Windows security.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="directorySecurity">The access control to apply to the directory.</param>
      /// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, DirectorySecurity directorySecurity, bool compress)
      {
         return CreateDirectoryCore(false, transaction, path, null, directorySecurity, compress, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates all the directories in the specified path, applying the specified Windows security.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="directorySecurity">The access control to apply to the directory.</param>
      /// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, DirectorySecurity directorySecurity, bool compress, PathFormat pathFormat)
      {
         return CreateDirectoryCore(false, transaction, path, null, directorySecurity, compress, pathFormat);
      }


      /// <summary>[AlphaFS] Creates a new directory, with the attributes of a specified template directory.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="templatePath">The path of the directory to use as a template when creating the new directory.</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath)
      {
         return CreateDirectoryCore(false, transaction, path, templatePath, null, false, PathFormat.RelativePath);
      }

      /// <summary>[AlphaFS] Creates a new directory, with the attributes of a specified template directory.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="templatePath">The path of the directory to use as a template when creating the new directory.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, PathFormat pathFormat)
      {
         return CreateDirectoryCore(false, transaction, path, templatePath, null, false, pathFormat);
      }


      /// <summary>[AlphaFS] Creates a new directory, with the attributes of a specified template directory.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="templatePath">The path of the directory to use as a template when creating the new directory.</param>
      /// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, bool compress)
      {
         return CreateDirectoryCore(false, transaction, path, templatePath, null, compress, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates a new directory, with the attributes of a specified template directory.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="templatePath">The path of the directory to use as a template when creating the new directory.</param>
      /// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, bool compress, PathFormat pathFormat)
      {
         return CreateDirectoryCore(false, transaction, path, templatePath, null, compress, pathFormat);
      }


      /// <summary>[AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="templatePath">The path of the directory to use as a template when creating the new directory.</param>
      /// <param name="directorySecurity">The access control to apply to the directory.</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, DirectorySecurity directorySecurity)
      {
         return CreateDirectoryCore(false, transaction, path, templatePath, directorySecurity, false, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="templatePath">The path of the directory to use as a template when creating the new directory.</param>
      /// <param name="directorySecurity">The access control to apply to the directory.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, DirectorySecurity directorySecurity, PathFormat pathFormat)
      {
         return CreateDirectoryCore(false, transaction, path, templatePath, directorySecurity, false, pathFormat);
      }


      /// <summary>[AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="templatePath">The path of the directory to use as a template when creating the new directory.</param>
      /// <param name="directorySecurity">The access control to apply to the directory.</param>
      /// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, DirectorySecurity directorySecurity, bool compress)
      {
         return CreateDirectoryCore(false, transaction, path, templatePath, directorySecurity, compress, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security.</summary>
      /// <returns>An object that represents the directory at the specified path. This object is returned regardless of whether a directory at the specified path already exists.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="templatePath">The path of the directory to use as a template when creating the new directory.</param>
      /// <param name="directorySecurity">The access control to apply to the directory.</param>
      /// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
      [SecurityCritical]
      public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transaction, string path, string templatePath, DirectorySecurity directorySecurity, bool compress, PathFormat pathFormat)
      {
         return CreateDirectoryCore(false, transaction, path, templatePath, directorySecurity, compress, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.IsLockedCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Determines whether the specified file is in use (locked).</summary>
      /// <returns>Returns <c>true</c> if the specified file is in use (locked); otherwise, <c>false</c></returns>
      /// <exception cref="FileNotFoundException"></exception>
      /// <exception cref="IOException"/>
      /// <exception cref="Exception"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="filePath">The path to the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static bool IsLockedCore(KernelTransaction transaction, string filePath, PathFormat pathFormat)
      {
         try
         {
            // Use FileAccess.Read since FileAccess.ReadWrite always fails when file is read-only.
            using (OpenCore(transaction, filePath, FileMode.Open, FileAccess.Read, FileShare.None, ExtendedFileAttributes.Normal, null, null, pathFormat)) {}
         }
         catch (IOException ex)
         {
            var lastError = Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift;
            if (lastError == Win32Errors.ERROR_SHARING_VIOLATION || lastError == Win32Errors.ERROR_LOCK_VIOLATION)
               return true;

            throw;
         }
         catch (Exception ex)
         {
            NativeError.ThrowException(Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift, filePath);
         }

         return false;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumeMountPoints.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;

namespace AlphaFS.UnitTest
{
   public partial class EnumerationTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Volume_EnumerateVolumeMountPoints_Local_Success()
      {
         UnitTestAssert.IsElevatedProcess();
         UnitTestConstants.PrintUnitTestHeader(false);
         
         var cnt = 0;
         Console.WriteLine("Logical Drives\n");

         // Get Logical Drives from UnitTestConstants.Local Host, .IsReady Drives only.
         foreach (var drive in Alphaleonis.Win32.Filesystem.Directory.GetLogicalDrives(false, true))
         {
            try
            {
               // Logical Drives --> Volumes --> Volume Mount Points.
               var uniqueVolName = Alphaleonis.Win32.Filesystem.Volume.GetUniqueVolumeNameForPath(drive);

               if (!Alphaleonis.Utils.IsNullOrWhiteSpace(uniqueVolName) && !uniqueVolName.Equals(drive, StringComparison.OrdinalIgnoreCase))
               {
                  foreach (var mountPoint in Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumeMountPoints(uniqueVolName).Where(mp => !Alphaleonis.Utils.IsNullOrWhiteSpace(mp)))
                  {
                     string guid = null;
                     try { guid = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(System.IO.Path.Combine(drive, mountPoint)); }
                     catch (Exception ex)
                     {
                        Console.WriteLine("\n\tCaught (UNEXPECTED #1) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
                     }

                     Console.WriteLine("\t#{0:000}\tLogical Drive: [{1}]\tGUID: [{2}]\n\t\tDestination  : [{3}]\n", ++cnt, drive, guid ?? "null", mountPoint);
                  }
               }
            }
            catch (Exception ex)
            {
               Console.WriteLine("\n\tCaught (UNEXPECTED #2) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
         }


         if (cnt == 0)
            UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.CreateSymbolicLinkCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>[AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file or directory as a transacted operation.</summary>
      /// <para>&#160;</para>
      /// <remarks>
      /// <para>Symbolic links can point to a non-existent target.</para>
      /// <para>When creating a symbolic link, the operating system does not check to see if the target exists.</para>
      /// <para>Symbolic links are reparse points.</para>
      /// <para>There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path.</para>
      /// <para>See <see cref="Security.Privilege.CreateSymbolicLink"/> to run this method in an elevated state.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="symlinkFileName">The name of the target for the symbolic link to be created.</param>
      /// <param name="targetFileName">The symbolic link to be created.</param>
      /// <param name="targetType">Indicates whether the link target, <paramref name="targetFileName"/>, is a file or directory.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void CreateSymbolicLinkCore(KernelTransaction transaction, string symlinkFileName, string targetFileName, SymbolicLinkTarget targetType, PathFormat pathFormat)
      {
         if (!NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message);


         if (pathFormat != PathFormat.LongFullPath)
         {
            const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck;

            symlinkFileName = Path.GetExtendedLengthPathCore(transaction, symlinkFileName, pathFormat, options);
            targetFileName = Path.GetExtendedLengthPathCore(transaction, targetFileName, pathFormat, options);
         }


         // Don't use long path notation, as it will be empty upon creation.
         targetFileName = Path.GetRegularPathCore(targetFileName, GetFullPathOptions.None, false);


         if (targetType == SymbolicLinkTarget.Directory)
         {
            ThrowIOExceptionIfFsoExist(transaction, false, targetFileName, pathFormat);
            ThrowIOExceptionIfFsoExist(transaction, false, symlinkFileName, pathFormat);
         }

         else
         {
            ThrowIOExceptionIfFsoExist(transaction, true, targetFileName, pathFormat);
            ThrowIOExceptionIfFsoExist(transaction, true, symlinkFileName, pathFormat);
         }


         var success = null == transaction

            // CreateSymbolicLink() / CreateSymbolicLinkTransacted()
            // 2017-05-30: CreateSymbolicLink() MSDN confirms LongPath usage: Starting with Windows 10, version 1607
            // 2015-07-17: This function does not support long paths.
            // 2014-02-14: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
            
            ? NativeMethods.CreateSymbolicLink(symlinkFileName, targetFileName, targetType)
            : NativeMethods.CreateSymbolicLinkTransacted(symlinkFileName, targetFileName, targetType, transaction.SafeHandle);


         var lastError = (uint) Marshal.GetLastWin32Error();
         if (!success)
            NativeError.ThrowException(lastError, targetFileName, symlinkFileName);
      }
   }
}


<|start_filename|>src/AlphaFS/Security/Native Other/TOKEN_INFORMATION_CLASS.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

namespace Alphaleonis.Win32.Security
{
   internal static partial class NativeMethods
   {
      /// <summary>The TOKEN_INFORMATION_CLASS enumeration contains values that specify the type of information being assigned to or retrieved from an access token.
      /// <para>The GetTokenInformation function uses these values to indicate the type of token information to retrieve.</para>
      /// <para>The SetTokenInformation function uses these values to set the token information.</para>
      /// </summary>
      /// <remarks>
      /// <para>Minimum supported client: Windows XP [desktop apps only]</para>
      /// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
      /// </remarks>
      internal enum TOKEN_INFORMATION_CLASS
      {
         ///// <summary>The buffer receives a TOKEN_USER structure that contains the user account of the token.</summary>
         //TokenUser = 1,

         ///// <summary>The buffer receives a TOKEN_GROUPS structure that contains the group accounts associated with the token.</summary>
         //TokenGroups = 2,

         ///// <summary>The buffer receives a TOKEN_PRIVILEGES structure that contains the privileges of the token.</summary>
         //TokenPrivileges = 3,

         ///// <summary>The buffer receives a TOKEN_OWNER structure that contains the default owner security identifier (SID) for newly created objects.</summary>
         //TokenOwner = 4,

         ///// <summary>The buffer receives a TOKEN_PRIMARY_GROUP structure that contains the default primary group SID for newly created objects.</summary>
         //TokenPrimaryGroup = 5,

         ///// <summary>The buffer receives a TOKEN_DEFAULT_DACL structure that contains the default DACL for newly created objects.</summary>
         //TokenDefaultDacl = 6,

         ///// <summary>The buffer receives a TOKEN_SOURCE structure that contains the source of the token. TOKEN_QUERY_SOURCE access is needed to retrieve this information.</summary>
         //TokenSource = 7,

         ///// <summary>The buffer receives a TOKEN_TYPE value that indicates whether the token is a primary or impersonation token.</summary>
         //TokenType = 8,

         ///// <summary>The buffer receives a SECURITY_IMPERSONATION_LEVEL value that indicates the impersonation level of the token. If the access token is not an impersonation token, the function fails.</summary>
         //TokenImpersonationLevel = 9,

         ///// <summary>The buffer receives a TOKEN_STATISTICS structure that contains various token statistics.</summary>
         //TokenStatistics = 10,

         ///// <summary>The buffer receives a TOKEN_GROUPS structure that contains the list of restricting SIDs in a restricted token.</summary>
         //TokenRestrictedSids = 11,

         ///// <summary>The buffer receives a DWORD value that indicates the Terminal Services session identifier that is associated with the token.</summary>
         //TokenSessionId = 12,

         ///// <summary>The buffer receives a TOKEN_GROUPS_AND_PRIVILEGES structure that contains the user SID, the group accounts, the restricted SIDs, and the authentication ID associated with the token.</summary>
         //TokenGroupsAndPrivileges = 13,

         ///// <summary>Reserved.</summary>
         //TokenSessionReference = 14,

         ///// <summary>The buffer receives a DWORD value that is nonzero if the token includes the SANDBOX_INERT flag.</summary>
         //TokenSandBoxInert = 15,

         ///// <summary>Reserved.</summary>
         //TokenAuditPolicy = 16,

         ///// <summary>The buffer receives a TOKEN_ORIGIN value.</summary>
         //TokenOrigin = 17,

         /// <summary>The buffer receives a TOKEN_ELEVATION_TYPE value that specifies the elevation level of the token.</summary>
         TokenElevationType = 18,

         ///// <summary>The buffer receives a TOKEN_LINKED_TOKEN structure that contains a handle to another token that is linked to this token.</summary>
         //TokenLinkedToken = 19,

         ///// <summary>The buffer receives a TOKEN_ELEVATION structure that specifies whether the token is elevated.</summary>
         //TokenElevation = 20,

         ///// <summary>The buffer receives a DWORD value that is nonzero if the token has ever been filtered.</summary>
         //TokenHasRestrictions = 21,

         ///// <summary>The buffer receives a TOKEN_ACCESS_INFORMATION structure that specifies security information contained in the token.</summary>
         //TokenAccessInformation = 22,

         ///// <summary>The buffer receives a DWORD value that is nonzero if virtualization is allowed for the token.</summary>
         //TokenVirtualizationAllowed = 23,

         ///// <summary>The buffer receives a DWORD value that is nonzero if virtualization is enabled for the token.</summary>
         //TokenVirtualizationEnabled = 24,

         ///// <summary>The buffer receives a TOKEN_MANDATORY_LABEL structure that specifies the token's integrity level.</summary>
         //TokenIntegrityLevel = 25,

         ///// <summary>The buffer receives a DWORD value that is nonzero if the token has the UIAccess flag set.</summary>
         //TokenUIAccess = 26,

         ///// <summary>The buffer receives a TOKEN_MANDATORY_POLICY structure that specifies the token's mandatory integrity policy.</summary>
         //TokenMandatoryPolicy = 27,

         ///// <summary>The buffer receives a TOKEN_GROUPS structure that specifies the token's logon SID.</summary>
         //TokenLogonSid = 28,

         ///// <summary>The buffer receives a DWORD value that is nonzero if the token is an app container token.</summary>
         //TokenIsAppContainer = 29,

         ///// <summary>The buffer receives a TOKEN_GROUPS structure that contains the capabilities associated with the token.</summary>
         //TokenCapabilities = 30,

         ///// <summary>The buffer receives a TOKEN_APPCONTAINER_INFORMATION structure that contains the AppContainerSid associated with the token.</summary>
         //TokenAppContainerSid = 31,

         ///// <summary>The buffer receives a DWORD value that includes the app container number for the token. For tokens that are not app container tokens, this value is zero.</summary>
         //TokenAppContainerNumber = 32,

         ///// <summary>The buffer receives a CLAIM_SECURITY_ATTRIBUTES_INFORMATION structure that contains the user claims associated with the token.</summary>
         //TokenUserClaimAttributes = 33,

         ///// <summary>The buffer receives a CLAIM_SECURITY_ATTRIBUTES_INFORMATION structure that contains the device claims associated with the token.</summary>
         //TokenDeviceClaimAttributes = 34,

         ///// <summary>This value is reserved.</summary>
         //TokenRestrictedUserClaimAttributes = 35,

         ///// <summary>This value is reserved.</summary>
         //TokenRestrictedDeviceClaimAttributes = 36,

         ///// <summary>The buffer receives a TOKEN_GROUPS structure that contains the device groups that are associated with the token.</summary>
         //TokenDeviceGroups = 37,

         ///// <summary>The buffer receives a TOKEN_GROUPS structure that contains the restricted device groups that are associated with the token.</summary>
         //TokenRestrictedDeviceGroups = 38,

         ///// <summary>This value is reserved.</summary>
         //TokenSecurityAttributes = 39,

         ///// <summary>This value is reserved.</summary>
         //TokenIsRestricted = 40, 

         ///// <summary>The maximum value for this enumeration.</summary>
         //MaxTokenInfoClass = 41
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory CopyMove/Directory.ValidateMoveAction.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      [SecurityCritical]
      internal static CopyMoveArguments ValidateMoveAction(CopyMoveArguments cma)
      {
         // Determine if a Move action or Copy action-fallback is possible.

         cma.IsCopy = false;
         cma.EmulateMove = false;
         

         // Compare the root part of both paths.

         var equalRootPaths = Path.GetPathRoot(cma.SourcePathLp, false).Equals(Path.GetPathRoot(cma.DestinationPathLp, false), StringComparison.OrdinalIgnoreCase);
         

         // Method Volume.IsSameVolume() returns true when both paths refer to the same volume, even if one of the paths is a UNC path.
         // For example, src = C:\TempSrc and dst = \\localhost\C$\TempDst

         var isSameVolume = equalRootPaths || Volume.IsSameVolume(cma.SourcePathLp, cma.DestinationPathLp);
         
         var isMove = isSameVolume && equalRootPaths;

         if (!isMove)
         {
            // A Move() can be emulated by using Copy() and Delete(), but only if the MoveOptions.CopyAllowed flag is set.

            isMove = File.HasCopyAllowed(cma.MoveOptions);


            // MSDN: .NET3.5+: IOException: An attempt was made to move a directory to a different volume.

            if (!isMove)
               NativeError.ThrowException(Win32Errors.ERROR_NOT_SAME_DEVICE, cma.SourcePathLp, cma.DestinationPathLp);
         }


         // The MoveFileXxx methods fail when:
         // - A directory is being moved;
         // - One of the paths is a UNC path, even though both paths refer to the same volume.
         //   For example, src = C:\TempSrc and dst = \\localhost\C$\TempDst

         if (isMove)
         {
            var srcIsUncPath = Path.IsUncPathCore(cma.SourcePathLp, false, false);
            var dstIsUncPath = Path.IsUncPathCore(cma.DestinationPathLp, false, false);

            isMove = srcIsUncPath == dstIsUncPath;
         }


         isMove = isMove && isSameVolume && equalRootPaths;


         // Emulate Move().
         if (!isMove)
         {
            cma.MoveOptions = null;

            cma.IsCopy = true;
            cma.EmulateMove = true;
            cma.CopyOptions = CopyOptions.None;
         }


         return cma;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Other/WIN32_FIND_DATA.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      /// <summary>Contains information about the file that is found by the FindFirstFile, FindFirstFileEx, or FindNextFile function.</summary>
      /// <remarks>
      /// If a file has a long file name, the complete name appears in the cFileName member, and the 8.3 format truncated version of the name appears
      /// in the cAlternateFileName member. Otherwise, cAlternateFileName is empty. If the FindFirstFileEx function was called with a value of FindExInfoBasic
      /// in the fInfoLevelId parameter, the cAlternateFileName member will always contain a <c>null</c> string value. This remains true for all subsequent calls to the
      /// FindNextFile function. As an alternative method of retrieving the 8.3 format version of a file name, you can use the GetShortPathName function.
      /// For more information about file names, see File Names, Paths, and Namespaces.
      /// </remarks>
      /// <remarks>
      /// Not all file systems can record creation and last access times, and not all file systems record them in the same manner.
      /// For example, on the FAT file system, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds,
      /// and access time has a resolution of 1 day. The NTFS file system delays updates to the last access time for a file by up to 1 hour
      /// after the last access. For more information, see File Times.
      /// </remarks>
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      [Serializable]
      internal struct WIN32_FIND_DATA
      {
         /// <summary>The file attributes of a file.</summary>
         public FileAttributes dwFileAttributes;

         
         /// <summary>A <see cref="FILETIME"/> structure that specifies when a file or directory was created.
         /// If the underlying file system does not support creation time, this member is zero.</summary>
         public FILETIME ftCreationTime;

         
         /// <summary>A <see cref="FILETIME"/> structure.
         /// For a file, the structure specifies when the file was last read from, written to, or for executable files, run.
         /// For a directory, the structure specifies when the directory is created. If the underlying file system does not support last access time, this member is zero.
         /// On the FAT file system, the specified date for both files and directories is correct, but the time of day is always set to midnight.
         /// </summary>
         public FILETIME ftLastAccessTime;

         
         /// <summary>A <see cref="FILETIME"/> structure.
         /// For a file, the structure specifies when the file was last written to, truncated, or overwritten, for example, when WriteFile or SetEndOfFile are used.
         /// The date and time are not updated when file attributes or security descriptors are changed.
         /// For a directory, the structure specifies when the directory is created. If the underlying file system does not support last write time, this member is zero.
         /// </summary>
         public FILETIME ftLastWriteTime;

         
         /// <summary>The high-order DWORD of the file size. This member does not have a meaning for directories.
         /// This value is zero unless the file size is greater than MAXDWORD.
         /// The size of the file is equal to (nFileSizeHigh * (MAXDWORD+1)) + nFileSizeLow.
         /// </summary>
         public uint nFileSizeHigh;

         
         /// <summary>The low-order DWORD of the file size. This member does not have a meaning for directories.</summary>
         public uint nFileSizeLow;

         
         /// <summary>If the dwFileAttributes member includes the FILE_ATTRIBUTE_REPARSE_POINT attribute, this member specifies the reparse point tag.
         /// Otherwise, this value is undefined and should not be used.
         /// </summary>
         public readonly ReparsePointTag dwReserved0;

         
         /// <summary>Reserved for future use.</summary>
         private readonly uint dwReserved1;

         
         /// <summary>The name of the file.</summary>
         [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MaxPath)] public string cFileName;

         
         /// <summary>An alternative name for the file. This name is in the classic 8.3 file name format.</summary>
         [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public readonly string cAlternateFileName;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.GetChangeTimeCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.Win32.SafeHandles;
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Gets the change date and time of the specified file.</summary>
      /// <returns>A <see cref="DateTime"/> structure set to the change date and time for the specified file. This value is expressed in local time.</returns>
      /// <remarks><para>Use either <paramref name="path"/> or <paramref name="safeFileHandle"/>, not both.</para></remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="safeFileHandle">An open handle to the file or directory from which to retrieve information.</param>
      /// <param name="isFolder">Specifies that <paramref name="path"/> is a file or directory.</param>
      /// <param name="path">The file or directory for which to obtain creation date and time information.</param>
      /// <param name="getUtc"><c>true</c> gets the Coordinated Universal Time (UTC), <c>false</c> gets the local time.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposing is controlled.")]
      [SecurityCritical]
      internal static DateTime GetChangeTimeCore(KernelTransaction transaction, SafeFileHandle safeFileHandle, bool isFolder, string path, bool getUtc, PathFormat pathFormat)
      {
         if (!NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message);


         var callerHandle = null != safeFileHandle;
         if (!callerHandle)
         {
            if (pathFormat != PathFormat.LongFullPath && Utils.IsNullOrWhiteSpace(path))
               throw new ArgumentNullException("path");

            var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars);

            safeFileHandle = CreateFileCore(transaction, isFolder, pathLp, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.ReadData, FileShare.ReadWrite, true, false, PathFormat.LongFullPath);
         }


         try
         {
            NativeMethods.IsValidHandle(safeFileHandle);
            
            using (var safeBuffer = new SafeGlobalMemoryBufferHandle(IntPtr.Size + Marshal.SizeOf(typeof(NativeMethods.FILE_BASIC_INFO))))
            {
               NativeMethods.FILE_BASIC_INFO fbi;

               var success = NativeMethods.GetFileInformationByHandleEx_FileBasicInfo(safeFileHandle, NativeMethods.FILE_INFO_BY_HANDLE_CLASS.FILE_BASIC_INFO, out fbi, (uint) safeBuffer.Capacity);
               
               var lastError = Marshal.GetLastWin32Error();
               if (!success)
                  NativeError.ThrowException(lastError, !Utils.IsNullOrWhiteSpace(path) ? path : null);


               safeBuffer.StructureToPtr(fbi, true);
               var changeTime = safeBuffer.PtrToStructure<NativeMethods.FILE_BASIC_INFO>(0).ChangeTime;


               return getUtc ? DateTime.FromFileTimeUtc(changeTime) : DateTime.FromFileTime(changeTime);
            }
         }
         finally
         {
            // Handle is ours, dispose.
            if (!callerHandle && null != safeFileHandle && !safeFileHandle.IsClosed)
               safeFileHandle.Close();
         }
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/UnitTest Utility/TestAccessRules.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Security.AccessControl;

namespace AlphaFS.UnitTest
{
   /// <summary>Containts static variables, used by unit tests.</summary>
   public static partial class UnitTestConstants
   {
      public static void TestAccessRules(ObjectSecurity sysIO, ObjectSecurity alphaFS)
      {
         Console.WriteLine();


         Console.WriteLine("\tSystem.IO .AccessRightType: [{0}]", sysIO.AccessRightType);
         Console.WriteLine("\tAlphaFS   .AccessRightType: [{0}]", alphaFS.AccessRightType);
         Console.WriteLine();
         Assert.AreEqual(sysIO.AccessRightType, alphaFS.AccessRightType);


         Console.WriteLine("\tSystem.IO .AccessRuleType: [{0}]", sysIO.AccessRuleType);
         Console.WriteLine("\tAlphaFS   .AccessRuleType: [{0}]", alphaFS.AccessRuleType);
         Console.WriteLine();
         Assert.AreEqual(sysIO.AccessRuleType, alphaFS.AccessRuleType);


         Console.WriteLine("\tSystem.IO .AuditRuleType: [{0}]", sysIO.AuditRuleType);
         Console.WriteLine("\tAlphaFS   .AuditRuleType: [{0}]", alphaFS.AuditRuleType);
         Console.WriteLine();
         Assert.AreEqual(sysIO.AuditRuleType, alphaFS.AuditRuleType);




         Console.WriteLine("\tSystem.IO .AreAccessRulesProtected: [{0}]", sysIO.AreAccessRulesProtected);
         Console.WriteLine("\tAlphaFS   .AreAccessRulesProtected: [{0}]", alphaFS.AreAccessRulesProtected);
         Console.WriteLine();
         Assert.AreEqual(sysIO.AreAccessRulesProtected, alphaFS.AreAccessRulesProtected);


         Console.WriteLine("\tSystem.IO .AreAuditRulesProtected: [{0}]", sysIO.AreAuditRulesProtected);
         Console.WriteLine("\tAlphaFS   .AreAuditRulesProtected: [{0}]", alphaFS.AreAuditRulesProtected);
         Console.WriteLine();
         Assert.AreEqual(sysIO.AreAuditRulesProtected, alphaFS.AreAuditRulesProtected);


         Console.WriteLine("\tSystem.IO .AreAccessRulesCanonical: [{0}]", sysIO.AreAccessRulesCanonical);
         Console.WriteLine("\tAlphaFS   .AreAccessRulesCanonical: [{0}]", alphaFS.AreAccessRulesCanonical);
         Console.WriteLine();
         Assert.AreEqual(sysIO.AreAccessRulesCanonical, alphaFS.AreAccessRulesCanonical);


         Console.WriteLine("\tSystem.IO .AreAuditRulesCanonical: [{0}]", sysIO.AreAuditRulesCanonical);
         Console.WriteLine("\tAlphaFS   .AreAuditRulesCanonical: [{0}]", alphaFS.AreAuditRulesCanonical);
         Console.WriteLine();
         Assert.AreEqual(sysIO.AreAuditRulesCanonical, alphaFS.AreAuditRulesCanonical);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File.Exists.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Determines whether the specified file exists.</summary>
      /// <remarks>
      ///   <para>MSDN: .NET 3.5+: Trailing spaces are removed from the end of the
      ///   <paramref name="path"/> parameter before checking whether the directory exists.</para>
      ///   <para>The Exists method returns <c>false</c> if any error occurs while trying to
      ///   determine if the specified file exists.</para>
      ///   <para>This can occur in situations that raise exceptions such as passing a file name with
      ///   invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the
      ///   file.</para>
      ///   <para>The Exists method should not be used for path validation,
      ///   this method merely checks if the file specified in path exists.</para>
      ///   <para>Passing an invalid path to Exists returns false.</para>
      ///   <para>Be aware that another process can potentially do something with the file in
      ///   between the time you call the Exists method and perform another operation on the file, such as Delete.</para>
      /// </remarks>
      /// <param name="path">The file to check.</param>
      /// <returns>
      ///   Returns <c>true</c> if the caller has the required permissions and
      ///   <paramref name="path"/> contains the name of an existing file; otherwise,
      ///   <c>false</c>
      /// </returns>
      [SecurityCritical]
      public static bool Exists(string path)
      {
         return ExistsCore(null, false, path, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Determines whether the specified file exists.</summary>
      /// <remarks>
      ///   <para>MSDN: .NET 3.5+: Trailing spaces are removed from the end of the
      ///   <paramref name="path"/> parameter before checking whether the directory exists.</para>
      ///   <para>The Exists method returns <c>false</c> if any error occurs while trying to
      ///   determine if the specified file exists.</para>
      ///   <para>This can occur in situations that raise exceptions such as passing a file name with
      ///   invalid characters or too many characters,</para>
      ///   <para>a failing or missing disk, or if the caller does not have permission to read the
      ///   file.</para>
      ///   <para>The Exists method should not be used for path validation, this method merely checks
      ///   if the file specified in path exists.</para>
      ///   <para>Passing an invalid path to Exists returns false.</para>
      ///   <para>Be aware that another process can potentially do something with the file in
      ///   between the time you call the Exists method and perform another operation on the file, such
      ///   as Delete.</para>
      /// </remarks>
      /// <param name="path">The file to check.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>
      ///   <para>Returns <c>true</c> if the caller has the required permissions and
      ///   <paramref name="path"/> contains the name of an existing file; otherwise,
      ///   <c>false</c></para>
      /// </returns>
      [SecurityCritical]
      public static bool Exists(string path, PathFormat pathFormat)
      {
         return ExistsCore(null, false, path, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.IO;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      public static readonly bool IsAtLeastWindows8 = OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows8);
      public static readonly bool IsAtLeastWindows7 = OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows7);
      public static readonly bool IsAtLeastWindowsVista = OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.WindowsVista);

      /// <summary>The FindFirstFileEx function does not query the short file name, improving overall enumeration speed.
      /// <para>&#160;</para>
      /// <remarks>
      /// <para>The data is returned in a <see cref="WIN32_FIND_DATA"/> structure,</para>
      /// <para>and cAlternateFileName member is always a NULL string.</para>
      /// <para>This value is not supported until Windows Server 2008 R2 and Windows 7.</para>
      /// </remarks>
      /// </summary>
      public static readonly FINDEX_INFO_LEVELS FindexInfoLevel = IsAtLeastWindows7 ? FINDEX_INFO_LEVELS.Basic : FINDEX_INFO_LEVELS.Standard;

      /// <summary>Uses a larger buffer for directory queries, which can increase performance of the find operation.</summary>
      /// <remarks>This value is not supported until Windows Server 2008 R2 and Windows 7.</remarks>
      public static readonly FIND_FIRST_EX_FLAGS UseLargeCache = IsAtLeastWindows7 ? FIND_FIRST_EX_FLAGS.LARGE_FETCH : FIND_FIRST_EX_FLAGS.NONE;

      /// <summary>DefaultFileBufferSize = 4096; Default type buffer size used for reading and writing files.</summary>
      public const int DefaultFileBufferSize = 4096;

      /// <summary>DefaultFileEncoding = Encoding.UTF8; Default type of Encoding used for reading and writing files.</summary>
      public static readonly Encoding DefaultFileEncoding = Encoding.UTF8;

      /// <summary>MaxDirectoryLength = 255</summary>
      internal const int MaxDirectoryLength = 255;

      /// <summary>MaxPath = 260
      /// The specified path, file name, or both exceed the system-defined maximum length.
      /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. 
      /// </summary>
      internal const int MaxPath = 260;

      /// <summary>MaxPathUnicode = 32700</summary>
      internal const int MaxPathUnicode = 32700;


      /// <summary>When an exception is raised, bit shifting is needed to prevent: "System.OverflowException: Arithmetic operation resulted in an overflow."</summary>
      internal const int OverflowExceptionBitShift = 65535;


      /// <summary>Invalid FileAttributes = -1</summary>
      internal const FileAttributes InvalidFileAttributes = (FileAttributes) (-1);




      /// <summary>MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384</summary>
      internal const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384;

      /// <summary>REPARSE_DATA_BUFFER_HEADER_SIZE = 8</summary>
      internal const int REPARSE_DATA_BUFFER_HEADER_SIZE = 8;


      private const int DeviceIoControlMethodBuffered = 0;
      private const int DeviceIoControlFileDeviceFileSystem = 9;

      // <summary>Command to compression state of a file or directory on a volume whose file system supports per-file and per-directory compression.</summary>
      internal const int FSCTL_SET_COMPRESSION = (DeviceIoControlFileDeviceFileSystem << 16) | (16 << 2) | DeviceIoControlMethodBuffered | (int) (FileAccess.Read | FileAccess.Write) << 14;

      // <summary>Command to set the reparse point data block.</summary>
      internal const int FSCTL_SET_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (41 << 2) | DeviceIoControlMethodBuffered | (0 << 14);
      
      /// <summary>Command to delete the reparse point data base.</summary>
      internal const int FSCTL_DELETE_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (43 << 2) | DeviceIoControlMethodBuffered | (0 << 14);

      /// <summary>Command to get the reparse point data block.</summary>
      internal const int FSCTL_GET_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (42 << 2) | DeviceIoControlMethodBuffered | (0 << 14);
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.SetTimestamps.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class TimestampsTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>
      

      [TestMethod]
      public void AlphaFS_File_SetTimestamps_LocalAndNetwork_Success()
      {
         UnitTestAssert.IsElevatedProcess();

         AlphaFS_File_SetTimestamps(false);
         AlphaFS_File_SetTimestamps(true);
      }


      private void AlphaFS_File_SetTimestamps(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var file = tempRoot.CreateFile();

            var symlinkPath = System.IO.Path.Combine(tempRoot.Directory.FullName, tempRoot.RandomString) + "_symlink";

            Console.WriteLine("Input File Path   : [{0}]", file);
            Console.WriteLine("Input SymLink Path: [{0}]", symlinkPath);


            Alphaleonis.Win32.Filesystem.File.CreateSymbolicLink(symlinkPath, file.FullName);


            var creationTime = tempRoot.GetRandomFileDate();
            var lastAccessTime = tempRoot.GetRandomFileDate();
            var lastWriteTime = tempRoot.GetRandomFileDate();


            Alphaleonis.Win32.Filesystem.File.SetTimestamps(file.FullName, creationTime, lastAccessTime, lastWriteTime);


            UnitTestConstants.Dump(file);


            Assert.AreEqual(System.IO.File.GetCreationTime(file.FullName), creationTime);
            Assert.AreEqual(System.IO.File.GetLastAccessTime(file.FullName), lastAccessTime);
            Assert.AreEqual(System.IO.File.GetLastWriteTime(file.FullName), lastWriteTime);


            // SymbolicLink
            Alphaleonis.Win32.Filesystem.File.SetTimestamps(symlinkPath, creationTime.AddDays(1), lastAccessTime.AddDays(1), lastWriteTime.AddDays(1), true, Alphaleonis.Win32.Filesystem.PathFormat.RelativePath);

            Assert.AreEqual(System.IO.File.GetCreationTime(symlinkPath), Alphaleonis.Win32.Filesystem.File.GetCreationTime(symlinkPath));
            Assert.AreEqual(System.IO.File.GetLastAccessTime(symlinkPath), Alphaleonis.Win32.Filesystem.File.GetLastAccessTime(symlinkPath));
            Assert.AreEqual(System.IO.File.GetLastWriteTime(symlinkPath), Alphaleonis.Win32.Filesystem.File.GetLastWriteTime(symlinkPath));


            creationTime = tempRoot.GetRandomFileDate();
            lastAccessTime = tempRoot.GetRandomFileDate();
            lastWriteTime = tempRoot.GetRandomFileDate();


            Alphaleonis.Win32.Filesystem.File.SetTimestampsUtc(file.FullName, creationTime, lastAccessTime, lastWriteTime);


            Assert.AreEqual(System.IO.File.GetCreationTimeUtc(file.FullName), creationTime);
            Assert.AreEqual(System.IO.File.GetLastAccessTimeUtc(file.FullName), lastAccessTime);
            Assert.AreEqual(System.IO.File.GetLastWriteTimeUtc(file.FullName), lastWriteTime);


            // SymbolicLink
            Alphaleonis.Win32.Filesystem.File.SetTimestampsUtc(symlinkPath, creationTime.AddDays(1), lastAccessTime.AddDays(1), lastWriteTime.AddDays(1), true, Alphaleonis.Win32.Filesystem.PathFormat.RelativePath);

            Assert.AreEqual(System.IO.File.GetCreationTimeUtc(symlinkPath), Alphaleonis.Win32.Filesystem.File.GetCreationTimeUtc(symlinkPath));
            Assert.AreEqual(System.IO.File.GetLastAccessTimeUtc(symlinkPath), Alphaleonis.Win32.Filesystem.File.GetLastAccessTimeUtc(symlinkPath));
            Assert.AreEqual(System.IO.File.GetLastWriteTimeUtc(symlinkPath), Alphaleonis.Win32.Filesystem.File.GetLastWriteTimeUtc(symlinkPath));
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/FileSystemInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Provides the base class for both <see cref="FileInfo"/> and <see cref="DirectoryInfo"/> objects.</summary>
   [Serializable]
   [ComVisible(true)]
   public abstract class FileSystemInfo : MarshalByRefObject, IEquatable<FileSystemInfo>
   {
      #region Fields

      #region .NET

      /// <summary>Represents the fully qualified path of the file or directory.</summary>
      /// <remarks>
      ///   <para>Classes derived from <see cref="FileSystemInfo"/> can use the FullPath field</para>
      ///   <para>to determine the full path of the object being manipulated.</para>
      /// </remarks>
      [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
      protected string FullPath;

      /// <summary>The path originally specified by the user, whether relative or absolute.</summary>
      [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
      protected string OriginalPath;

      #endregion // .NET


      // We use this field in conjunction with the Refresh methods, if we succeed we store a zero,
      // on failure we store the HResult in it so that we can give back a generic error back.
      [NonSerialized] internal int DataInitialised = -1;


      // The pre-cached FileSystemInfo information.
      [NonSerialized] internal NativeMethods.WIN32_FILE_ATTRIBUTE_DATA Win32AttributeData;

      #endregion // Fields


      #region Properties

      #region .NET

      /// <summary>Gets or sets the attributes for the current file or directory.</summary>
      /// <remarks>
      ///   <para>The value of the CreationTime property is pre-cached</para>
      ///   <para>To get the latest value, call the Refresh method.</para>
      /// </remarks>
      /// <value><see cref="FileAttributes"/> of the current <see cref="FileSystemInfo"/>.</value>
      ///
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      public FileAttributes Attributes
      {
         [SecurityCritical]
         get
         {
            if (DataInitialised == -1)
            {
               Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
               Refresh();
            }

            // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. 

            if (DataInitialised != 0)
               NativeError.ThrowException(DataInitialised, FullPath);

            return Win32AttributeData.dwFileAttributes;
         }


         [SecurityCritical]
         set
         {
            File.SetAttributesCore(Transaction, IsDirectory, LongFullName, value, PathFormat.LongFullPath);
            Reset();
         }
      }


      /// <summary>Gets or sets the creation time of the current file or directory.</summary>
      /// <remarks>
      ///   <para>The value of the CreationTime property is pre-cached To get the latest value, call the Refresh method.</para>
      ///   <para>This method may return an inaccurate value, because it uses native functions whose values may not be continuously updated by
      ///   the operating system.</para>
      ///   <para>If the file described in the FileSystemInfo object does not exist, this property will return
      ///   12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.</para>
      ///   <para>NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time.
      ///   This process is known as file tunneling. As a result, it may be necessary to explicitly set the creation time of a file if you are
      ///   overwriting or replacing an existing file.</para>
      /// </remarks>
      /// <value>The creation date and time of the current <see cref="FileSystemInfo"/> object.</value>
      ///
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      public DateTime CreationTime
      {
         [SecurityCritical] get { return CreationTimeUtc.ToLocalTime(); }

         [SecurityCritical] set { CreationTimeUtc = value.ToUniversalTime(); }
      }


      /// <summary>Gets or sets the creation time, in coordinated universal time (UTC), of the current file or directory.</summary>
      /// <remarks>
      ///   <para>The value of the CreationTimeUtc property is pre-cached
      ///   To get the latest value, call the Refresh method.</para>
      ///   <para>This method may return an inaccurate value, because it uses native functions
      ///   whose values may not be continuously updated by the operating system.</para>
      ///   <para>To get the latest value, call the Refresh method.</para>
      ///   <para>If the file described in the FileSystemInfo object does not exist, this property will return
      ///   12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC).</para>
      ///   <para>NTFS-formatted drives may cache file meta-info, such as file creation time, for a short period of time.
      ///   This process is known as file tunneling. As a result, it may be necessary to explicitly set the creation time
      ///   of a file if you are overwriting or replacing an existing file.</para>
      /// </remarks>
      /// <value>The creation date and time in UTC format of the current <see cref="FileSystemInfo"/> object.</value>
      ///
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      [ComVisible(false)]
      public DateTime CreationTimeUtc
      {
         [SecurityCritical]
         get
         {
            if (DataInitialised == -1)
            {
               Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
               Refresh();
            }

            // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. 
            if (DataInitialised != 0)
               NativeError.ThrowException(DataInitialised, LongFullName);

            return DateTime.FromFileTimeUtc(Win32AttributeData.ftCreationTime);
         }


         [SecurityCritical]
         set
         {
            File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, value, null, null, false, PathFormat.LongFullPath);

            Reset();
         }
      }


      /// <summary>Gets a value indicating whether the file or directory exists.</summary>
      /// <remarks>
      ///   <para>The <see cref="Exists"/> property returns <c>false</c> if any error occurs while trying to determine if the
      ///   specified file or directory exists.</para>
      ///   <para>This can occur in situations that raise exceptions such as passing a directory- or file name with invalid characters or too
      ///   many characters,</para>
      ///   <para>a failing or missing disk, or if the caller does not have permission to read the file or directory.</para>
      /// </remarks>
      /// <value><c>true</c> if the file or directory exists; otherwise, <c>false</c>.</value>
      public abstract bool Exists { get; }


      /// <summary>Gets the string representing the extension part of the file.</summary>
      /// <remarks>
      ///   The Extension property returns the <see cref="FileSystemInfo"/> extension, including the period (.).
      ///   For example, for a file c:\NewFile.txt, this property returns ".txt".
      /// </remarks>
      /// <value>A string containing the <see cref="FileSystemInfo"/> extension.</value>
      public string Extension
      {
         get { return Path.GetExtension(FullPath, false); }
      }


      /// <summary>Gets the full path of the directory or file.</summary>
      /// <value>A string containing the full path.</value>
      public virtual string FullName
      {
         [SecurityCritical] get { return FullPath; }
      }

      
      /// <summary>Gets or sets the time the current file or directory was last accessed.</summary>
      /// <remarks>
      ///   <para>The value of the LastAccessTime property is pre-cached
      ///   To get the latest value, call the Refresh method.</para>
      ///   <para>This method may return an inaccurate value, because it uses native functions
      ///   whose values may not be continuously updated by the operating system.</para>
      ///   <para>If the file described in the FileSystemInfo object does not exist, this property will return
      ///   12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.</para>
      /// </remarks>
      /// <value>The time that the current file or directory was last accessed.</value>
      ///
      /// <exception cref="IOException"/>
      public DateTime LastAccessTime
      {
         [SecurityCritical] get { return LastAccessTimeUtc.ToLocalTime(); }

         [SecurityCritical] set { LastAccessTimeUtc = value.ToUniversalTime(); }
      }


      /// <summary>Gets or sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed.</summary>
      /// <remarks>
      ///   <para>The value of the LastAccessTimeUtc property is pre-cached.
      ///   To get the latest value, call the Refresh method.</para>
      ///   <para>This method may return an inaccurate value, because it uses native functions
      ///   whose values may not be continuously updated by the operating system.</para>
      ///   <para>If the file described in the FileSystemInfo object does not exist, this property will return
      ///   12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.</para>
      /// </remarks>
      /// <value>The UTC time that the current file or directory was last accessed.</value>
      ///
      /// <exception cref="IOException"/>
      [ComVisible(false)]
      public DateTime LastAccessTimeUtc
      {
         [SecurityCritical]
         get
         {
            if (DataInitialised == -1)
            {
               Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
               Refresh();
            }

            // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. 
            if (DataInitialised != 0)
               NativeError.ThrowException(DataInitialised, LongFullName);

            return DateTime.FromFileTimeUtc(Win32AttributeData.ftLastAccessTime);
         }


         [SecurityCritical]
         set
         {
            File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, null, value, null, false, PathFormat.LongFullPath);

            Reset();
         }
      }


      /// <summary>Gets or sets the time when the current file or directory was last written to.</summary>
      /// <remarks>
      ///   <para>The value of the LastWriteTime property is pre-cached.
      ///   To get the latest value, call the Refresh method.</para>
      ///   <para>This method may return an inaccurate value, because it uses native functions
      ///   whose values may not be continuously updated by the operating system.</para>
      ///   <para>If the file described in the FileSystemInfo object does not exist, this property will return
      ///   12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.</para>
      /// </remarks>
      /// <value>The time the current file was last written.</value>
      ///
      /// <exception cref="IOException"/>
      public DateTime LastWriteTime
      {
         get { return LastWriteTimeUtc.ToLocalTime(); }

         set { LastWriteTimeUtc = value.ToUniversalTime(); }
      }


      /// <summary>Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to.</summary>
      /// <remarks>
      ///   <para>The value of the LastWriteTimeUtc property is pre-cached. To get the latest value, call the Refresh method.</para>
      ///   <para>This method may return an inaccurate value, because it uses native functions whose values may not be continuously updated by
      ///   the operating system.</para>
      ///   <para>If the file described in the FileSystemInfo object does not exist, this property will return 12:00 midnight, January 1, 1601
      ///   A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.</para>
      /// </remarks>
      /// <value>The UTC time when the current file was last written to.</value>
      [ComVisible(false)]
      public DateTime LastWriteTimeUtc
      {
         [SecurityCritical]
         get
         {
            if (DataInitialised == -1)
            {
               Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
               Refresh();
            }

            // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. 
            if (DataInitialised != 0)
               NativeError.ThrowException(DataInitialised, LongFullName);

            return DateTime.FromFileTimeUtc(Win32AttributeData.ftLastWriteTime);
         }


         [SecurityCritical]
         set
         {
            File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, null, null, value, false, PathFormat.LongFullPath);

            Reset();
         }
      }


      /// <summary>
      ///   For files, gets the name of the file. For directories, gets the name of the last directory in the hierarchy if a hierarchy exists.
      ///   <para>Otherwise, the Name property gets the name of the directory.</para>
      /// </summary>
      /// <remarks>
      ///   <para>For a directory, Name returns only the name of the parent directory, such as Dir, not c:\Dir.</para>
      ///   <para>For a subdirectory, Name returns only the name of the subdirectory, such as Sub1, not c:\Dir\Sub1.</para>
      ///   <para>For a file, Name returns only the file name and file name extension, such as MyFile.txt, not c:\Dir\Myfile.txt.</para>
      /// </remarks>
      /// <value>
      ///   <para>A string that is the name of the parent directory, the name of the last directory in the hierarchy,</para>
      ///   <para>or the name of a file, including the file name extension.</para>
      /// </value>
      public abstract string Name { get; }

      #endregion // .NET


      #region AlphaFS

      /// <summary>Returns the path as a string.</summary>
      protected internal string DisplayPath { get; protected set; }


      private FileSystemEntryInfo _entryInfo;

      /// <summary>[AlphaFS] Gets the instance of the <see cref="FileSystemEntryInfo"/> class.</summary>
      public FileSystemEntryInfo EntryInfo
      {
         [SecurityCritical]
         get
         {
            if (null == _entryInfo)
            {
               Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
               RefreshEntryInfo();
            }

            // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. 
            if (DataInitialised > 0)
               NativeError.ThrowException(DataInitialised, LongFullName);

            return _entryInfo;
         }


         internal set
         {
            _entryInfo = value;

            DataInitialised = value == null ? -1 : 0;

            if (DataInitialised == 0 && null != _entryInfo)
               Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(_entryInfo.Win32FindData);
         }
      }


      /// <summary>[AlphaFS] The initial "IsDirectory" indicator that was passed to the constructor.</summary>
      protected bool IsDirectory { get; set; }


      /// <summary>The full path of the file system object in Unicode (LongPath) format.</summary>
      protected string LongFullName { get; set; }


      /// <summary>[AlphaFS] Represents the KernelTransaction that was passed to the constructor.</summary>
      protected KernelTransaction Transaction { get; set; }

      #endregion // AlphaFS

      #endregion // Properties


      #region Methods

      #region .NET

      /// <summary>Deletes a file or directory.</summary>
      [SecurityCritical]
      public abstract void Delete();


      /// <summary>Refreshes the state of the object.</summary>
      /// <remarks>
      ///   <para>FileSystemInfo.Refresh() takes a snapshot of the file from the current file system.</para>
      ///   <para>Refresh cannot correct the underlying file system even if the file system returns incorrect or outdated information.</para>
      ///   <para>This can happen on platforms such as Windows 98.</para>
      ///   <para>Calls must be made to Refresh() before attempting to get the attribute information, or the information will be
      ///   outdated.</para>
      /// </remarks>
      [SecurityCritical]
      public void Refresh()
      {
         DataInitialised = File.FillAttributeInfoCore(Transaction, LongFullName, ref Win32AttributeData, false, false);

         IsDirectory = File.IsDirectory(Win32AttributeData.dwFileAttributes);
      }


      /// <summary>Returns a string that represents the current object.</summary>
      /// <remarks>
      ///   ToString is the major formatting method in the .NET Framework. It converts an object to its string representation so that it is
      ///   suitable for display.
      /// </remarks>
      /// <returns>A string that represents this instance.</returns>
      public override string ToString()
      {
         // "Alphaleonis.Win32.Filesystem.FileSystemInfo"
         return GetType().ToString();
      }


      /// <summary>Serves as a hash function for a particular type.</summary>
      /// <returns>A hash code for the current Object.</returns>
      public override int GetHashCode()
      {
         return null != FullName ? FullName.GetHashCode() : 0;
      }


      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="other">Another <see cref="FileSystemInfo"/> instance to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public bool Equals(FileSystemInfo other)
      {
         return null != other && GetType() == other.GetType() &&
                Equals(Name, other.Name) &&
                Equals(FullName, other.FullName) &&
                Equals(Attributes, other.Attributes) &&
                Equals(CreationTimeUtc, other.CreationTimeUtc) &&
                Equals(LastAccessTimeUtc, other.LastAccessTimeUtc);
      }


      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="obj">Another object to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public override bool Equals(object obj)
      {
         var other = obj as FileSystemInfo;

         return null != other && Equals(other);
      }


      /// <summary>Implements the operator ==</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator ==(FileSystemInfo left, FileSystemInfo right)
      {
         return ReferenceEquals(left, null) && ReferenceEquals(right, null) ||
                !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right);
      }


      /// <summary>Implements the operator !=</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator !=(FileSystemInfo left, FileSystemInfo right)
      {
         return !(left == right);
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Refreshes the current <see cref="FileSystemInfo"/> instance (<see cref="DirectoryInfo"/> or <see cref="FileInfo"/>) with a new destination path.</summary>
      internal void UpdateSourcePath(string destinationPath, string destinationPathLp)
      {
         LongFullName = destinationPathLp;

         FullPath = null != destinationPathLp ? Path.GetRegularPathCore(LongFullName, GetFullPathOptions.None, false) : null;

         OriginalPath = destinationPath;

         DisplayPath = null != OriginalPath ? Path.GetRegularPathCore(OriginalPath, GetFullPathOptions.None, false) : null;

         // Flush any cached information about the FileSystemInfo instance.
         Reset();
      }


      /// <summary>[AlphaFS] Refreshes the state of the <see cref="FileSystemEntryInfo"/> EntryInfo property.</summary>
      /// <remarks>
      ///   <para>FileSystemInfo.RefreshEntryInfo() takes a snapshot of the file from the current file system.</para>
      ///   <para>Refresh cannot correct the underlying file system even if the file system returns incorrect or outdated information.</para>
      ///   <para>This can happen on platforms such as Windows 98.</para>
      ///   <para>Calls must be made to Refresh() before attempting to get the attribute information, or the information will be outdated.</para>
      /// </remarks>
      [SecurityCritical]
      protected void RefreshEntryInfo()
      {
         _entryInfo = File.GetFileSystemEntryInfoCore(Transaction, IsDirectory, LongFullName, true, PathFormat.LongFullPath);

         if (null == _entryInfo)
            DataInitialised = -1;

         else
         {
            DataInitialised = 0;
            Win32AttributeData = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(_entryInfo.Win32FindData);
         }
      }


      /// <summary>[AlphaFS] Resets the state of the file system object to uninitialized.</summary>
      private void Reset()
      {
         DataInitialised = -1;
      }


      /// <summary>Initializes the specified file name.</summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="NotSupportedException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="isFolder">Specifies that <paramref name="path"/> is a file or directory.</param>
      /// <param name="path">The full path and name of the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      internal void InitializeCore(KernelTransaction transaction, bool isFolder, string path, PathFormat pathFormat)
      {
         if (pathFormat == PathFormat.RelativePath)
            Path.CheckSupportedPathFormat(path, true, true);

         LongFullName = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | (isFolder ? GetFullPathOptions.RemoveTrailingDirectorySeparator : 0) | GetFullPathOptions.ContinueOnNonExist);
         
         // (Not on MSDN): .NET 4+ Trailing spaces are removed from the end of the path parameter before creating the FileSystemInfo instance.

         FullPath = Path.GetRegularPathCore(LongFullName, GetFullPathOptions.None, false);

         IsDirectory = isFolder;

         Transaction = transaction;

         OriginalPath = FullPath.Length == 2 && FullPath[1] == Path.VolumeSeparatorChar ? Path.CurrentDirectoryPrefix : path;

         DisplayPath = OriginalPath.Length != 2 || OriginalPath[1] != Path.VolumeSeparatorChar ? Path.GetRegularPathCore(OriginalPath, GetFullPathOptions.None, false) : Path.CurrentDirectoryPrefix;
      }


      internal static SafeFindFileHandle FindFirstFileNative(KernelTransaction transaction, string pathLp, NativeMethods.FINDEX_INFO_LEVELS infoLevel, NativeMethods.FINDEX_SEARCH_OPS searchOption, NativeMethods.FIND_FIRST_EX_FLAGS additionalFlags, out int lastError, out NativeMethods.WIN32_FIND_DATA win32FindData)
      {
         var safeHandle = null == transaction || !NativeMethods.IsAtLeastWindowsVista

            // FindFirstFileEx() / FindFirstFileTransacted()
            // 2013-01-13: MSDN confirms LongPath usage.

            // A trailing backslash is not allowed.
            ? NativeMethods.FindFirstFileEx(Path.RemoveTrailingDirectorySeparator(pathLp), infoLevel, out win32FindData, searchOption, IntPtr.Zero, additionalFlags)

            : NativeMethods.FindFirstFileTransacted(Path.RemoveTrailingDirectorySeparator(pathLp), infoLevel, out win32FindData, searchOption, IntPtr.Zero, additionalFlags, transaction.SafeHandle);

         lastError = Marshal.GetLastWin32Error();

         if (!NativeMethods.IsValidHandle(safeHandle, false))
            safeHandle = null;


         return safeHandle;
      }

      #endregion // Methods
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/AlphaFS_Directory.HasInheritedPermissions.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Security.AccessControl;

namespace AlphaFS.UnitTest
{
   public partial class AccessControlTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_HasInheritedPermissions_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_HasInheritedPermissions(false);
         AlphaFS_Directory_HasInheritedPermissions(true);
      }


      private void AlphaFS_Directory_HasInheritedPermissions(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5);

            Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName);
            

            foreach (var dir in System.IO.Directory.EnumerateDirectories(folder.FullName, "*", System.IO.SearchOption.AllDirectories))
            {
               // Assume inheritance is enabled by default.

               Assert.IsTrue(Alphaleonis.Win32.Filesystem.Directory.HasInheritedPermissions(dir));


               DirectorySecurity acl;

               try
               {
                  // Disable inheritance.

                  acl = System.IO.Directory.GetAccessControl(dir);
                  acl.SetAccessRuleProtection(true, false);
                  Alphaleonis.Win32.Filesystem.Directory.SetAccessControl(dir, acl, AccessControlSections.Access);

                  Assert.IsFalse(Alphaleonis.Win32.Filesystem.Directory.HasInheritedPermissions(dir));
               }
               finally
               {

                  // Enable inheritance.

                  acl = System.IO.Directory.GetAccessControl(dir);
                  acl.SetAccessRuleProtection(false, true);
                  Alphaleonis.Win32.Filesystem.Directory.SetAccessControl(dir, acl, AccessControlSections.Access);

                  Assert.IsTrue(Alphaleonis.Win32.Filesystem.Directory.HasInheritedPermissions(dir));
               }
            }
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetRegularPathCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>Gets the regular path from a long path.</summary>
      /// <returns>
      ///   Returns the regular form of a long <paramref name="path"/>.
      ///   For example: "\\?\C:\Temp\file.txt" to: "C:\Temp\file.txt", or: "\\?\UNC\Server\share\file.txt" to: "\\Server\share\file.txt".
      /// </returns>
      /// <remarks>
      ///   MSDN: String.TrimEnd Method notes to Callers: http://msdn.microsoft.com/en-us/library/system.string.trimend%28v=vs.110%29.aspx
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="path">The path.</param>
      /// <param name="options">Options for controlling the full path retrieval.</param>
      /// <param name="allowEmpty">When <c>false</c>, throws an <see cref="ArgumentException"/>.</param>
      [SecurityCritical]
      internal static string GetRegularPathCore(string path, GetFullPathOptions options, bool allowEmpty)
      {
         if (null == path)
            throw new ArgumentNullException("path");

         if (!allowEmpty && (path.Trim().Length == 0 || Utils.IsNullOrWhiteSpace(path)))
            throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "path");

         if (options != GetFullPathOptions.None)
            path = ApplyFullPathOptions(path, options);


         if (path.StartsWith(DosDeviceUncPrefix, StringComparison.OrdinalIgnoreCase))
            return UncPrefix + path.Substring(DosDeviceUncPrefix.Length);


         if (path.StartsWith(LogicalDrivePrefix, StringComparison.Ordinal))
            return path.Substring(LogicalDrivePrefix.Length);


         if (path.StartsWith(NonInterpretedPathPrefix, StringComparison.Ordinal))
            return path.Substring(NonInterpretedPathPrefix.Length);


         return path.StartsWith(GlobalRootPrefix, StringComparison.OrdinalIgnoreCase) || path.StartsWith(VolumePrefix, StringComparison.OrdinalIgnoreCase) ||
                !path.StartsWith(LongPathPrefix, StringComparison.Ordinal)

            ? path
            : (path.StartsWith(LongPathUncPrefix, StringComparison.OrdinalIgnoreCase) ? UncPrefix + path.Substring(LongPathUncPrefix.Length) : path.Substring(LongPathPrefix.Length));
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/File.Copy/File.Copy.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class CopyTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void File_Copy_LocalAndNetwork_Success()
      {
         File_Copy(false);
         File_Copy(true);
      }


      private void File_Copy(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var fileSource = tempRoot.CreateFileRandomizedAttributes();
            var fileCopy = tempRoot.RandomTxtFileFullPath;

            Console.WriteLine("Src File Path: [{0}] [{1}]", Alphaleonis.Utils.UnitSizeToText(fileSource.Length), fileSource.FullName);
            Console.WriteLine("Dst File Path: [{0}]", fileCopy);
            

            var cmr = Alphaleonis.Win32.Filesystem.File.Copy(fileSource.FullName, fileCopy, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);

            UnitTestConstants.Dump(cmr);


            Assert.IsTrue(System.IO.File.Exists(fileCopy), "The file does not exists, but is expected to.");
            
            Assert.AreEqual(fileSource.Length, new System.IO.FileInfo(fileCopy).Length, "The file sizes do no match, but are expected to.");

            Assert.IsTrue(System.IO.File.Exists(fileSource.FullName), "The original file does not exist, but is expected to.");

            Assert.AreEqual(0, cmr.Retries);
         }
         
         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File.WriteAllBytesTransacted.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>[AlphaFS] Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to write to.</param>
      /// <param name="bytes">The bytes to write to the file.</param>
      [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "bytes")]
      [SecurityCritical]
      public static void WriteAllBytesTransacted(KernelTransaction transaction, string path, byte[] bytes)
      {
         WriteAllBytesCore(transaction, path, bytes, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to write to.</param>
      /// <param name="bytes">The bytes to write to the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "bytes")]
      [SecurityCritical]
      public static void WriteAllBytesTransacted(KernelTransaction transaction, string path, byte[] bytes, PathFormat pathFormat)
      {
         WriteAllBytesCore(transaction, path, bytes, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Enumerations/ResourceDisplayType.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>The display options for the network object in a network browsing user interface.</summary>
      internal enum ResourceDisplayType
      {
         /// <summary>RESOURCEDISPLAYTYPE_GENERIC
         /// <para>The method used to display the object does not matter.</para>
         /// </summary>
         Generic = 0,

         /// <summary>RESOURCEDISPLAYTYPE_DOMAIN
         /// <para>The object should be displayed as a domain.</para>
         /// </summary>
         Domain = 1,

         /// <summary>RESOURCEDISPLAYTYPE_SERVER
         /// <para>The object should be displayed as a server.</para>
         /// </summary>
         Server = 2,

         /// <summary>RESOURCEDISPLAYTYPE_SHARE
         /// <para>The object should be displayed as a share</para>
         /// </summary>
         Share = 3,

         /// <summary>RESOURCEDISPLAYTYPE_FILE
         /// <para>The object should be displayed as a file.</para>
         /// </summary>
         File = 4,

         /// <summary>RESOURCEDISPLAYTYPE_GROUP
         /// <para>The object should be displayed as a group.</para>
         /// </summary>
         Group = 5,

         /// <summary>RESOURCEDISPLAYTYPE_NETWORK
         /// <para>The object should be displayed as a network.</para>
         /// </summary>
         Network = 6,

         /// <summary>RESOURCEDISPLAYTYPE_ROOT
         /// <para>The object should be displayed as a logical root for the entire network.</para>
         /// </summary>
         Root = 7,

         /// <summary>RESOURCEDISPLAYTYPE_SHAREADMIN
         /// <para>The object should be displayed as a administrative share.</para>
         /// </summary>
         ShareAdmin = 8,

         /// <summary>RESOURCEDISPLAYTYPE_DIRECTORY
         /// <para>The object should be displayed as a directory.</para>
         /// </summary>
         Directory = 9,

         /// <summary>RESOURCEDISPLAYTYPE_TREE
         /// <para>The object should be displayed as a tree.</para>
         /// </summary>
         Tree = 10,

         /// <summary>RESOURCEDISPLAYTYPE_NDSCONTAINER
         /// <para>The object should be displayed as a Netware Directory Service container.</para>
         /// </summary>
         NdsContainer = 11
      }
   }
}

<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.EnumerateHardLinksCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>[AlphaFS] Creates an enumeration of all the hard links to the specified <paramref name="path"/>.</summary>
      /// <returns>An enumerable collection of <see cref="string"/> of all the hard links to the specified <paramref name="path"/></returns>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The name of the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      internal static IEnumerable<string> EnumerateHardLinksCore(KernelTransaction transaction, string path, PathFormat pathFormat)
      {
         if (!NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message);

         var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

         // Default buffer length, will be extended if needed, although this should not happen.
         uint length = NativeMethods.MaxPathUnicode;
         var builder = new StringBuilder((int) length);


      getFindFirstFileName:

         using (var safeHandle = null == transaction

            // FindFirstFileNameW() / FindFirstFileNameTransactedW() / FindNextFileNameW()
            // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
            // 2017-05-30: FindFirstFileNameW() MSDN confirms LongPath usage: Starting with Windows 10, version 1607

            ? NativeMethods.FindFirstFileNameW(pathLp, 0, out length, builder)

            : NativeMethods.FindFirstFileNameTransactedW(pathLp, 0, out length, builder, transaction.SafeHandle))
         {
            var lastError = Marshal.GetLastWin32Error();

            if (!NativeMethods.IsValidHandle(safeHandle, false))
            {
               switch ((uint) lastError)
               {
                  case Win32Errors.ERROR_MORE_DATA:
                     builder = new StringBuilder((int) length);
                     goto getFindFirstFileName;

                  default:
                     // If the function fails, the return value is INVALID_HANDLE_VALUE.
                     NativeError.ThrowException(lastError, pathLp);
                     break;
               }
            }

            yield return builder.ToString();


            do
            {
               while (!NativeMethods.FindNextFileNameW(safeHandle, out length, builder))
               {
                  lastError = Marshal.GetLastWin32Error();

                  switch ((uint) lastError)
                  {
                     // We've reached the end of the enumeration.
                     case Win32Errors.ERROR_HANDLE_EOF:
                        yield break;

                     case Win32Errors.ERROR_MORE_DATA:
                        builder = new StringBuilder((int) length);
                        continue;

                     default:
                        // If the function fails, the return value is zero (0).
                        NativeError.ThrowException(lastError);
                        break;
                  }
               }


               yield return builder.ToString();

            } while (true);
         }
      }
   }
}


<|start_filename|>build/git-util.cake<|end_filename|>

/// <summary>
///  Executes a command using git.exe.
/// </summary>
/// <param name="repositoryDir">The directory of the git repository. This will be the working directory. Specify null to not change the directory (eg. for clone).</param>
/// <param name="command">The command to run.</param>
/// <param name="args">Any additional arguments to the command.</param>
void GitCommand(DirectoryPath repositoryDir, string command, params string[] args)
{
    var gitPath = Context.Tools.Resolve("git.exe");
    if (gitPath == null)
        throw new Exception($"Unable to resolve git.exe tool.");

    var argumentBuilder = new ProcessArgumentBuilder();
    argumentBuilder.Append(command);
    foreach (var arg in args)
        argumentBuilder.Append(arg);

    int exitCode = StartProcess(gitPath, new ProcessSettings {
        WorkingDirectory = repositoryDir, 
        Arguments = argumentBuilder,
        RedirectStandardOutput = true,
        RedirectStandardError = true
    }, out var stdOut, out var stdErr);

    foreach (var output in stdOut)
        Verbose(output);

    // Git apparently writes all messages to stderr... so we just write them as verbose.
     foreach (var output in stdErr)
        Verbose(output);

    if (exitCode != 0)
    {
        throw new Exception($"Git failed with exit code {exitCode}.");
    }
}

<|start_filename|>tests/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetSuffixedDirectoryNameWithoutRoot.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class PathTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Path_GetSuffixedDirectoryNameWithoutRoot_LocalAndNetwork_Success()
      {
         // Note: System.IO.Path does not have a similar method to compare with.

         AlphaFS_Path_GetSuffixedDirectoryNameWithoutRoot(false);
         AlphaFS_Path_GetSuffixedDirectoryNameWithoutRoot(true);
      }


      private void AlphaFS_Path_GetSuffixedDirectoryNameWithoutRoot(bool isNetwork)
      {
         UnitTestConstants.PrintUnitTestHeader(isNetwork);

         var backslash = Alphaleonis.Win32.Filesystem.Path.DirectorySeparator;
         var neDir = "Non-Existing Directory";
         var system32Folder = (Environment.SystemDirectory + backslash).Replace(UnitTestConstants.SysDrive + backslash, string.Empty);


         var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, neDir);
         if (isNetwork)
            fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath);

         var suffixedDirectoryNameWithoutRoot = Alphaleonis.Win32.Filesystem.Path.GetSuffixedDirectoryNameWithoutRoot(fullPath);

         Console.WriteLine("Full Path                          : " + fullPath);
         Console.WriteLine("GetSuffixedDirectoryNameWithoutRoot: " + suffixedDirectoryNameWithoutRoot);

         Assert.AreEqual(system32Folder, suffixedDirectoryNameWithoutRoot);




         fullPath = System.IO.Path.Combine(fullPath, "Non-Existing file.txt");
         neDir = (System.IO.Path.Combine(Environment.SystemDirectory, neDir) + backslash).Replace(UnitTestConstants.SysDrive + backslash, string.Empty);
         if (isNetwork)
            fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath);

         suffixedDirectoryNameWithoutRoot = Alphaleonis.Win32.Filesystem.Path.GetSuffixedDirectoryNameWithoutRoot(fullPath);

         Console.WriteLine("\nFull Path                          : " + fullPath);
         Console.WriteLine("GetSuffixedDirectoryNameWithoutRoot: " + suffixedDirectoryNameWithoutRoot);

         Assert.AreEqual(neDir, suffixedDirectoryNameWithoutRoot);




         fullPath = Environment.SystemDirectory;
         if (isNetwork)
            fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath);

         suffixedDirectoryNameWithoutRoot = Alphaleonis.Win32.Filesystem.Path.GetSuffixedDirectoryNameWithoutRoot(fullPath);

         Console.WriteLine("\nFull Path                          : " + fullPath);
         Console.WriteLine("GetSuffixedDirectoryNameWithoutRoot: " + suffixedDirectoryNameWithoutRoot);


         var windowsFolderName = System.IO.Path.GetDirectoryName(fullPath).Replace(System.IO.Directory.GetDirectoryRoot(fullPath), string.Empty) + backslash;

         if (isNetwork)
            windowsFolderName = windowsFolderName.TrimStart(Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar);

         Assert.AreEqual(windowsFolderName, suffixedDirectoryNameWithoutRoot);




         fullPath = UnitTestConstants.SysDrive + backslash;
         if (isNetwork)
            fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath);

         suffixedDirectoryNameWithoutRoot = Alphaleonis.Win32.Filesystem.Path.GetSuffixedDirectoryNameWithoutRoot(fullPath);

         Console.WriteLine("\nFull Path                          : " + fullPath);
         Console.WriteLine("GetSuffixedDirectoryNameWithoutRoot: " + suffixedDirectoryNameWithoutRoot);

         Assert.AreEqual(null, suffixedDirectoryNameWithoutRoot);


         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetFinalPathNameByHandleCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>Retrieves the final path for the specified file, formatted as <see cref="FinalPathFormats"/>.</summary>
      /// <returns>The final path as a string.</returns>
      /// <remarks>
      ///   A final path is the path that is returned when a path is fully resolved. For example, for a symbolic link named "C:\tmp\mydir" that
      ///   points to "D:\yourdir", the final path would be "D:\yourdir". The string that is returned by this function uses the
      ///   <see cref="LongPathPrefix"/> syntax.
      /// </remarks>
      /// <param name="handle">Then handle to a <see cref="SafeFileHandle"/> instance.</param>
      /// <param name="finalPath">The final path, formatted as <see cref="FinalPathFormats"/></param>
      [SecurityCritical]
      internal static string GetFinalPathNameByHandleCore(SafeFileHandle handle, FinalPathFormats finalPath)
      {
         NativeMethods.IsValidHandle(handle);

         var buffer = new StringBuilder(NativeMethods.MaxPathUnicode);

         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
         {
            if (NativeMethods.IsAtLeastWindowsVista)
            {
               // MSDN: GetFinalPathNameByHandle(): If the function fails for any other reason, the return value is zero.

               var success = NativeMethods.GetFinalPathNameByHandle(handle, buffer, (uint) buffer.Capacity, finalPath) == Win32Errors.ERROR_SUCCESS;

               var lastError = Marshal.GetLastWin32Error();
               if (!success && lastError != Win32Errors.ERROR_SUCCESS)
                  NativeError.ThrowException(lastError);


               return buffer.ToString();
            }
         }

         
         // Older OperatingSystem

         // Obtaining a File Name From a File Handle
         // http://msdn.microsoft.com/en-us/library/aa366789%28VS.85%29.aspx

         // Be careful when using GetFileSizeEx to check the size of hFile handle of an unknown "File" type object.
         // This is more towards returning a filename from a file handle. If the handle is a named pipe handle it seems to hang the thread.
         // Check for: FileTypes.DiskFile

         // Can't map a 0 byte file.
         long fileSizeHi;
         if (!NativeMethods.GetFileSizeEx(handle, out fileSizeHi))
            if (fileSizeHi == 0)
               return string.Empty;


         // PAGE_READONLY
         // Allows views to be mapped for read-only or copy-on-write access. An attempt to write to a specific region results in an access violation.
         // The file handle that the hFile parameter specifies must be created with the GENERIC_READ access right.
         // PageReadOnly = 0x02,
         using (var handle2 = NativeMethods.CreateFileMapping(handle, null, 2, 0, 1, null))
         {
            NativeMethods.IsValidHandle(handle, Marshal.GetLastWin32Error());

            // FILE_MAP_READ
            // Read = 4
            using (var pMem = NativeMethods.MapViewOfFile(handle2, 4, 0, 0, (UIntPtr)1))
            {
               if (NativeMethods.IsValidHandle(pMem, Marshal.GetLastWin32Error()))
                  if (NativeMethods.GetMappedFileName(Process.GetCurrentProcess().Handle, pMem, buffer, (uint) buffer.Capacity))
                     NativeMethods.UnmapViewOfFile(pMem);
            }
         }


         // Default output from GetMappedFileName(): "\Device\HarddiskVolumeX\path\filename.ext"
         var dosDevice = buffer.Length > 0 ? buffer.ToString() : string.Empty;


         // Select output format.
         switch (finalPath)
         {
            // As-is: "\Device\HarddiskVolumeX\path\filename.ext"
            case FinalPathFormats.VolumeNameNT:
               return dosDevice;


            // To: "\path\filename.ext"
            case FinalPathFormats.VolumeNameNone:
               return DosDeviceToDosPath(dosDevice, string.Empty);


            // To: "\\?\Volume{GUID}\path\filename.ext"
            case FinalPathFormats.VolumeNameGuid:
               var dosPath = DosDeviceToDosPath(dosDevice, null);

               if (!Utils.IsNullOrWhiteSpace(dosPath))
               {
                  var driveLetter = RemoveTrailingDirectorySeparator(GetPathRoot(dosPath, false));
                  var file = GetFileName(dosPath, true);


                  if (!Utils.IsNullOrWhiteSpace(file))
                  { 
                     foreach (var drive in Directory.EnumerateLogicalDrivesCore(false, false)
                        
                        .Select(drv => drv.Name).Where(drv => driveLetter.Equals(RemoveTrailingDirectorySeparator(drv), StringComparison.OrdinalIgnoreCase)))

                        return CombineCore(false, Volume.GetUniqueVolumeNameForPath(drive), GetSuffixedDirectoryNameWithoutRootCore(null, dosPath, PathFormat.FullPath), file);
                  }
               }

               break;
         }


         // To: "\\?\C:\path\filename.ext"
         return !Utils.IsNullOrWhiteSpace(dosDevice) ? LongPathPrefix + DosDeviceToDosPath(dosDevice, null) : string.Empty;
      }


      /// <summary>Tranlates DosDevicePath, Volume GUID. For example: "\Device\HarddiskVolumeX\path\filename.ext" can translate to: "\path\filename.ext" or: "\\?\Volume{GUID}\path\filename.ext".</summary>
      /// <returns>A translated dos path.</returns>
      /// <param name="dosDevice">A DosDevicePath, for example: \Device\HarddiskVolumeX\path\filename.ext.</param>
      /// <param name="deviceReplacement">Alternate path/device text, usually <c>string.Empty</c> or <c>null</c>.</param>
      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      [SecurityCritical]
      private static string DosDeviceToDosPath(string dosDevice, string deviceReplacement)
      {
         if (Utils.IsNullOrWhiteSpace(dosDevice))
            return string.Empty;


         foreach (var drive in Directory.EnumerateLogicalDrivesCore(false, false).Select(drv => drv.Name))
         {
            try
            {
               var path = RemoveTrailingDirectorySeparator(drive);

               foreach (var devNt in Volume.QueryAllDosDevices().Where(device => device.StartsWith(path, StringComparison.OrdinalIgnoreCase)).ToArray())

                  return dosDevice.ReplaceIgnoreCase(devNt, deviceReplacement ?? path);
            }
            catch
            {
            }
         }

         return string.Empty;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory.HasInheritedPermissions.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>[AlphaFS] Checks if the directory has permission inheritance enabled.</summary>
      /// <param name="path">The full path to the directory to check.</param>
      /// <returns><c>true</c> if permission inheritance is enabled, <c>false</c> if permission inheritance is disabled.</returns>
      public static bool HasInheritedPermissions(string path)
      {
         return HasInheritedPermissions(path, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Checks if the directory has permission inheritance enabled.</summary>
      /// <returns><c>true</c> if permission inheritance is enabled, <c>false</c> if permission inheritance is disabled.</returns>
      /// <param name="path">The full path to the directory to check.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      public static bool HasInheritedPermissions(string path, PathFormat pathFormat)
      {
         if (Utils.IsNullOrWhiteSpace(path))
            throw new ArgumentNullException("path");


         var acl = File.GetAccessControlCore<DirectorySecurity>(true, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, pathFormat);

         var rawBytes = acl.GetSecurityDescriptorBinaryForm();

         var rsd = new RawSecurityDescriptor(rawBytes, 0);


         // "Include inheritable permissions from this object's parent" is unchecked.
         var inheritanceDisabled = (rsd.ControlFlags & ControlFlags.DiscretionaryAclProtected) == ControlFlags.DiscretionaryAclProtected;

         return !inheritanceDisabled;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File.Create.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.IO;
using System.Security;
using System.Security.AccessControl;
using FileStream = System.IO.FileStream;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      #region .NET

      /// <summary>Creates or overwrites a file in the specified path.</summary>
      /// <param name="path">The path and name of the file to create.</param>
      /// <returns>A <see cref="FileStream"/> that provides read/write access to the file specified in <paramref name="path"/>.</returns>
      [SecurityCritical]
      public static FileStream Create(string path)
      {
         return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, PathFormat.RelativePath);
      }


      /// <summary>Creates or overwrites the specified file.</summary>
      /// <param name="path">The name of the file.</param>
      /// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
      /// <returns>A <see cref="FileStream"/> with the specified buffer size that provides read/write access to the file specified in <paramref name="path"/>.</returns>
      [SecurityCritical]
      public static FileStream Create(string path, int bufferSize)
      {
         return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath);
      }


      /// <summary>Creates or overwrites the specified file, specifying a buffer size and a <see cref="FileOptions"/> value that describes how to create or overwrite the file.</summary>
      /// <param name="path">The name of the file.</param>
      /// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
      /// <param name="options">One of the <see cref="FileOptions"/> values that describes how to create or overwrite the file.</param>
      /// <returns>A new file with the specified buffer size.</returns>
      [SecurityCritical]
      public static FileStream Create(string path, int bufferSize, FileOptions options)
      {
         return CreateFileStreamCore(null, path, (ExtendedFileAttributes) options, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath);
      }


      /// <summary>Creates or overwrites the specified file, specifying a buffer size and a <see cref="FileOptions"/> value that describes how to create or overwrite the file.</summary>
      /// <param name="path">The name of the file.</param>
      /// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
      /// <param name="options">One of the <see cref="FileOptions"/> values that describes how to create or overwrite the file.</param>
      /// <param name="fileSecurity">One of the <see cref="FileSecurity"/> values that determines the access control and audit security for the file.</param>
      /// <returns>A new file with the specified buffer size, file options, and file security.</returns>
      [SecurityCritical]
      public static FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity)
      {
         return CreateFileStreamCore(null, path, (ExtendedFileAttributes) options, fileSecurity, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath);
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Creates or overwrites a file in the specified path.</summary>
      /// <param name="path">The path and name of the file to create.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>A <see cref="FileStream"/> that provides read/write access to the file specified in <paramref name="path"/>.</returns>
      [SecurityCritical]
      public static FileStream Create(string path, PathFormat pathFormat)
      {
         return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, pathFormat);
      }


      /// <summary>[AlphaFS] Creates or overwrites the specified file.</summary>
      /// <param name="path">The name of the file.</param>
      /// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>A <see cref="FileStream"/> with the specified buffer size that provides read/write access to the file specified in <paramref name="path"/>.</returns>
      [SecurityCritical]
      public static FileStream Create(string path, int bufferSize, PathFormat pathFormat)
      {
         return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat);
      }


      /// <summary>[AlphaFS] Creates or overwrites the specified file, specifying a buffer size and a <see cref="FileOptions"/> value that describes how to create or overwrite the file.</summary>
      /// <param name="path">The name of the file.</param>
      /// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
      /// <param name="options">One of the <see cref="FileOptions"/> values that describes how to create or overwrite the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>A new file with the specified buffer size.</returns>
      [SecurityCritical]
      public static FileStream Create(string path, int bufferSize, FileOptions options, PathFormat pathFormat)
      {
         return CreateFileStreamCore(null, path, (ExtendedFileAttributes) options, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat);
      }


      /// <summary>[AlphaFS] Creates or overwrites the specified file, specifying a buffer size and a <see cref="FileOptions"/> value that describes how to create or overwrite the file.</summary>
      /// <param name="path">The name of the file.</param>
      /// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
      /// <param name="options">One of the <see cref="FileOptions"/> values that describes how to create or overwrite the file.</param>
      /// <param name="fileSecurity">One of the <see cref="FileSecurity"/> values that determines the access control and audit security for the file.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>A new file with the specified buffer size, file options, and file security.</returns>
      [SecurityCritical]
      public static FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity, PathFormat pathFormat)
      {
         return CreateFileStreamCore(null, path, (ExtendedFileAttributes) options, fileSecurity, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/UnitTest Utility/DirectoryAssert.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Globalization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public static class DirectoryAssert
   {
      public static void Exists(string directoryPath)
      {
         if (!System.IO.Directory.Exists(directoryPath))
            throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The directory: [{0}] does not exist, but is expected to.", directoryPath));
      }


      public static void IsEncrypted(string directoryPath)
      {
         if ((System.IO.File.GetAttributes(directoryPath) & System.IO.FileAttributes.Encrypted) == 0)
            throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The directory: [{0}] is not encrypted, but is expected to.", directoryPath));
      }


      public static void IsNotEncrypted(string directoryPath)
      {
         if ((System.IO.File.GetAttributes(directoryPath) & System.IO.FileAttributes.Encrypted) != 0)
            throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The directory: [{0}] is encrypted, but is expected not to.", directoryPath));
      }


      public static void IsCompressed(string directoryPath)
      {
         if ((System.IO.File.GetAttributes(directoryPath) & System.IO.FileAttributes.Compressed) == 0)
            throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The directory: [{0}] is not compressed, but is expected to.", directoryPath));
      }


      public static void IsNotCompressed(string directoryPath)
      {
         if ((System.IO.File.GetAttributes(directoryPath) & System.IO.FileAttributes.Compressed) != 0)
            throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The directory: [{0}] is compressed, but is expected not to.", directoryPath));
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CopyMoveCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Copy/move a Non-/Transacted file or directory including its children to a new location, <see cref="CopyOptions"/> or <see cref="MoveOptions"/> can be specified,
      /// and the possibility of notifying the application of its progress through a callback function.
      /// </summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Copy or Move action.</returns>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>You cannot use the Move method to overwrite an existing file, unless <paramref name="cma.moveOptions"/> contains <see cref="MoveOptions.ReplaceExisting"/>.</para>
      ///   <para>Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an IOException.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      [SecurityCritical]
      internal static CopyMoveResult CopyMoveCore(CopyMoveArguments cma)
      {
         #region Setup
         
         var fsei = File.GetFileSystemEntryInfoCore(cma.Transaction, false, cma.SourcePath, true, cma.PathFormat);

         var isFolder = null == fsei || fsei.IsDirectory;

         // Directory.Move is applicable to both files and folders.

         cma = File.ValidateFileOrDirectoryMoveArguments(cma, false, isFolder);


         var copyMoveResult = new CopyMoveResult(cma, isFolder);

         var errorFilter = null != cma.DirectoryEnumerationFilters && null != cma.DirectoryEnumerationFilters.ErrorFilter ? cma.DirectoryEnumerationFilters.ErrorFilter : null;

         var retry = null != errorFilter && (cma.DirectoryEnumerationFilters.ErrorRetry > 0 || cma.DirectoryEnumerationFilters.ErrorRetryTimeout > 0);

         if (retry)
         {
            if (cma.DirectoryEnumerationFilters.ErrorRetry <= 0)
               cma.DirectoryEnumerationFilters.ErrorRetry = 2;

            if (cma.DirectoryEnumerationFilters.ErrorRetryTimeout <= 0)
               cma.DirectoryEnumerationFilters.ErrorRetryTimeout = 10;
         }


         // Calling start on a running Stopwatch is a no-op.
         copyMoveResult.Stopwatch.Start();

         #endregion // Setup


         if (cma.IsCopy)
         {
            // Copy folder SymbolicLinks.
            // Cannot be done by CopyFileEx() so emulate this.

            if (File.HasCopySymbolicLink(cma.CopyOptions))
            {
               var lvi = File.GetLinkTargetInfoCore(cma.Transaction, cma.SourcePathLp, true, PathFormat.LongFullPath);

               if (null != lvi)
               {
                  File.CreateSymbolicLinkCore(cma.Transaction, cma.DestinationPathLp, lvi.SubstituteName, SymbolicLinkTarget.Directory, PathFormat.LongFullPath);

                  copyMoveResult.TotalFolders = 1;
               }
            }

            else
            {
               if (isFolder)
                  CopyMoveDirectoryCore(retry, cma, copyMoveResult);

               else
                  File.CopyMoveCore(retry, cma, true, false, cma.SourcePathLp, cma.DestinationPathLp, copyMoveResult);
            }
         }


         // Move

         else
         {
            // AlphaFS feature to overcome a MoveFileXxx limitation.
            // MoveOptions.ReplaceExisting: This value cannot be used if lpNewFileName or lpExistingFileName names a directory.

            if (isFolder && !cma.DelayUntilReboot && File.HasReplaceExisting(cma.MoveOptions))

               DeleteDirectoryCore(cma.Transaction, null, cma.DestinationPathLp, true, true, true, PathFormat.LongFullPath);


            // 2017-06-07: A large target directory will probably create a progress-less delay in UI.
            // One way to get around this is to perform the delete in the File.CopyMove method.


            // Moves a file or directory, including its children.
            // Copies an existing directory, including its children to a new directory.

            File.CopyMoveCore(retry, cma, true, isFolder, cma.SourcePathLp, cma.DestinationPathLp, copyMoveResult);


            // If the move happened on the same drive, we have no knowledge of the number of files/folders.
            // However, we do know that the one folder was moved successfully.
            
            if (copyMoveResult.ErrorCode == Win32Errors.NO_ERROR && isFolder)
               copyMoveResult.TotalFolders = 1;
         }


         copyMoveResult.Stopwatch.Stop();

         return copyMoveResult;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetFinalPathNameByHandle/AlphaFS_Path.GetFinalPathNameByHandle.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class PathTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Path_GetFinalPathNameByHandle_Local_Success()
      {
         using (var tempRoot = new TemporaryDirectory())
         {
            var file = tempRoot.RandomDirectoryFullPath;

            Console.WriteLine("Input File Path: [{0}]\n", file);


            var longTempStream = Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + file;
            bool gotFileNameNormalized;
            bool gotFileNameOpened;
            bool gotVolumeNameDos;
            bool gotVolumeNameGuid;
            bool gotVolumeNameNt;
            bool gotVolumeNameNone;


            using (var stream = System.IO.File.Create(file))
            {
               // For Windows versions < Vista, the file must be > 0 bytes.
               if (!Alphaleonis.Win32.Filesystem.NativeMethods.IsAtLeastWindowsVista)
                  stream.WriteByte(1);


               var handle = stream.SafeFileHandle;

               var fileNameNormalized = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(handle);
               var fileNameOpened = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(handle, Alphaleonis.Win32.Filesystem.FinalPathFormats.FileNameOpened);

               var volumeNameDos = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(handle, Alphaleonis.Win32.Filesystem.FinalPathFormats.None);
               var volumeNameGuid = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(handle, Alphaleonis.Win32.Filesystem.FinalPathFormats.VolumeNameGuid);
               var volumeNameNt = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(handle, Alphaleonis.Win32.Filesystem.FinalPathFormats.VolumeNameNT);
               var volumeNameNone = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(handle, Alphaleonis.Win32.Filesystem.FinalPathFormats.VolumeNameNone);


               gotFileNameNormalized = !Alphaleonis.Utils.IsNullOrWhiteSpace(fileNameNormalized) && longTempStream.Equals(fileNameNormalized);
               gotFileNameOpened = !Alphaleonis.Utils.IsNullOrWhiteSpace(fileNameOpened) && longTempStream.Equals(fileNameOpened);
               gotVolumeNameDos = !Alphaleonis.Utils.IsNullOrWhiteSpace(volumeNameDos) && longTempStream.Equals(volumeNameDos);


               gotVolumeNameGuid = !Alphaleonis.Utils.IsNullOrWhiteSpace(volumeNameGuid) && volumeNameGuid.StartsWith(Alphaleonis.Win32.Filesystem.Path.VolumePrefix) && volumeNameGuid.EndsWith(volumeNameNone);
               gotVolumeNameNt = !Alphaleonis.Utils.IsNullOrWhiteSpace(volumeNameNt) && volumeNameNt.StartsWith(Alphaleonis.Win32.Filesystem.Path.DevicePrefix);
               gotVolumeNameNone = !Alphaleonis.Utils.IsNullOrWhiteSpace(volumeNameNone) && file.EndsWith(volumeNameNone);


               Console.WriteLine("\tFilestream.Name                : [{0}]", stream.Name);
               Console.WriteLine("\tFinalPathFormats.None          : [{0}]", fileNameNormalized);
               Console.WriteLine("\tFinalPathFormats.FileNameOpened: [{0}]", fileNameOpened);
               Console.WriteLine("\tFinalPathFormats.VolumeNameDos : [{0}]", volumeNameDos);
               Console.WriteLine("\tFinalPathFormats.VolumeNameGuid: [{0}]", volumeNameGuid);
               Console.WriteLine("\tFinalPathFormats.VolumeNameNT  : [{0}]", volumeNameNt);
               Console.WriteLine("\tFinalPathFormats.VolumeNameNone: [{0}]", volumeNameNone);
            }


            Assert.IsTrue(gotFileNameNormalized);
            Assert.IsTrue(gotFileNameOpened);
            Assert.IsTrue(gotVolumeNameDos);
            Assert.IsTrue(gotVolumeNameGuid);
            Assert.IsTrue(gotVolumeNameNt);
            Assert.IsTrue(gotVolumeNameNone);
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CompressDecompressCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Compress/decompress Non-/Transacted files/directories.</summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">A path that describes a directory to compress.</param>
      /// <param name="searchPattern">
      ///    The search string to match against the names of directories in <paramref name="path"/>.
      ///    This parameter can contain a combination of valid literal path and wildcard
      ///    (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
      /// </param>
      /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
      /// <param name="filters">The specification of custom filters to be used in the process.</param>
      /// <param name="compress"><c>true</c> compress, when <c>false</c> decompress.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void CompressDecompressCore(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions? options, DirectoryEnumerationFilters filters, bool compress, PathFormat pathFormat)
      {
         var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

         if (null == options)
            options = DirectoryEnumerationOptions.None;


         // Traverse the source folder, processing files and folders.

         foreach (var fsei in EnumerateFileSystemEntryInfosCore<FileSystemEntryInfo>(null, transaction, pathLp, searchPattern, null, options | DirectoryEnumerationOptions.AsLongPath, filters, PathFormat.LongFullPath))

            Device.ToggleCompressionCore(transaction, fsei.IsDirectory, fsei.FullPath, compress, PathFormat.LongFullPath);


         // Process the root directory, the given path.

         Device.ToggleCompressionCore(transaction, true, pathLp, compress, PathFormat.LongFullPath);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public static class UnitTestAssert
   {
      public static void IsElevatedProcess()
      {
         if (!Alphaleonis.Win32.Security.ProcessContext.IsElevatedProcess)
            Inconclusive("This unit test must be run elevated.");
      }

      
      public static void Inconclusive(string errorMessage)
      {
         Console.WriteLine("{0}{1}{0}", Environment.NewLine, errorMessage);

         Assert.Inconclusive(errorMessage);

         //throw new AssertFailedException(errorMessage);
      }


      public static void InconclusiveBecauseResourcesAreUnavailable()
      {
         Inconclusive("No resources are available for this unit test.");
      }


      public static void InconclusiveBecauseFileNotFound(string fullPath)
      {
         Inconclusive("The file system object was not found: " + fullPath);
      }


      public static void ThrowsException<T>(Action action, string findString = null)
      {
         Exception exception = null;
         var message = string.Empty;
         var expectedException = typeof(T);

         try
         {
            action();
         }
         catch (Exception ex)
         {
            exception = ex;
            message = ex.Message;
         }


         var gotException = null != exception && exception.GetType() == expectedException;


         if (null != exception)
            Console.WriteLine("\n\t[{0}]{1} {2}: {3}", MethodBase.GetCurrentMethod().Name,

               gotException ? string.Empty : " Caught unexpected",
               gotException ? expectedException.Name : exception.GetType().Name, message.Trim());


         Assert.IsTrue(gotException, "The {0} is not caught, but is expected to.", expectedException.Name);


         if (gotException && !Alphaleonis.Utils.IsNullOrWhiteSpace(findString))
            Assert.IsTrue(message.Contains(findString), "The findString is not found in the exception message, but is expected to.");
      }


      public static bool TestException<T>(Action action)
      {
         Exception exception = null;
         var message = string.Empty;
         var expectedException = typeof(T);

         try
         {
            action();
         }
         catch (Exception ex)
         {
            exception = ex;
            message = ex.Message;
         }


         var gotException = null != exception && exception.GetType() == expectedException;


         if (null != exception)
            Console.WriteLine("\n\t[{0}]{1} {2}: {3}", MethodBase.GetCurrentMethod().Name,

               gotException ? string.Empty : " Caught unexpected",
               gotException ? expectedException.Name : exception.GetType().Name, message.Trim());


         return gotException;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathFileExists.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_Shell32Test
   {
      [TestMethod]
      public void AlphaFS_Shell32_PathFileExists()
      {
         var path = Environment.SystemDirectory;

         Shell32_PathFileExists(path, true);

         Shell32_PathFileExists(Alphaleonis.Win32.Filesystem.Path.LocalToUnc(path), true);

         Shell32_PathFileExists("BlaBlaBla", false);

         Shell32_PathFileExists(System.IO.Path.Combine(Environment.SystemDirectory, "BlaBlaBla"), false);


         foreach (var file in System.IO.Directory.EnumerateFiles(path))

            Assert.IsTrue(Alphaleonis.Win32.Filesystem.Shell32.PathFileExists(file));
      }

      
      private static void Shell32_PathFileExists(string path, bool doesExist)
      {
         var fileExists = Alphaleonis.Win32.Filesystem.Shell32.PathFileExists(path);

         if (doesExist)
            Assert.IsTrue(fileExists);

         if (!doesExist)
            Assert.IsTrue(!fileExists);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.OpenCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.Win32.SafeHandles;
using System.IO;
using System.Security.AccessControl;
using FileStream = System.IO.FileStream;
using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Opens a <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access, the specified sharing option and additional options specified.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.</param>
      /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param>
      /// <param name="share">A <see cref="FileShare"/> value specifying the type of access other threads have to the file.</param>
      /// <param name="attributes">Advanced <see cref="ExtendedFileAttributes"/> options for this file.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The default buffer size is 4096.</param>
      /// <param name="security">The security.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>
      ///   <para>A <see cref="FileStream"/> instance on the specified path, having the specified mode with</para>
      ///   <para>read, write, or read/write access and the specified sharing option.</para>
      /// </returns>
      internal static FileStream OpenCore(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, ExtendedFileAttributes attributes, int? bufferSize, FileSecurity security, PathFormat pathFormat)
      {
         var rights = access == FileAccess.Read ? FileSystemRights.Read : (access == FileAccess.Write ? FileSystemRights.Write : FileSystemRights.Read | FileSystemRights.Write);

         return OpenCore(transaction, path, mode, rights, share, attributes, bufferSize, security, pathFormat);
      }


      /// <summary>Opens a <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access, the specified sharing option and additional options specified.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The file to open.</param>
      /// <param name="mode">A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.</param>
      /// <param name="rights">A <see cref="FileSystemRights"/> value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten along with additional options.</param>
      /// <param name="share">A <see cref="FileShare"/> value specifying the type of access other threads have to the file.</param>
      /// <param name="attributes">Advanced <see cref="ExtendedFileAttributes"/> options for this file.</param>
      /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The default buffer size is 4096.</param>
      /// <param name="security">The security.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>
      ///   <para>A <see cref="FileStream"/> instance on the specified path, having the specified mode with</para>
      ///   <para>read, write, or read/write access and the specified sharing option.</para>
      /// </returns>
      [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
      internal static FileStream OpenCore(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, ExtendedFileAttributes attributes, int? bufferSize, FileSecurity security, PathFormat pathFormat)
      {
         var access = ((rights & FileSystemRights.ReadData) != 0 ? FileAccess.Read : 0) |
                      ((rights & FileSystemRights.WriteData) != 0 || (rights & FileSystemRights.AppendData) != 0 ? FileAccess.Write : 0);


         SafeFileHandle safeHandle = null;

         try
         {
            safeHandle = CreateFileCore(transaction, false, path, attributes, security, mode, rights, share, true, false, pathFormat);

            return new FileStream(safeHandle, access, bufferSize ?? NativeMethods.DefaultFileBufferSize, (attributes & ExtendedFileAttributes.Overlapped) != 0);
         }
         catch
         {
            if (null != safeHandle && !safeHandle.IsClosed)
               safeHandle.Close();

            throw;
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Native Methods/NativeMethods.DistributedFileSystem.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>Enumerates the Distributed File System (DFS) namespaces hosted on a server or DFS links of a namespace hosted by a server.</summary>
      /// <returns>
      /// If the function succeeds, the return value is NERR_Success.
      /// If the function fails, the return value is a system error code.
      /// </returns>
      /// <remarks>
      /// <para>No special group membership is required for using the NetDfsEnum function.</para>
      /// <para>Minimum supported client: Windows Vista</para>
      /// <para>Minimum supported server: Windows Server 2003</para>
      /// </remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("netapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint NetDfsEnum([MarshalAs(UnmanagedType.LPWStr)] string dfsName, [MarshalAs(UnmanagedType.U4)] uint level, [MarshalAs(UnmanagedType.U4)] int prefMaxLen, out SafeGlobalMemoryBufferHandle buffer, [MarshalAs(UnmanagedType.U4)] out uint entriesRead, [MarshalAs(UnmanagedType.U4)] out uint resumeHandle);

      
      /// <summary>Retrieves information about a Distributed File System (DFS) root or link from the cache maintained by the DFS client.</summary>
      /// <returns>
      /// If the function succeeds, the return value is NERR_Success.
      /// If the function fails, the return value is a system error code.
      /// </returns>
      /// <remarks>
      /// <para>No special group membership is required for using the NetDfsGetClientInfo function.</para>
      /// <para>Minimum supported client: Windows Vista</para>
      /// <para>Minimum supported server: Windows Server 2003</para>
      /// </remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("netapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint NetDfsGetClientInfo([MarshalAs(UnmanagedType.LPWStr)] string dfsEntryPath, [MarshalAs(UnmanagedType.LPWStr)] string serverName, [MarshalAs(UnmanagedType.LPWStr)] string shareName, [MarshalAs(UnmanagedType.U4)] uint level, out SafeGlobalMemoryBufferHandle buffer);

      
      /// <summary>Retrieves information about a specified Distributed File System (DFS) root or link in a DFS namespace.</summary>
      /// <returns>
      /// If the function succeeds, the return value is NERR_Success.
      /// If the function fails, the return value is a system error code.
      /// </returns>
      /// <remarks>
      /// <para>No special group membership is required for using the NetDfsGetInfo function.</para>
      /// <para>Minimum supported client: Windows Vista</para>
      /// <para>Minimum supported server: Windows Server 2003</para>
      /// </remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("netapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint NetDfsGetInfo([MarshalAs(UnmanagedType.LPWStr)] string dfsEntryPath, [MarshalAs(UnmanagedType.LPWStr)] string serverName, [MarshalAs(UnmanagedType.LPWStr)] string shareName, [MarshalAs(UnmanagedType.U4)] uint level, out SafeGlobalMemoryBufferHandle buffer);
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.SetVolumeLabel.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_VolumeTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Volume_SetVolumeLabel_Local_Success()
      {
         UnitTestAssert.IsElevatedProcess();
         UnitTestConstants.PrintUnitTestHeader(false);
         
         const string newLabel = "ÂĽpĥæƑŞ ŠëtVőlümèĻāßƩl() Ťest";
         const string template = "System Drive: [{0}]\tCurrent Label: [{1}]\n";
         var drive = UnitTestConstants.SysDrive;


         #region Get Label

         var originalLabel = Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive);
         Console.WriteLine(template, drive, originalLabel);

         Assert.IsTrue(originalLabel.Equals(Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive)));

         #endregion // Get Label


         #region Set Label

         var isLabelSet = false;
         var currentLabel = Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive);
         try
         {
            Alphaleonis.Win32.Filesystem.Volume.SetVolumeLabel(drive, newLabel);
            isLabelSet = true;

            Console.WriteLine(template, drive, newLabel);
            Console.WriteLine("Set label.");
            Assert.IsTrue(!currentLabel.Equals(newLabel));
         }
         catch (Exception ex)
         {
            Console.WriteLine("\nCaught (UNEXPECTED) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
         }
         Assert.IsTrue(isLabelSet);

         #endregion // Set Label


         #region Remove Label

         var isLabelRemoved = false;
         try
         {
            Alphaleonis.Win32.Filesystem.Volume.DeleteVolumeLabel(drive);
            isLabelRemoved = true;

            currentLabel = Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive);

            Console.WriteLine(template, drive, currentLabel);
            Console.WriteLine("Removed label.");
            Assert.IsTrue(currentLabel.Equals(string.Empty));
         }
         catch (Exception ex)
         {
            Console.WriteLine("\nCaught (UNEXPECTED) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
         }
         Assert.IsTrue(isLabelRemoved);

         #endregion // Remove Label


         #region Restore Label

         isLabelSet = false;
         try
         {
            Alphaleonis.Win32.Filesystem.Volume.SetVolumeLabel(drive, originalLabel);
            isLabelSet = true;

            currentLabel = Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive);

            Console.WriteLine(template, drive, currentLabel);
            Console.WriteLine("Restored label.");
            Assert.IsTrue(currentLabel.Equals(originalLabel));
         }
         catch (Exception ex)
         {
            Console.WriteLine("\nCaught (UNEXPECTED) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
         }
         Assert.IsTrue(isLabelSet);

         #endregion // Restore Label
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.GetCurrentDirectory.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class Directory_CurrentDirectoryTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void Directory_GetCurrentDirectory_LocalAndNetwork_Success()
      {
         Directory_GetCurrentDirectory(false);
         Directory_GetCurrentDirectory(true);
      }


      private void Directory_GetCurrentDirectory(bool isNetwork)
      {
         UnitTestConstants.PrintUnitTestHeader(isNetwork);

         // #1
         var tempPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
         if (isNetwork)
            tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);


         System.IO.Directory.SetCurrentDirectory(tempPath);

         
         var sysIoCurrPath = System.IO.Directory.GetCurrentDirectory();
         var alphaFSCurrPath = Alphaleonis.Win32.Filesystem.Directory.GetCurrentDirectory();

         Console.WriteLine("\tSystem.IO Current Directory Path: [{0}]", sysIoCurrPath);
         Console.WriteLine("\tAlphaFS   Current Directory Path: [{0}]", alphaFSCurrPath);

         Assert.AreEqual(sysIoCurrPath, alphaFSCurrPath, "The current directories do not match, but are expected to.");
         

         // #2
         tempPath = Environment.SystemDirectory;
         if (isNetwork)
            tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);


         System.IO.Directory.SetCurrentDirectory(tempPath);


         sysIoCurrPath = System.IO.Directory.GetCurrentDirectory();
         alphaFSCurrPath = Alphaleonis.Win32.Filesystem.Directory.GetCurrentDirectory();

         Console.WriteLine("\n\tSystem.IO Current Directory Path: [{0}]", sysIoCurrPath);
         Console.WriteLine("\tAlphaFS   Current Directory Path: [{0}]", alphaFSCurrPath);

         Assert.AreEqual(sysIoCurrPath, alphaFSCurrPath, "The current directories do not match, but are expected to.");


         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetFullPathCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>Retrieves the absolute path for the specified <paramref name="path"/> string.</summary>
      /// <returns>The fully qualified location of <paramref name="path"/>, such as "C:\MyFile.txt".</returns>
      /// <remarks>
      /// <para>GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file.</para>
      /// <para>It also calculates the address of the file name portion of the full path and file name.</para>
      /// <para>&#160;</para>
      /// <para>This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume.</para>
      /// <para>The .NET Framework does not support direct access to physical disks through paths that are device names, such as <c>\\.\PhysicalDrive0</c>.</para>
      /// <para>&#160;</para>
      /// <para>MSDN: Multithreaded applications and shared library code should not use the GetFullPathName function and</para>
      /// <para>should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,</para>
      /// <para>therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.</para>
      /// <para>This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread,</para>
      /// <para>for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
      /// <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="checkSupported"></param>
      /// <param name="path">The file or directory for which to obtain absolute path information.</param>
      /// <param name="options">Options for controlling the full path retrieval.</param>
      [SecurityCritical]
      internal static string GetFullPathCore(KernelTransaction transaction, bool checkSupported, string path, GetFullPathOptions options)
      {
         // Skip the special paths recognised by Windows kernel only.

         if (null != path)
         {
            if (path.StartsWith(GlobalRootPrefix, StringComparison.OrdinalIgnoreCase) ||
                path.StartsWith(VolumePrefix, StringComparison.OrdinalIgnoreCase) ||
                path.StartsWith(NonInterpretedPathPrefix, StringComparison.Ordinal))

               return path;


            if (checkSupported)
            {
               CheckInvalidUncPath(path);

               CheckSupportedPathFormat(path, true, true);
            }
         }


         if (options != GetFullPathOptions.None)
         {
            if (!checkSupported && (options & GetFullPathOptions.CheckInvalidPathChars) != 0)
            {
               var checkAdditional = (options & GetFullPathOptions.CheckAdditional) != 0;

               CheckInvalidPathChars(path, checkAdditional, false);
               

               // Prevent duplicate checks.
               options &= ~GetFullPathOptions.CheckInvalidPathChars;

               if (checkAdditional)
                  options &= ~GetFullPathOptions.CheckAdditional;
            }

            // Do not remove trailing directory separator when path points to a drive like: "C:\"
            // Doing so makes path point to the current directory.

            // ".", "C:", "C:\"
            if (null == path || path.Length <= 3 || !path.StartsWith(LongPathPrefix, StringComparison.Ordinal) && path[1] != VolumeSeparatorChar)
               options &= ~GetFullPathOptions.RemoveTrailingDirectorySeparator;
         }
         

         var pathLp = GetLongPathCore(path, options);

         uint bufferSize = NativeMethods.MaxPathUnicode;

         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
         {
         
      startGetFullPathName:

            var buffer = new StringBuilder((int) bufferSize);

            var returnLength = null == transaction || !NativeMethods.IsAtLeastWindowsVista

               // GetFullPathName() / GetFullPathNameTransacted()
               // 2013-04-15: MSDN confirms LongPath usage.

               ? NativeMethods.GetFullPathName(pathLp, bufferSize, buffer, IntPtr.Zero)

               : NativeMethods.GetFullPathNameTransacted(pathLp, bufferSize, buffer, IntPtr.Zero, transaction.SafeHandle);


            if (returnLength != Win32Errors.NO_ERROR)
            {
               if (returnLength > bufferSize)
               {
                  bufferSize = returnLength;
                  goto startGetFullPathName;
               }
            }

            else
            {
               if ((options & GetFullPathOptions.ContinueOnNonExist) != 0)
                  return null;

               NativeError.ThrowException(returnLength, pathLp);
            }


            var finalFullPath = (options & GetFullPathOptions.AsLongPath) != 0 ? GetLongPathCore(buffer.ToString(), GetFullPathOptions.None) : GetRegularPathCore(buffer.ToString(), GetFullPathOptions.None, false);
            
            finalFullPath = NormalizePath(finalFullPath, options);
            

            if ((options & GetFullPathOptions.KeepDotOrSpace) != 0)
            {
               if (pathLp.EndsWith(CurrentDirectoryPrefix, StringComparison.Ordinal))

                  finalFullPath += CurrentDirectoryPrefix;


               var lastChar = pathLp[pathLp.Length - 1];

               if (char.IsWhiteSpace(lastChar))

                  finalFullPath += lastChar;
            }


            return finalFullPath;
         }
      }


      /// <summary>Applies the <seealso cref="GetFullPathOptions"/> to <paramref name="path"/>.</summary>
      /// <returns><paramref name="path"/> with applied <paramref name="options"/>.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="path"></param>
      /// <param name="options"></param>
      private static string ApplyFullPathOptions(string path, GetFullPathOptions options)
      {
         if ((options & GetFullPathOptions.TrimEnd) != 0)
            if ((options & GetFullPathOptions.KeepDotOrSpace) == 0)
               path = path.TrimEnd();

         if ((options & GetFullPathOptions.AddTrailingDirectorySeparator) != 0)
            path = AddTrailingDirectorySeparator(path, false);

         if ((options & GetFullPathOptions.RemoveTrailingDirectorySeparator) != 0)
            path = RemoveTrailingDirectorySeparator(path);

         if ((options & GetFullPathOptions.CheckInvalidPathChars) != 0)
            CheckInvalidPathChars(path, (options & GetFullPathOptions.CheckAdditional) != 0, false);


         // Trim leading whitespace.
         if ((options & GetFullPathOptions.KeepDotOrSpace) == 0)
            path = path.TrimStart();

         return path;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_EnableEncryption_And_DisableEncryption.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_EncryptionTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_EnableEncryption_And_DisableEncryption_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_EnableEncryption_And_DisableEncryption(false);
         AlphaFS_Directory_EnableEncryption_And_DisableEncryption(true);

      }


      private void AlphaFS_Directory_EnableEncryption_And_DisableEncryption(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.CreateDirectory();

            Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName);


            var deskTopIni = System.IO.Path.Combine(folder.FullName, "Desktop.ini");
            var enabled = new[] {"[Encryption]", "Disable=0"};
            var disabled = new[] {"[Encryption]", "Disable=1"};


            // Enable.
            Alphaleonis.Win32.Filesystem.Directory.EnableEncryption(folder.FullName);
            

            // Read Desktop.ini file.
            var collection = System.IO.File.ReadAllLines(deskTopIni);

            for (int i = 0, l = collection.Length; i < l; i++)
               Console.WriteLine("\t" + collection[i]);
            Console.WriteLine();

            CollectionAssert.AreEqual(enabled, collection);




            // Disable.
            Alphaleonis.Win32.Filesystem.Directory.DisableEncryption(folder.FullName);


            // Read Desktop.ini file.
            collection = System.IO.File.ReadAllLines(deskTopIni);

            for (int i = 0, l = collection.Length; i < l; i++)
               Console.WriteLine("\t" + collection[i]);

            CollectionAssert.AreEqual(disabled, collection);
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetFinalPathNameByHandle/AlphaFS_Path.GetFinalPathNameByHandle_ToGetFileStreamName.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class PathTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Path_GetFinalPathNameByHandle_ToGetFileStreamName_Success()
      {
         // Issue #438, filestream name.
         // AlphaFS implementation of fileStream.Name returns = "[Unknown]"
         // System.IO returns the full path.


         using (var tempRoot = new TemporaryDirectory())
         {
            var file = tempRoot.CreateFile();

            Console.WriteLine("Input File Path: [{0}]\n", file.FullName);

            string sysIoStreamName;
            using (var fs = file.Create())
               sysIoStreamName = fs.Name;
            

            using (var fs = Alphaleonis.Win32.Filesystem.File.Create(file.FullName))
            {
               var fileStreamName = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(fs.SafeFileHandle);

               fileStreamName = Alphaleonis.Win32.Filesystem.Path.GetRegularPath(fileStreamName);


               Console.WriteLine("\tSystem.IO Filestream Name: " + sysIoStreamName);

               Console.WriteLine("\tAlphaFS   Filestream Name: " + fileStreamName);


               Assert.AreEqual("[Unknown]", fs.Name);

               Assert.AreEqual(sysIoStreamName, fileStreamName);
            }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetExtensionCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>Returns the extension of the specified path string.</summary>
      /// <returns>
      ///   <para>The extension of the specified path (including the period "."), or null, or <see cref="string.Empty"/>.</para>
      ///   <para>If <paramref name="path"/> is null, this method returns null.</para>
      ///   <para>If <paramref name="path"/> does not have extension information,
      ///   this method returns <see cref="string.Empty"/>.</para>
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <param name="path">The path string from which to get the extension. The path cannot contain any of the characters defined in <see cref="GetInvalidPathChars"/>.</param>
      /// <param name="checkInvalidPathChars"><c>true</c> will check <paramref name="path"/> for invalid path characters.</param>
      [SecurityCritical]
      internal static string GetExtensionCore(string path, bool checkInvalidPathChars)
      {
         if (null == path)
            return null;

         if (checkInvalidPathChars)
            CheckInvalidPathChars(path, false, true);

         var length = path.Length;
         var index = length;

         while (--index >= 0)
         {
            var ch = path[index];

            if (ch == ExtensionSeparatorChar)
               return index != length - 1 ? path.Substring(index, length - index) : string.Empty;

            if (IsDVsc(ch, null))
               break;
         }

         return string.Empty;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.GetSizeCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.Win32.SafeHandles;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Retrieves the size of the specified file.</summary>
      /// <returns>The file size of the first or all streams, in bytes.</returns>
      /// <remarks>Use either <paramref name="path"/> or <paramref name="safeFileHandle"/>, not both.</remarks>
      /// <param name="safeFileHandle">The <see cref="SafeFileHandle"/> to the file.</param>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The path to the file.</param>
      /// <param name="sizeOfAllStreams"><c>true</c> to retrieve the size of all alternate data streams, <c>false</c> to get the size of the first stream.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
      [SecurityCritical]
      internal static long GetSizeCore(SafeFileHandle safeFileHandle, KernelTransaction transaction, string path, bool sizeOfAllStreams, PathFormat pathFormat)
      {
         var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

         if (sizeOfAllStreams)
            return FindAllStreamsCore(transaction, pathLp);


         var callerHandle = null != safeFileHandle;

         if (!callerHandle)
            safeFileHandle = CreateFileCore(transaction, false, pathLp, ExtendedFileAttributes.Normal, null, FileMode.Open, FileSystemRights.ReadData, FileShare.ReadWrite, true, false, PathFormat.LongFullPath);
         
         long fileSize;

         try
         {
            var success = NativeMethods.GetFileSizeEx(safeFileHandle, out fileSize);

            var lastError = Marshal.GetLastWin32Error();

            if (!success && lastError != Win32Errors.ERROR_SUCCESS)
               NativeError.ThrowException(lastError, path);
         }
         finally
         {
            // Handle is ours, dispose.
            if (!callerHandle && null != safeFileHandle && !safeFileHandle.IsClosed)
               safeFileHandle.Close();
         }

         return fileSize;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/AlphaFS_DirectoryInfo.MoveTo_DelayUntilReboot.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation directorys (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Microsoft.Win32;

namespace AlphaFS.UnitTest
{
   public partial class MoveTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>

      
      [TestMethod]
      public void AlphaFS_DirectoryInfo_MoveTo_DelayUntilReboot_Local_Success()
      {
         UnitTestAssert.IsElevatedProcess();

         AlphaFS_DirectoryInfo_MoveTo_DelayUntilReboot(false);
      }

      
      private void AlphaFS_DirectoryInfo_MoveTo_DelayUntilReboot(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(tempRoot.RandomDirectoryFullPath);

            var pendingEntry = folder.FullName;

            Console.WriteLine("Src Directory Path: [{0}]", pendingEntry);


            if (isNetwork)
               // Trigger DelayUntilReboot.
               UnitTestAssert.ThrowsException<ArgumentException>(() => folder.MoveTo(null, Alphaleonis.Win32.Filesystem.MoveOptions.DelayUntilReboot));
            
            else
            {
               // Trigger DelayUntilReboot.
               folder.MoveTo(null, Alphaleonis.Win32.Filesystem.MoveOptions.DelayUntilReboot);


               // Verify DelayUntilReboot in registry.

               var pendingList = (string[]) Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager", "PendingFileRenameOperations", null);


               Assert.IsNotNull(pendingList, "The PendingFileRenameOperations is null, but is not expected to.");


               var found = false;

               foreach (var line in pendingList)
               {
                  found = !Alphaleonis.Utils.IsNullOrWhiteSpace(line) && line.Replace(pendingEntry, string.Empty).Equals(Alphaleonis.Win32.Filesystem.Path.NonInterpretedPathPrefix, StringComparison.Ordinal);

                  if (found)
                  {
                     Console.WriteLine("\n\tPending entry found in registry: [{0}]", line);

                     // TODO: Remove unit test entry from registry.

                     break;
                  }
               }


               Assert.IsTrue(found, "Registry does not contain pending entry, but is expected to.");
            }
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_FileSystemEntryInfoTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_GetFileSystemEntryInfo_LogicalDrives_Local_Success()
      {
         AlphaFS_Directory_GetFileSystemEntryInfo_LogicalDrives();
      }


      private void AlphaFS_Directory_GetFileSystemEntryInfo_LogicalDrives()
      {
         UnitTestConstants.PrintUnitTestHeader(false);
         
         var drives = Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives().ToArray();

         foreach (var driveInfo in drives)
         {
            Console.WriteLine("Input Logical Drive: [{0}]", driveInfo.Name);

            try
            { 
               var fsei = Alphaleonis.Win32.Filesystem.Directory.GetFileSystemEntryInfo(driveInfo.Name);

               UnitTestConstants.Dump(fsei);


               Assert.IsTrue(fsei.GetType().IsEquivalentTo(typeof(Alphaleonis.Win32.Filesystem.FileSystemEntryInfo)));
               Assert.IsTrue((fsei.Attributes & System.IO.FileAttributes.Directory) != 0, "The Directory attribute is not found, but is expected.");


               // Fixed local drives should have these attributes.
               if (new Alphaleonis.Win32.Filesystem.DriveInfo(driveInfo.Name).DriveType == System.IO.DriveType.Fixed)
               {
                  Assert.IsTrue((fsei.Attributes & System.IO.FileAttributes.Hidden) != 0, "The Hidden attribute is not found, but is expected.");
                  Assert.IsTrue((fsei.Attributes & System.IO.FileAttributes.System) != 0, "The System attribute is not found, but is expected.");
               }


               Assert.AreEqual(".", fsei.FileName, "The file names are not equal, but are expected to be.");
               Assert.AreEqual(driveInfo.Name, fsei.FullPath, "The full paths are not equal, but are expected to be.");
            }
            catch (Exception ex)
            {
               Console.WriteLine("\n\tCaught UNEXPECTED Exception: [{0}] {1}", ex.GetType().Name, ex.Message);
            }


            Console.WriteLine();
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File CopyMove/File.CopyMoveNative.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      // Symbolic Link Effects on File Systems Functions: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365682(v=vs.85).aspx


      // MSDN: If lpProgressRoutine returns PROGRESS_CANCEL due to the user canceling the operation,
      // CopyFileEx will return zero and GetLastError will return ERROR_REQUEST_ABORTED.
      // In this case, the partially copied destination file is deleted.
      //
      // If lpProgressRoutine returns PROGRESS_STOP due to the user stopping the operation,
      // CopyFileEx will return zero and GetLastError will return ERROR_REQUEST_ABORTED.
      // In this case, the partially copied destination file is left intact.


      // Note: MoveFileXxx fails if one of the paths is a UNC path, even though both paths refer to the same volume.
      // For example, src = C:\TempSrc and dst = \\localhost\C$\TempDst

      // MoveFileXxx fails if it cannot access the registry. The function stores the locations of the files to be renamed at restart in the following registry value:
      //
      //    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations
      //
      // This registry value is of type REG_MULTI_SZ. Each rename operation stores one of the following NULL-terminated strings, depending on whether the rename is a delete or not:
      //
      //    szDstFile\0\0              : indicates that the file szDstFile is to be deleted on reboot.
      //    szSrcFile\0szDstFile\0     : indicates that szSrcFile is to be renamed szDstFile on reboot.


      [SecurityCritical]
      private static bool CopyMoveNative(CopyMoveArguments cma, bool isMove, string sourcePathLp, string destinationPathLp, out bool cancel, out int lastError)
      {
         cancel = false;

         var success = null == cma.Transaction || !NativeMethods.IsAtLeastWindowsVista

            // CopyFileEx() / CopyFileTransacted() / MoveFileWithProgress() / MoveFileTransacted()
            // 2013-04-15: MSDN confirms LongPath usage.


            ? isMove
               ? NativeMethods.MoveFileWithProgress(sourcePathLp, destinationPathLp, cma.Routine, IntPtr.Zero, (MoveOptions) cma.MoveOptions)

               : NativeMethods.CopyFileEx(sourcePathLp, destinationPathLp, cma.Routine, IntPtr.Zero, out cancel, (CopyOptions) cma.CopyOptions)

            : isMove
               ? NativeMethods.MoveFileTransacted(sourcePathLp, destinationPathLp, cma.Routine, IntPtr.Zero, (MoveOptions) cma.MoveOptions, cma.Transaction.SafeHandle)

               : NativeMethods.CopyFileTransacted(sourcePathLp, destinationPathLp, cma.Routine, IntPtr.Zero, out cancel, (CopyOptions) cma.CopyOptions, cma.Transaction.SafeHandle);


         lastError = Marshal.GetLastWin32Error();


         return success;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory.Exists/Directory.Exists_UseCases.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class ExistsTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void Directory_Exists_UseCases_LocalAndNetwork_Success()
      {
         Directory_Exists_UseCases(false);
         Directory_Exists_UseCases(true);
      }


      private void Directory_Exists_UseCases(bool isNetwork)
      {
         // Issue #288: Directory.Exists on root drive problem has come back with recent updates
         

         using (var tempRoot = new TemporaryDirectory())
         {
            System.IO.Directory.SetCurrentDirectory(tempRoot.Directory.FullName);


            var sysDrive = UnitTestConstants.SysDrive + @"\";
            if (isNetwork)
               sysDrive = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(sysDrive);


            var randomName = tempRoot.RandomDirectoryName;

            // C:\randomName
            var NonExistingFolder1 = UnitTestConstants.SysDrive + @"\" + randomName;

            // C:randomName
            var NonExistingFolder2 = UnitTestConstants.SysDrive + randomName;


            // C:\randomName-exists
            var existingFolder1 = NonExistingFolder1 + "-exists";
            System.IO.Directory.CreateDirectory(existingFolder1);

            // C:randomName-exists
            var existingFolder2 = NonExistingFolder2 + "-exists";
            System.IO.Directory.CreateDirectory(existingFolder2);



            if (isNetwork)
            {
               NonExistingFolder1 = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(NonExistingFolder1);
               NonExistingFolder2 = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(NonExistingFolder2);

               existingFolder1 = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(existingFolder1);
               existingFolder2 = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(existingFolder2);
            }


            // Some use cases.
            var paths = new Dictionary<string, List<bool>>
            {
               {NonExistingFolder1, new List<bool> {false, false}},
               {NonExistingFolder2, new List<bool> {false, false}},
               {NonExistingFolder1 + @"\", new List<bool> {false, false}},
               {NonExistingFolder2 + @"\", new List<bool> {false, false}},

               {existingFolder1, new List<bool> {true, true}},
               {existingFolder2, new List<bool> {!isNetwork, !isNetwork}},
               {existingFolder1 + @"\", new List<bool> {true, true}},
               {existingFolder2 + @"\", new List<bool> {!isNetwork, !isNetwork}}
            };


            System.IO.Directory.SetCurrentDirectory(sysDrive);

            Console.WriteLine("Current directory: " + System.IO.Directory.GetCurrentDirectory());


            foreach (var path in paths)
            {
               var sysIOshouldBe = path.Value[0];
               var alphaFSshouldBe = path.Value[1];
               var inputPath = path.Key;

               var existSysIO = System.IO.Directory.Exists(inputPath);
               var existAlpha = Alphaleonis.Win32.Filesystem.Directory.Exists(inputPath);


               Console.WriteLine("\n\tSystem.IO   (should be {0}):\t[{1}]\t\tdirectory= {2}", sysIOshouldBe.ToString().ToUpperInvariant(), existSysIO, inputPath);
               Console.WriteLine("\tAlphaFS     (should be {0}):\t[{1}]\t\tdirectory= {2}", alphaFSshouldBe.ToString().ToUpperInvariant(), existAlpha, inputPath);


               Assert.AreEqual(sysIOshouldBe, existSysIO);

               Assert.AreEqual(alphaFSshouldBe, existAlpha);

               Assert.AreEqual(sysIOshouldBe, alphaFSshouldBe);
            }


            System.IO.Directory.Delete(existingFolder1);

            if (System.IO.Directory.Exists(existingFolder2))
               System.IO.Directory.Delete(existingFolder2);
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/UnitTests/AlphaFS_DfsInfoTest.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Network;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using System.Net.NetworkInformation;

namespace AlphaFS.UnitTest
{
   /// <summary>This is a test class for all DfsInfo class Unit Tests.</summary>
   [TestClass]
   public class AlphaFS_DfsInfoTest
   {
      [TestMethod]
      public void AlphaFS_DfsInfo()
      {
         var cnt = 0;
         var noDomainConnection = true;

         try
         {
            foreach (var dfsNamespace in Host.EnumerateDomainDfsRoot())
            {
               noDomainConnection = false;

               try
               {
                  Console.Write("\n#{0:000}\tDFS Root: [{1}]\n", ++cnt, dfsNamespace);

                  var dfsInfo = Host.GetDfsInfo(dfsNamespace);

                  UnitTestConstants.Dump(dfsInfo);


                  Console.Write("\n\tNumber of Storages: [{0}]\n", dfsInfo.StorageInfoCollection.Count());

                  foreach (var store in dfsInfo.StorageInfoCollection)
                     UnitTestConstants.Dump(store);

                  Console.WriteLine();
               }
               catch (NetworkInformationException ex)
               {
                  Console.WriteLine("\n\tNetworkInformationException #1: [{0}]", ex.Message.Replace(Environment.NewLine, "  "));
               }
               catch (Exception ex)
               {
                  Console.WriteLine("\n\t(1) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
               }
            }

            if (cnt == 0)
               UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable();
         }
         catch (NetworkInformationException ex)
         {
            Console.WriteLine("\n\tNetworkInformationException #2: [{0}]", ex.Message.Replace(Environment.NewLine, "  "));
         }
         catch (Exception ex)
         {
            Console.WriteLine("\n\t(2) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
         }


         if (noDomainConnection)
            UnitTestAssert.Inconclusive("Test ignored because the computer is either not connected to a domain or no DFS root exists.");

         if (cnt == 0)
            UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable();

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/FileInfo Class/FileInfo CopyToMoveTo/FileInfo.CopyToMoveToCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   partial class FileInfo
   {
      /// <summary>Copy/move an existing file to a new file, allowing the overwriting of an existing file.</summary>
      /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Copy or Move action.</returns>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <param name="destinationPath"><para>A full path string to the destination directory</para></param>
      /// <param name="copyOptions"><para>This parameter can be <c>null</c>. Use <see cref="CopyOptions"/> to specify how the file is to be copied.</para></param>
      /// <param name="moveOptions"><para>This parameter can be <c>null</c>. Use <see cref="MoveOptions"/> that specify how the file is to be moved.</para></param>
      /// <param name="preserveDates"><c>true</c> if original Timestamps must be preserved, <c>false</c> otherwise.</param>
      /// <param name="progressHandler"><para>This parameter can be <c>null</c>. A callback function that is called each time another portion of the file has been copied.</para></param>
      /// <param name="userProgressData"><para>This parameter can be <c>null</c>. The argument to be passed to the callback function.</para></param>
      /// <param name="longFullPath">[out] Returns the retrieved long full path.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      [SecurityCritical]
      private CopyMoveResult CopyToMoveToCore(string destinationPath, CopyOptions? copyOptions, MoveOptions? moveOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, out string longFullPath, PathFormat pathFormat)
      {
         longFullPath = Path.GetExtendedLengthPathCore(Transaction, destinationPath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

         return File.CopyMoveCore(false, new CopyMoveArguments
         {
            Transaction = Transaction,
            CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp,
            MoveOptions = moveOptions,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData,
            PathFormat = PathFormat.LongFullPath

         }, false, false, LongFullName, longFullPath, null);
      }


      /// <summary>Refreshes the current <see cref="FileInfo"/> instance with a new destination path.</summary>
      private void UpdateDestinationPath(string destinationPath, string destinationPathLp)
      {
         _name = Path.GetFileName(destinationPathLp, true);

         UpdateSourcePath(destinationPath, destinationPathLp);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/File.Open/File_Open_OverlappedIO.cs<|end_filename|>
///*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
// *  
// *  Permission is hereby granted, free of charge, to any person obtaining a copy 
// *  of this software and associated documentation files (the "Software"), to deal 
// *  in the Software without restriction, including without limitation the rights 
// *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
// *  copies of the Software, and to permit persons to whom the Software is 
// *  furnished to do so, subject to the following conditions:
// *  
// *  The above copyright notice and this permission notice shall be included in 
// *  all copies or substantial portions of the Software.
// *  
// *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
// *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
// *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
// *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
// *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
// *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
// *  THE SOFTWARE. 
// */

//using Microsoft.VisualStudio.TestTools.UnitTesting;
//using System;
//using System.Reflection;

//namespace AlphaFS.UnitTest
//{
//   partial class FileTest
//   {
//      // Pattern: <class>_<function>_<scenario>_<expected result>


//      [TestMethod]
//      public void File_Open_OverlappedIO_LocalAndNetwork_Success()
//      {
//         // https://gist.github.com/mattpodwysocki/1862069
//         // https://gist.github.com/PaulStovell/1696375


//         File_Open_OverlappedIO(false);
//         File_Open_OverlappedIO(true);
//      }
      

//      private void File_Open_OverlappedIO(bool isNetwork)
//      {
//         UnitTestConstants.PrintUnitTestHeader(isNetwork);

//         var tempPath = UnitTestConstants.TempPath;
//         if (isNetwork)
//            tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);


//         using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name))
//         {
//            var file = rootDir.RandomTxtFileFullPath;
//            Console.WriteLine("\nInput File Path: [{0}]", file);


//            long fileLength;
//            var ten = UnitTestConstants.TenNumbers.Length;

//            using (var fs = Alphaleonis.Win32.Filesystem.File.Open(file, System.IO.FileMode.Create,
//               System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite, 4096,
//               Alphaleonis.Win32.Filesystem.ExtendedFileAttributes.Overlapped,
//               Alphaleonis.Win32.Filesystem.PathFormat.FullPath))
//            {
//               // According to NotePad++, creates a file type: "ANSI", which is reported as: "Unicode (UTF-8)".
//               fs.Write(UnitTestConstants.StringToByteArray(UnitTestConstants.TenNumbers), 0, ten);

//               fileLength = fs.Length;
//            }

//            Assert.IsTrue(System.IO.File.Exists(file), "The file does not exists, but is expected to.");
//            Assert.IsTrue(fileLength == ten, "The file is: {0} bytes, but is expected to be: {1} bytes.", fileLength, ten);
//         }

//         Console.WriteLine();
//      }
//   }
//}


<|start_filename|>src/AlphaFS/Network/Native Other/STAT_SERVER_0.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>Contains statistical information about the server.</summary>
      /// <remarks>
      /// <para>Minimum supported client: Windows XP [desktop apps only]</para>
      /// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
      /// </remarks>
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      internal struct STAT_SERVER_0
      {
         /// <summary>
         /// <para>Specifies a DWORD value that indicates the time when statistics collection started (or when the statistics were last cleared).</para>
         /// <para>The value is stored as the number of seconds that have elapsed since 00:00:00, January 1, 1970, GMT.</para>
         /// <para>To calculate the length of time that statistics have been collected,</para>
         /// <para>subtract the value of this member from the present time.</para>
         /// </summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_start;

         /// <summary>Specifies a DWORD value that indicates the number of times a file is opened on a server. This includes the number of times named pipes are opened.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_fopens;

         /// <summary>Specifies a DWORD value that indicates the number of times a server device is opened.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_devopens;

         /// <summary>Specifies a DWORD value that indicates the number of server print jobs spooled.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_jobsqueued;

         /// <summary>Specifies a DWORD value that indicates the number of times the server session started.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_sopens;

         /// <summary>Specifies a DWORD value that indicates the number of times the server session automatically disconnected.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_stimedout;

         /// <summary>Specifies a DWORD value that indicates the number of times the server sessions failed with an error.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_serrorout;

         /// <summary>Specifies a DWORD value that indicates the number of server password violations.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_pwerrors;

         /// <summary>Specifies a DWORD value that indicates the number of server access permission errors.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_permerrors;

         /// <summary>Specifies a DWORD value that indicates the number of server system errors.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_syserrors;

         /// <summary>Specifies the low-order DWORD of the number of server bytes sent to the network.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_bytessent_low;

         /// <summary>Specifies the high-order DWORD of the number of server bytes sent to the network.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_bytessent_high;

         /// <summary>Specifies the low-order DWORD of the number of server bytes received from the network.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_bytesrcvd_low;

         /// <summary>Specifies the high-order DWORD of the number of server bytes received from the network.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_bytesrcvd_high;

         /// <summary>Specifies a DWORD value that indicates the average server response time (in milliseconds).</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_avresponse;

         /// <summary>Specifies a DWORD value that indicates the number of times the server required a request buffer but failed to allocate one. This value indicates that the server parameters may need adjustment.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_reqbufneed;

         /// <summary>Specifies a DWORD value that indicates the number of times the server required a big buffer but failed to allocate one. This value indicates that the server parameters may need adjustment.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_bigbufneed;
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Retrieves the volume mount point where the specified path is mounted.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="path">The path to the volume, for example: "C:\Windows".</param>
      /// <returns>
      ///   <para>Returns the nearest volume root path for a given directory.</para>
      ///   <para>The volume path name, for example: "C:\Windows" returns: "C:\".</para>
      /// </returns>
      [SecurityCritical]
      public static string GetVolumePathName(string path)
      {
         if (Utils.IsNullOrWhiteSpace(path))
            throw new ArgumentNullException("path");


         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
         {
            var volumeRootPath = new StringBuilder(NativeMethods.MaxPathUnicode / 32);
            var pathLp = Path.GetFullPathCore(null, false, path, GetFullPathOptions.AsLongPath | GetFullPathOptions.FullCheck);


            // GetVolumePathName()
            // 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

            var success = NativeMethods.GetVolumePathName(pathLp, volumeRootPath, (uint) volumeRootPath.Capacity);

            var lastError = Marshal.GetLastWin32Error();

            if (success)
               return Path.GetRegularPathCore(volumeRootPath.ToString(), GetFullPathOptions.None, false);


            switch ((uint) lastError)
            {
               // Don't throw exception on these errors.
               case Win32Errors.ERROR_NO_MORE_FILES:
               case Win32Errors.ERROR_INVALID_PARAMETER:
               case Win32Errors.ERROR_INVALID_NAME:
                  break;

               default:
                  NativeError.ThrowException(lastError, path);
                  break;
            }


            // Return original path.
            return path;
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/VolumeInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Contains information about a filesystem Volume.</summary>
   [Serializable]
   [SecurityCritical]
   public sealed class VolumeInfo
   {
      [NonSerialized] private readonly bool _continueOnAccessError;
      [NonSerialized] private readonly SafeFileHandle _volumeHandle;
      [NonSerialized] private NativeMethods.VOLUME_INFO_FLAGS _volumeInfoAttributes;


      /// <summary>Initializes a VolumeInfo instance.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <param name="volumeName">A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z' or a network share in the format: \\server\share.</param>
      [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")]
      [SecurityCritical]
      public VolumeInfo(string volumeName)
      {
         if (Utils.IsNullOrWhiteSpace(volumeName))
            throw new ArgumentNullException("volumeName");


         if (!volumeName.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal))
            volumeName = Path.IsUncPathCore(volumeName, false, false) ? Path.GetLongPathCore(volumeName, GetFullPathOptions.None) : Path.LongPathPrefix + volumeName;

         else
         {
            volumeName = volumeName.Length == 1 ? volumeName + Path.VolumeSeparatorChar : Path.GetPathRoot(volumeName, false);

            if (!volumeName.StartsWith(Path.GlobalRootPrefix, StringComparison.OrdinalIgnoreCase))
               volumeName = Path.GetPathRoot(volumeName, false);
         }


         if (Utils.IsNullOrWhiteSpace(volumeName))
            throw new ArgumentException(Resources.InvalidDriveLetterArgument, "volumeName");


         Name = Path.AddTrailingDirectorySeparator(volumeName, false);

         _volumeHandle = null;
      }


      /// <summary>Initializes a VolumeInfo instance.</summary>
      /// <param name="driveName">A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z' or a network share in the format: "\\server\share".</param>
      /// <param name="refresh">Refreshes the state of the object.</param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public VolumeInfo(string driveName, bool refresh, bool continueOnException) : this(driveName)
      {
         _continueOnAccessError = continueOnException;

         if (refresh)
            Refresh();
      }


      /// <summary>Initializes a VolumeInfo instance.</summary>
      /// <param name="volumeHandle">An instance to a <see cref="SafeFileHandle"/> handle.</param>
      [SecurityCritical]
      public VolumeInfo(SafeFileHandle volumeHandle)
      {
         _volumeHandle = volumeHandle;
      }


      /// <summary>Initializes a VolumeInfo instance.</summary>
      /// <param name="volumeHandle">An instance to a <see cref="SafeFileHandle"/> handle.</param>
      /// <param name="refresh">Refreshes the state of the object.</param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public VolumeInfo(SafeFileHandle volumeHandle, bool refresh, bool continueOnException) : this(volumeHandle)
      {
         _continueOnAccessError = continueOnException;

         if (refresh)
            Refresh();
      }


      

      /// <summary>Refreshes the state of the object.</summary>
      public void Refresh()
      {
         var volumeNameBuffer = new StringBuilder(NativeMethods.MaxPath + 1);
         var fileSystemNameBuffer = new StringBuilder(NativeMethods.MaxPath + 1);
         int maximumComponentLength;
         uint serialNumber;

         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
         {
            // GetVolumeInformationXxx()
            // 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

            uint lastError;

            do
            {
               var success = null != _volumeHandle && NativeMethods.IsAtLeastWindowsVista

                  // GetVolumeInformationByHandle() / GetVolumeInformation()
                  // 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

                  ? NativeMethods.GetVolumeInformationByHandle(_volumeHandle, volumeNameBuffer, (uint) volumeNameBuffer.Capacity, out serialNumber, out maximumComponentLength, out _volumeInfoAttributes, fileSystemNameBuffer, (uint) fileSystemNameBuffer.Capacity)

                  // A trailing backslash is required.
                  : NativeMethods.GetVolumeInformation(Path.AddTrailingDirectorySeparator(Name, false), volumeNameBuffer, (uint) volumeNameBuffer.Capacity, out serialNumber, out maximumComponentLength, out _volumeInfoAttributes, fileSystemNameBuffer, (uint) fileSystemNameBuffer.Capacity);


               lastError = (uint) Marshal.GetLastWin32Error();
               if (!success)
               {
                  switch (lastError)
                  {
                     case Win32Errors.ERROR_NOT_READY:
                        if (!_continueOnAccessError)
                           throw new DeviceNotReadyException(Name, true);
                        break;

                     case Win32Errors.ERROR_MORE_DATA:
                        // With a large enough buffer this code never executes.
                        volumeNameBuffer.Capacity = volumeNameBuffer.Capacity*2;
                        fileSystemNameBuffer.Capacity = fileSystemNameBuffer.Capacity*2;
                        break;

                     default:
                        if (!_continueOnAccessError)
                           NativeError.ThrowException(lastError, Name);
                        break;
                  }
               }

               else
                  break;

            } while (lastError == Win32Errors.ERROR_MORE_DATA);
         }

         FullPath = Path.GetRegularPathCore(Name, GetFullPathOptions.None, false);
         Name = volumeNameBuffer.ToString();

         FileSystemName = fileSystemNameBuffer.ToString();
         FileSystemName = !Utils.IsNullOrWhiteSpace(FileSystemName) ? FileSystemName : null;

         MaximumComponentLength = maximumComponentLength;
         SerialNumber = serialNumber;
      }


      /// <summary>Returns the full path of the volume.</summary>
      /// <returns>A string that represents this instance.</returns>
      public override string ToString()
      {
         return Guid;
      }




      /// <summary>The specified volume supports preserved case of file names when it places a name on disk.</summary>
      public bool CasePreservedNames
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_CASE_PRESERVED_NAMES) != 0; }
      }


      /// <summary>The specified volume supports case-sensitive file names.</summary>
      public bool CaseSensitiveSearch
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_CASE_SENSITIVE_SEARCH) != 0; }
      }


      /// <summary>The specified volume supports file-based compression.</summary>
      public bool Compression
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_FILE_COMPRESSION) != 0; }
      }


      /// <summary>The specified volume is a direct access (DAX) volume.</summary>
      public bool DirectAccess
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_DAX_VOLUME) != 0; }
      }


      /// <summary>Gets the name of the file system, for example, the FAT file system or the NTFS file system.</summary>
      /// <value>The name of the file system.</value>
      public string FileSystemName { get; private set; }


      /// <summary>The full path to the volume.</summary>
      public string FullPath { get; private set; }


      private string _guid;
      /// <summary>The volume GUID.</summary>
      public string Guid
      {
         get
         {
            if (Utils.IsNullOrWhiteSpace(_guid))
               _guid = !Utils.IsNullOrWhiteSpace(FullPath) ? Volume.GetUniqueVolumeNameForPath(FullPath) : null;

            return _guid;
         }
      }


      /// <summary>Gets the maximum length of a file name component that the file system supports.</summary>
      /// <value>The maximum length of a file name component that the file system supports.</value>      
      public int MaximumComponentLength { get; set; }


      /// <summary>Gets the label of the volume.</summary>
      /// <returns>The label of the volume.</returns>
      /// <remarks>This property is the label assigned to the volume, such "MyDrive"</remarks>
      public string Name { get; private set; }


      /// <summary>The specified volume supports named streams.</summary>
      public bool NamedStreams
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_NAMED_STREAMS) != 0; }
      }


      /// <summary>The specified volume preserves and enforces access control lists (ACL).</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Acls")]
      public bool PersistentAcls
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_PERSISTENT_ACLS) != 0; }
      }

      
      /// <summary>The specified volume is read-only.</summary>
      public bool ReadOnlyVolume
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_READ_ONLY_VOLUME) != 0; }
      }

      
      /// <summary>The specified volume supports a single sequential write.</summary>
      public bool SequentialWriteOnce
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SEQUENTIAL_WRITE_ONCE) != 0; }
      }


      /// <summary>Gets the volume serial number that the operating system assigns when a hard disk is formatted.</summary>
      /// <value>The volume serial number that the operating system assigns when a hard disk is formatted.</value>
      public long SerialNumber { get; private set; }


      /// <summary>The specified volume supports the Encrypted File System (EFS).</summary>
      public bool SupportsEncryption
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_ENCRYPTION) != 0; }
      }


      /// <summary>The specified volume supports extended attributes.</summary>
      public bool SupportsExtendedAttributes
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_EXTENDED_ATTRIBUTES) != 0; }
      }


      /// <summary>The specified volume supports hard links.</summary>
      public bool SupportsHardLinks
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_HARD_LINKS) != 0; }
      }


      /// <summary>The specified volume supports object identifiers.</summary>
      public bool SupportsObjectIds
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_OBJECT_IDS) != 0; }
      }


      /// <summary>The file system supports open by FileID.</summary>
      public bool SupportsOpenByFileId
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_OPEN_BY_FILE_ID) != 0; }
      }


      /// <summary>The specified volume supports remote storage. (This property does not appear on MSDN)</summary>
      public bool SupportsRemoteStorage
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_REMOTE_STORAGE) != 0; }
      }


      /// <summary>The specified volume supports re-parse points.</summary>
      public bool SupportsReparsePoints
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_REPARSE_POINTS) != 0; }
      }


      /// <summary>The specified volume supports sparse files.</summary>
      public bool SupportsSparseFiles
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_SPARSE_FILES) != 0; }
      }


      /// <summary>The specified volume supports transactions.</summary>
      public bool SupportsTransactions
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_TRANSACTIONS) != 0; }
      }


      /// <summary>The specified volume supports update sequence number (USN) journals.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usn")]
      public bool SupportsUsnJournal
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_USN_JOURNAL) != 0; }
      }


      /// <summary>The specified volume supports Unicode in file names as they appear on disk.</summary>
      public bool UnicodeOnDisk
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_UNICODE_ON_DISK) != 0; }
      }


      /// <summary>The specified volume is a compressed volume, for example, a DoubleSpace volume.</summary>
      public bool VolumeIsCompressed
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_VOLUME_IS_COMPRESSED) != 0; }
      }


      /// <summary>The specified volume supports disk quotas.</summary>
      public bool VolumeQuotas
      {
         get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_VOLUME_QUOTAS) != 0; }
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_3ExistingFiles_FromVolumeShadowCopy.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class CopyTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_File_Copy_3ExistingFiles_FromVolumeShadowCopy_LocalAndNetwork_Success()
      {
         AlphaFS_File_Copy_3ExistingFiles_FromVolumeShadowCopy(false);
         AlphaFS_File_Copy_3ExistingFiles_FromVolumeShadowCopy(true);
      } 


      private void AlphaFS_File_Copy_3ExistingFiles_FromVolumeShadowCopy(bool isNetwork)
      {
         var testOk = false;
         
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.CreateDirectoryRandomizedAttributes();

            var dosDevices = Alphaleonis.Win32.Filesystem.Volume.QueryAllDosDevices().Where(device => device.StartsWith("HarddiskVolumeShadowCopy", StringComparison.OrdinalIgnoreCase)).ToArray();

            foreach (var dosDevice in dosDevices)
            {
               if (testOk)
                  break;

               var shadowSource = Alphaleonis.Win32.Filesystem.Path.GlobalRootDevicePrefix + dosDevice;

               var sourceFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

               var drive = System.IO.Directory.GetDirectoryRoot(sourceFolder).TrimEnd('\\');

               var globalRoot = sourceFolder.Replace(drive, shadowSource);


               var dirInfo = new Alphaleonis.Win32.Filesystem.DirectoryInfo(globalRoot);

               Console.WriteLine("Input GlobalRoot Path: [{0}]\n", dirInfo.FullName);

               if (!dirInfo.Exists)
                  UnitTestAssert.InconclusiveBecauseFileNotFound("No volume shadow copy found.");


               var enumOptions = Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.SkipReparsePoints;

               var copyCount = 0;

               foreach (var fileSource in dirInfo.EnumerateFiles(enumOptions))
               {
                  if (copyCount == 3)
                     break;


                  var fileCopy = System.IO.Path.Combine(folder.FullName, System.IO.Path.GetFileName(fileSource.FullName));

                  Console.WriteLine("Copy file #{0}.", copyCount + 1);


                  var cmr = Alphaleonis.Win32.Filesystem.File.Copy(fileSource.FullName, fileCopy, Alphaleonis.Win32.Filesystem.CopyOptions.None);


                  UnitTestConstants.Dump(cmr);
                  Console.WriteLine();


                  Assert.AreEqual((int) Alphaleonis.Win32.Win32Errors.NO_ERROR, cmr.ErrorCode);


                  testOk = true;

                  copyCount++;
               }
            }
         }


         Console.WriteLine();


         if (!testOk)
            UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File CopyMove/File.RestartMoveOrThrowException.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
      [SecurityCritical]
      private static bool RestartMoveOrThrowException(bool retry, int lastError, bool isFolder, bool isMove, CopyMoveArguments cma, string sourcePathLp, string destinationPathLp)
      {
         var restart = false;
         var srcExists = ExistsCore(cma.Transaction, isFolder, sourcePathLp, PathFormat.LongFullPath);
         var dstExists = ExistsCore(cma.Transaction, isFolder, destinationPathLp, PathFormat.LongFullPath);


         switch ((uint) lastError)
         {
            // File.Copy()
            // File.Move()
            // MSDN: .NET 3.5+: FileNotFoundException: sourcePath was not found. 
            //
            // File.Copy()
            // File.Move()
            // Directory.Move()
            // MSDN: .NET 3.5+: DirectoryNotFoundException: The path specified in sourcePath or destinationPath is invalid (for example, it is on an unmapped drive).
            case Win32Errors.ERROR_FILE_NOT_FOUND: // On files.
            case Win32Errors.ERROR_PATH_NOT_FOUND: // On folders.

               if (!srcExists)
                  Directory.ExistsDriveOrFolderOrFile(cma.Transaction, sourcePathLp, isFolder, lastError, false, true);

               if (!dstExists)
                  Directory.ExistsDriveOrFolderOrFile(cma.Transaction, destinationPathLp, isFolder, lastError, false, true);

               break;


            case Win32Errors.ERROR_NOT_READY: // DeviceNotReadyException: Floppy device or network drive not ready.
               Directory.ExistsDriveOrFolderOrFile(cma.Transaction, sourcePathLp, false, lastError, true, false);
               Directory.ExistsDriveOrFolderOrFile(cma.Transaction, destinationPathLp, false, lastError, true, false);
               break;


            // File.Copy()
            // Directory.Copy()
            case Win32Errors.ERROR_ALREADY_EXISTS: // On folders.
            case Win32Errors.ERROR_FILE_EXISTS:    // On files.
               lastError = (int) (isFolder ? Win32Errors.ERROR_ALREADY_EXISTS : Win32Errors.ERROR_FILE_EXISTS);

               if (!retry)
                  NativeError.ThrowException(lastError, isFolder, destinationPathLp);

               break;


            default:
               var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();

               FillAttributeInfoCore(cma.Transaction, destinationPathLp, ref attrs, false, false);

               var destIsFolder = IsDirectory(attrs.dwFileAttributes);


               // For a number of error codes (sharing violation, path not found, etc)
               // we don't know if the problem was with the source or destination file.

               // Check if destination directory already exists.
               // Directory.Move()
               // MSDN: .NET 3.5+: IOException: destDirName already exists.

               if (destIsFolder && dstExists && !retry)
                  NativeError.ThrowException(Win32Errors.ERROR_ALREADY_EXISTS, destinationPathLp);




               if (isMove)
               {
                  // Ensure that the source file or folder exists.
                  // Directory.Move()
                  // MSDN: .NET 3.5+: DirectoryNotFoundException: The path specified by sourceDirName is invalid (for example, it is on an unmapped drive). 

                  if (!srcExists && !retry)
                     NativeError.ThrowException(isFolder ? Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_FILE_NOT_FOUND, sourcePathLp);
               }


               // Try reading the source file.
               var fileNameLp = destinationPathLp;

               if (!isFolder)
               {
                  using (var safeHandle = CreateFileCore(cma.Transaction, false, sourcePathLp, ExtendedFileAttributes.Normal, null, FileMode.Open, 0, FileShare.Read, false, false, PathFormat.LongFullPath))
                     if (null != safeHandle)
                        fileNameLp = sourcePathLp;
               }


               if (lastError == Win32Errors.ERROR_ACCESS_DENIED)
               {
                  // File.Copy()
                  // File.Move()
                  // MSDN: .NET 3.5+: IOException: An I/O error has occurred.


                  // Directory exists with the same name as the file.

                  if (dstExists && !isFolder && destIsFolder && !retry)

                     NativeError.ThrowException(lastError, false, string.Format(CultureInfo.InvariantCulture, Resources.Target_File_Is_A_Directory, destinationPathLp));

                  
                  // MSDN: .NET 3.5+: IOException: The directory specified by path is read-only.

                  if (isMove && IsReadOnlyOrHidden(attrs.dwFileAttributes))
                  {
                     if (HasReplaceExisting(cma.MoveOptions))
                     {
                        // Reset attributes to Normal.
                        SetAttributesCore(cma.Transaction, isFolder, destinationPathLp, FileAttributes.Normal, PathFormat.LongFullPath);


                        restart = true;
                        break;
                     }


                     // MSDN: .NET 3.5+: UnauthorizedAccessException: destinationPath is read-only.
                     // MSDN: Win32 CopyFileXxx: This function fails with ERROR_ACCESS_DENIED if the destination file already exists
                     // and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_READONLY attribute set.

                     if (!retry)
                        throw new FileReadOnlyException(destinationPathLp);
                  }
               }


               // MSDN: .NET 3.5+: An I/O error has occurred. 
               // File.Copy(): IOException: destinationPath exists and overwrite is false.
               // File.Move(): The destination file already exists or sourcePath was not found.

               if (!retry)
                  NativeError.ThrowException(lastError, isFolder, fileNameLp);

               break;
         }


         return restart;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.GetSize/AlphaFS_Directory.GetSize_WithStreamsOnRootFolder.cs<|end_filename|>
﻿/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;

namespace AlphaFS.UnitTest
{
   partial class SizeTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_GetSize_WithStreamsOnRootFolder_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_GetSize_WithStreamsOnRootFolder(false);
         AlphaFS_Directory_GetSize_WithStreamsOnRootFolder(true);
      }
      

      private void AlphaFS_Directory_GetSize_WithStreamsOnRootFolder(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.CreateTree(5);

            Console.WriteLine("Input Directory Path: [{0}]", folder.FullName);


            var folderSize = Alphaleonis.Win32.Filesystem.Directory.GetSize(folder.FullName, true, true);

            Console.WriteLine("\n\tTotal Directory size: [{0:N0} bytes ({1})]\n", folderSize, Alphaleonis.Utils.UnitSizeToText(folderSize));


            var folderProps = Alphaleonis.Win32.Filesystem.Directory.GetProperties(folder.FullName, Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.FilesAndFolders | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive);

            Assert.AreEqual(10, folderProps["Total"]);

            Assert.AreEqual(5, folderProps["Directory"]);

            Assert.AreEqual(5, folderProps["File"]);

            Assert.AreEqual(folderProps["Size"], folderSize);

            Assert.AreNotEqual(0, folderSize);
            



            var streamsCount = new Random(DateTime.UtcNow.Millisecond).Next(1, 9);

            var allStreamsSize = 0;

            for (var i = 0; i < streamsCount; i++)
            {
               var streamName = folder.FullName + ":myStream" + i;

               var streamText = new string((char) streamsCount, new Random(DateTime.UtcNow.Millisecond).Next(0, 5 * UnitTestConstants.OneMebibyte));

               allStreamsSize += streamText.Length;

               Console.WriteLine("\tAdd stream: [{0:N0} bytes ({1})] [{2}]", streamText.Length, Alphaleonis.Utils.UnitSizeToText(streamText.Length), streamName);


               // Create alternate data streams.
               // Because of the colon, you must supply a full path and use PathFormat.FullPath or PathFormat.LongFullPath,
               // to prevent a: "NotSupportedException: path is in an invalid format." exception.

               Alphaleonis.Win32.Filesystem.File.WriteAllText(streamName, streamText, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);
            }


            var streams = Alphaleonis.Win32.Filesystem.Directory.EnumerateAlternateDataStreams(folder.FullName).ToArray();

            Console.WriteLine("\n\tTotal added Stream count: [{0}] size: [{1:N0} bytes ({2})]", streams.Length, allStreamsSize, Alphaleonis.Utils.UnitSizeToText(allStreamsSize));


            var folderSizeWithStreams = Alphaleonis.Win32.Filesystem.Directory.GetSize(folder.FullName, true, true);

            Console.WriteLine("\n\tTotal Directory size + {0} streams: [{1:N0} bytes ({2})]", streamsCount, folderSizeWithStreams, Alphaleonis.Utils.UnitSizeToText(folderSizeWithStreams));

            Assert.AreEqual(folderSize + allStreamsSize, folderSizeWithStreams, "The total folder size does not match, but it is expected.");
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory.ExistsDrive.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>[AlphaFS] Checks if specified <paramref name="path"/> is a local- or network drive.</summary>
      /// <param name="path">The path to check, such as: "C:" or "\\server\c$".</param>
      /// <returns><c>true</c> if the drive exists, <c>false</c> otherwise.</returns>
      public static bool ExistsDrive(string path)
      {
         return ExistsDriveOrFolderOrFile(null, path, false, (int) Win32Errors.NO_ERROR, false, false);
      }


      /// <summary>[AlphaFS] Checks if specified <paramref name="path"/> is a local- or network drive.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The path to check, such as: "C:" or "\\server\c$".</param>
      /// <returns><c>true</c> if the drive exists, <c>false</c> otherwise.</returns>
      public static bool ExistsDrive(KernelTransaction transaction, string path)
      {
         return ExistsDriveOrFolderOrFile(transaction, path, false, (int) Win32Errors.NO_ERROR, false, false);
      }


      /// <summary>[AlphaFS] Checks if specified <paramref name="path"/> is a local- or network drive.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The path to check, such as: "C:" or "\\server\c$".</param>
      /// <param name="throwIfDriveNotExists">Throws DeviceNotReadyException when drive is not found.</param>
      /// <returns><c>true</c> if the drive exists, <c>false</c> otherwise.</returns>
      [Obsolete("This function will be removed.")]
      public static bool ExistsDrive(KernelTransaction transaction, string path, bool throwIfDriveNotExists)
      {
         return ExistsDriveOrFolderOrFile(transaction, path, false, (int) Win32Errors.NO_ERROR, throwIfDriveNotExists, false);
      }


      /// <summary>[AlphaFS] Checks if specified <paramref name="path"/> is a local- or network drive.</summary>
      /// <returns><c>true</c> if the drive exists, <c>false</c> otherwise.</returns>
      internal static bool ExistsDriveOrFolderOrFile(KernelTransaction transaction, string path, bool isFolder, int lastError, bool throwIfDriveNotExists, bool throwIfFolderOrFileNotExists)
      {
         if (Utils.IsNullOrWhiteSpace(path))
            return false;


         var drive = GetDirectoryRootCore(transaction, path, Path.IsPathRooted(path) ? PathFormat.FullPath : PathFormat.RelativePath);

         var driveExists = null != drive && File.ExistsCore(transaction, true, drive, PathFormat.FullPath);

         var regularPath = Path.GetCleanExceptionPath(path);


         if (!driveExists && throwIfDriveNotExists || lastError == Win32Errors.ERROR_NOT_READY)
            throw new DeviceNotReadyException(drive, true);


         throwIfFolderOrFileNotExists = throwIfFolderOrFileNotExists && lastError != Win32Errors.NO_ERROR;

         if (throwIfFolderOrFileNotExists)
         {
            if (lastError != Win32Errors.NO_ERROR)
            {
               if (lastError == Win32Errors.ERROR_PATH_NOT_FOUND)
                  throw new DirectoryNotFoundException(regularPath);


               if (lastError == Win32Errors.ERROR_FILE_NOT_FOUND)
               {
                  if (isFolder)
                     throw new DirectoryNotFoundException(regularPath);

                  throw new FileNotFoundException(regularPath);
               }
            }
         }


         return driveExists;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/FileInfo Class/FileInfo.Replace.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   partial class FileInfo
   {
      #region .NET

      /// <summary>Replaces the contents of a specified file with the file described by the current <see cref="FileInfo"/> object, deleting the original file, and creating a backup of the replaced file.</summary>
      /// <returns>A <see cref="FileInfo"/> object that encapsulates information about the file described by the <paramref name="destinationFileName"/> parameter.</returns>
      /// <remarks>
      ///   The Replace method replaces the contents of a specified file with the contents of the file described by the current
      ///   <see cref="FileInfo"/> object. It also creates a backup of the file that was replaced. Finally, it returns a new
      ///    <see cref="FileInfo"/> object that describes the overwritten file.
      /// </remarks>
      /// <remarks>Pass null to the <paramref name="destinationBackupFileName"/> parameter if you do not want to create a backup of the file being replaced.</remarks>
      /// <param name="destinationFileName">The name of a file to replace with the current file.</param>
      /// <param name="destinationBackupFileName">The name of a file with which to create a backup of the file described by the <paramref name="destinationFileName"/> parameter.</param>
      [SecurityCritical]
      public FileInfo Replace(string destinationFileName, string destinationBackupFileName)
      {
         return Replace(destinationFileName, destinationBackupFileName, false, PathFormat.RelativePath);
      }


      /// <summary>Replaces the contents of a specified file with the file described by the current <see cref="FileInfo"/> object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors.</summary>
      /// <returns>A <see cref="FileInfo"/> object that encapsulates information about the file described by the <paramref name="destinationFileName"/> parameter.</returns>
      /// <remarks>
      ///   The Replace method replaces the contents of a specified file with the contents of the file described by the current
      ///   <see cref="FileInfo"/> object. It also creates a backup of the file that was replaced. Finally, it returns a new
      ///   <see cref="FileInfo"/> object that describes the overwritten file.
      /// </remarks>
      /// <remarks>Pass null to the <paramref name="destinationBackupFileName"/> parameter if you do not want to create a backup of the file being replaced.</remarks>
      /// <param name="destinationFileName">The name of a file to replace with the current file.</param>
      /// <param name="destinationBackupFileName">The name of a file with which to create a backup of the file described by the <paramref name="destinationFileName"/> parameter.</param>
      /// <param name="ignoreMetadataErrors"><c>true</c> to ignore merge errors (such as attributes and ACLs) from the replaced file to the replacement file; otherwise, <c>false</c>.</param>
      [SecurityCritical]
      public FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors)
      {
         return Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors, PathFormat.RelativePath);
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Replaces the contents of a specified file with the file described by the current <see cref="FileInfo"/> object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors.</summary>
      /// <returns>A <see cref="FileInfo"/> object that encapsulates information about the file described by the <paramref name="destinationFileName"/> parameter.</returns>
      /// <remarks>
      ///   The Replace method replaces the contents of a specified file with the contents of the file described by the current
      ///   <see cref="FileInfo"/> object. It also creates a backup of the file that was replaced. Finally, it returns a new
      ///   <see cref="FileInfo"/> object that describes the overwritten file.
      /// </remarks>
      /// <remarks>Pass null to the <paramref name="destinationBackupFileName"/> parameter if you do not want to create a backup of the file being replaced.</remarks>
      /// <param name="destinationFileName">The name of a file to replace with the current file.</param>
      /// <param name="destinationBackupFileName">The name of a file with which to create a backup of the file described by the <paramref name="destinationFileName"/> parameter.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public FileInfo Replace(string destinationFileName, string destinationBackupFileName, PathFormat pathFormat)
      {
         return Replace(destinationFileName, destinationBackupFileName, false, pathFormat);
      }


      /// <summary>[AlphaFS] Replaces the contents of a specified file with the file described by the current <see cref="FileInfo"/> object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors.</summary>
      /// <returns>A <see cref="FileInfo"/> object that encapsulates information about the file described by the <paramref name="destinationFileName"/> parameter.</returns>
      /// <remarks>
      ///   The Replace method replaces the contents of a specified file with the contents of the file described by the current
      ///   <see cref="FileInfo"/> object. It also creates a backup of the file that was replaced. Finally, it returns a new
      ///   <see cref="FileInfo"/> object that describes the overwritten file.
      /// </remarks>
      /// <remarks>Pass null to the <paramref name="destinationBackupFileName"/> parameter if you do not want to create a backup of the file being replaced.</remarks>
      /// <param name="destinationFileName">The name of a file to replace with the current file.</param>
      /// <param name="destinationBackupFileName">The name of a file with which to create a backup of the file described by the <paramref name="destinationFileName"/> parameter.</param>
      /// <param name="ignoreMetadataErrors"><c>true</c> to ignore merge errors (such as attributes and ACLs) from the replaced file to the replacement file; otherwise, <c>false</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors, PathFormat pathFormat)
      {
         const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck;

         var destinationFileNameLp = Path.GetExtendedLengthPathCore(Transaction, destinationFileName, pathFormat, options);

         var destinationBackupFileNameLp = destinationBackupFileName != null
            ? Path.GetExtendedLengthPathCore(Transaction, destinationBackupFileName, pathFormat, options)
            : null;

         File.ReplaceCore(LongFullName, destinationFileNameLp, destinationBackupFileNameLp, ignoreMetadataErrors, PathFormat.LongFullPath);

         return new FileInfo(Transaction, destinationFileNameLp, PathFormat.LongFullPath);
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Returns an enumerable collection of <see cref="string"/> drive letters and mounted folder paths for the specified volume.</summary>
      /// <returns>An enumerable collection of <see cref="string"/> containing the path names for the specified volume.</returns>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="ArgumentException"/>
      /// <param name="volumeGuid">A volume <see cref="Guid"/> path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\.</param>
      [SecurityCritical]
      public static IEnumerable<string> EnumerateVolumePathNames(string volumeGuid)
      {
         if (Utils.IsNullOrWhiteSpace(volumeGuid))
            throw new ArgumentNullException("volumeGuid");

         if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase))
            throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid");


         var volName = Path.AddTrailingDirectorySeparator(volumeGuid, false);


         uint requiredLength = 10;
         var cBuffer = new char[requiredLength];


         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
            while (!NativeMethods.GetVolumePathNamesForVolumeName(volName, cBuffer, (uint)cBuffer.Length, out requiredLength))
            {
               var lastError = Marshal.GetLastWin32Error();

               switch ((uint)lastError)
               {
                  case Win32Errors.ERROR_MORE_DATA:
                  case Win32Errors.ERROR_INSUFFICIENT_BUFFER:
                     cBuffer = new char[requiredLength];
                     break;

                  default:
                     NativeError.ThrowException(lastError, volumeGuid);
                     break;
               }
            }


         var buffer = new StringBuilder(cBuffer.Length);
         foreach (var c in cBuffer)
         {
            if (c != Path.StringTerminatorChar)
               buffer.Append(c);
            else
            {
               if (buffer.Length > 0)
               {
                  yield return buffer.ToString();
                  buffer.Length = 0;
               }
            }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.EnableDisableEncryptionCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Enables/disables encryption of the specified directory and the files in it.
      ///   <para>This method only creates/modifies the file "Desktop.ini" in the root of <paramref name="path"/> and  enables/disables encryption by writing: "Disable=0" or "Disable=1".</para>
      ///   <para>This method does not affect encryption of files and subdirectories below the indicated directory.</para>
      /// </summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryReadOnlyException"/>
      /// <exception cref="FileReadOnlyException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="path">The name of the directory for which to enable encryption.</param>
      /// <param name="enable"><c>true</c> enabled encryption, <c>false</c> disables encryption.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void EnableDisableEncryptionCore(string path, bool enable, PathFormat pathFormat)
      {
         if (Utils.IsNullOrWhiteSpace(path))
            throw new ArgumentNullException("path");

         var pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

         // EncryptionDisable()
         // 2013-01-13: MSDN does not confirm LongPath usage and no Unicode version of this function exists.

         var success = NativeMethods.EncryptionDisable(pathLp, !enable);

         var lastError = Marshal.GetLastWin32Error();
         if (!success)
            NativeError.ThrowException(lastError, true, pathLp);
      }
   }
}


<|start_filename|>src/AlphaFS/Network/ServerStatisticsInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;

namespace Alphaleonis.Win32.Network
{
   /// <summary>Contains operating statistics for the Server service.</summary>
   [Serializable]
   public sealed class ServerStatisticsInfo : IEquatable<ServerStatisticsInfo>
   {
      #region Fields

      [NonSerialized] private DateTime _dateTimeNowUtc;
      [NonSerialized] private NativeMethods.STAT_SERVER_0 _serverStat;

      #endregion // Fields

      
      #region Constructors

      /// <summary>Create a ServerStatisticsInfo instance from the local host.</summary>
      public ServerStatisticsInfo() : this(Environment.MachineName, null)
      {
      }


      /// <summary>Create a ServerStatisticsInfo instance from the specified host name.</summary>
      /// <param name="hostName">The host name.</param>
      public ServerStatisticsInfo(string hostName) : this(hostName, null)
      {
      }


      /// <summary>Create a ServerStatisticsInfo instance from the specified host name.</summary>
      internal ServerStatisticsInfo(string hostName, NativeMethods.STAT_SERVER_0? serverStat)
      {
         HostName = !Utils.IsNullOrWhiteSpace(hostName) ? hostName : Environment.MachineName;

         if (serverStat.HasValue)
         {
            _dateTimeNowUtc = DateTime.UtcNow;

            _serverStat = (NativeMethods.STAT_SERVER_0) serverStat;
         }

         else
            Refresh();
      }

      #endregion // Constructors


      #region Properties

      /// <summary>The number of server access permission errors.</summary>
      public int AccessPermissionErrors
      {
         get { return (int) _serverStat.sts0_permerrors; }
      }


      /// <summary>The average server response time.</summary>
      public TimeSpan AverageResponseTime
      {
         get { return TimeSpan.FromMilliseconds(_serverStat.sts0_avresponse); }
      }


      /// <summary>The number of times the server required a big buffer but failed to allocate one. This value indicates that the server parameters may need adjustment.</summary>
      public int BufferAllocationFailed
      {
         get { return (int) _serverStat.sts0_bigbufneed; }
      }


      /// <summary>The number of times the server required a request buffer but failed to allocate one. This value indicates that the server parameters may need adjustment.</summary>
      public int BufferRequestFailed
      {
         get { return (int) _serverStat.sts0_reqbufneed; }
      }


      /// <summary>The number of server bytes received from the network.</summary>
      public long BytesReceived
      {
         get { return Filesystem.NativeMethods.ToLong(_serverStat.sts0_bytesrcvd_high, _serverStat.sts0_bytesrcvd_low); }
      }


      /// <summary>The number of server bytes received from the network, formatted as a unit size.</summary>
      public string BytesReceivedUnitSize
      {
         get { return Utils.UnitSizeToText(BytesReceived); }
      }


      /// <summary>The number of server bytes sent to the network.</summary>
      public long BytesSent
      {
         get { return Filesystem.NativeMethods.ToLong(_serverStat.sts0_bytessent_high, _serverStat.sts0_bytessent_low); }
      }


      /// <summary>The number of server bytes sent to the network, formatted as a unit size.</summary>
      public string BytesSentUnitSize
      {
         get { return Utils.UnitSizeToText(BytesSent); }
      }
      

      /// <summary>The number of times a server device is opened.</summary>
      public int DevicesOpened
      {
         get { return (int) _serverStat.sts0_devopens; }
      }


      /// <summary>The number of times a file is opened on a server. This includes the number of times named pipes are opened.</summary>
      public int FilesOpened
      {
         get { return (int) _serverStat.sts0_fopens; }
      }


      /// <summary>The host name from where the statistics are gathered.</summary>
      public string HostName { get; private set; }


      /// <summary>The number of server print jobs spooled.</summary>
      public int JobsQueued
      {
         get { return (int) _serverStat.sts0_jobsqueued; }
      }


      /// <summary>The number of server password violations.</summary>
      public int PasswordViolations
      {
         get { return (int) _serverStat.sts0_pwerrors; }
      }


      /// <summary>The number of times the server sessions failed with an error.</summary>
      public int SessionsFailed
      {
         get { return (int) _serverStat.sts0_serrorout; }
      }


      /// <summary>The number of times the server session started.</summary>
      public int SessionsStarted
      {
         get { return (int) _serverStat.sts0_sopens; }
      }


      /// <summary>The number of times the server session automatically disconnected.</summary>
      public int SessionsTimedOut
      {
         get { return (int) _serverStat.sts0_stimedout; }
      }


      /// <summary>The local time when statistics collection started or when the statistics were last cleared.</summary>
      public DateTime StatisticsStartTime
      {
         get { return StatisticsStartTimeUtc.ToLocalTime(); }
      }


      /// <summary>The time when statistics collection started or when the statistics were last cleared.</summary>
      public DateTime StatisticsStartTimeUtc
      {
         get { return new DateTime((_dateTimeNowUtc - new DateTime(_serverStat.sts0_start, DateTimeKind.Utc)).Ticks, DateTimeKind.Utc); }
      }


      /// <summary>The number of server system errors.</summary>
      public int SystemErrors
      {
         get { return (int) _serverStat.sts0_syserrors; }
      }

      #endregion // Properties


      #region Methods

      /// <summary>Refreshes the state of the object.</summary>
      public void Refresh()
      {
         _dateTimeNowUtc = DateTime.UtcNow;

         _serverStat = Host.GetNetStatisticsNative<NativeMethods.STAT_SERVER_0>(true, HostName);
      }


      /// <summary>Returns the local time when statistics collection started or when the statistics were last cleared.</summary>
      /// <returns>A string that represents this instance.</returns>
      public override string ToString()
      {
         return HostName;
      }


      /// <summary>Serves as a hash function for a particular type.</summary>
      /// <returns>A hash code for the current Object.</returns>
      public override int GetHashCode()
      {
         return Utils.CombineHashCodesOf(HostName, BytesSent, StatisticsStartTime);
      }
      

      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="other">Another <see cref="ServerStatisticsInfo"/> instance to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public bool Equals(ServerStatisticsInfo other)
      {
         return null != other && GetType() == other.GetType() &&
                Equals(HostName, other.HostName) &&
                Equals(BytesSent, other.BytesSent) &&
                Equals(BytesReceived, other.BytesReceived) &&
                Equals(StatisticsStartTimeUtc, other.StatisticsStartTimeUtc);
      }


      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="obj">Another object to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public override bool Equals(object obj)
      {
         var other = obj as ServerStatisticsInfo;

         return null != other && Equals(other);
      }


      /// <summary>Implements the operator ==</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator ==(ServerStatisticsInfo left, ServerStatisticsInfo right)
      {
         return ReferenceEquals(left, null) && ReferenceEquals(right, null) ||
                !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right);
      }


      /// <summary>Implements the operator !=</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator !=(ServerStatisticsInfo left, ServerStatisticsInfo right)
      {
         return !(left == right);
      }

      #endregion // Methods
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.EnumerateFileSystemEntryInfosCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path using <see cref="DirectoryEnumerationOptions"/> and <see cref="DirectoryEnumerationFilters"/>.</summary>
      /// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <typeparam name="T">The type to return. This may be one of the following types:
      ///    <list type="definition">
      ///    <item>
      ///       <term><see cref="FileSystemEntryInfo"/></term>
      ///       <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
      ///    </item>
      ///    <item>
      ///       <term><see cref="FileSystemInfo"/></term>
      ///       <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
      ///    </item>
      ///    <item>
      ///       <term><see cref="string"/></term>
      ///       <description>This method will return the full path of each item.</description>
      ///    </item>
      /// </list>
      /// </typeparam>
      /// <param name="onlyFolders"></param>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to search.</param>
      /// <param name="searchPattern">
      ///    The search string to match against the names of directories in <paramref name="path"/>.
      ///    This parameter can contain a combination of valid literal path and wildcard
      ///    (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
      /// </param>
      /// <param name="searchOption"></param>
      /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
      /// <param name="filters">The specification of custom filters to be used in the process.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static IEnumerable<T> EnumerateFileSystemEntryInfosCore<T>(bool? onlyFolders, KernelTransaction transaction, string path, string searchPattern, SearchOption? searchOption, DirectoryEnumerationOptions? options, DirectoryEnumerationFilters filters, PathFormat pathFormat)
      {
         if (null == options)
            options = DirectoryEnumerationOptions.None;


         if (searchOption == SearchOption.AllDirectories)
            options |= DirectoryEnumerationOptions.Recursive;


         if (null != onlyFolders)
         {
            // Adhere to the method name by validating the DirectoryEnumerationOptions value.
            // For example, method Directory.EnumerateDirectories() should only return folders
            // and method Directory.EnumerateFiles() should only return files.


            // Folders only.
            if ((bool) onlyFolders)
            {
               options &= ~DirectoryEnumerationOptions.Files;  // Remove enumeration of files.
               options |= DirectoryEnumerationOptions.Folders; // Add enumeration of folders.
            }

            // Files only.
            else
            {
               options &= ~DirectoryEnumerationOptions.Folders; // Remove enumeration of folders.
               options |= DirectoryEnumerationOptions.Files;    // Add enumeration of files.
            }
         }
         

         return new FindFileSystemEntryInfo(transaction, true, path, searchPattern, options, filters, pathFormat, typeof(T)).Enumerate<T>();
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Device.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Network;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Provides static methods to retrieve device resource information from a local or remote host.</summary>
   public static class Device
   {
      #region Enumerate Devices

      /// <summary>[AlphaFS] Enumerates all available devices on the local host.</summary>
      /// <returns><see cref="IEnumerable{DeviceInfo}"/> instances of type <see cref="DeviceGuid"/> from the local host.</returns>
      /// <param name="deviceGuid">One of the <see cref="DeviceGuid"/> devices.</param>
      [SecurityCritical]
      public static IEnumerable<DeviceInfo> EnumerateDevices(DeviceGuid deviceGuid)
      {
         return EnumerateDevicesCore(null, deviceGuid, true);
      }


      /// <summary>[AlphaFS] Enumerates all available devices of type <see cref="DeviceGuid"/> on the local or remote host.</summary>
      /// <returns><see cref="IEnumerable{DeviceInfo}"/> instances of type <see cref="DeviceGuid"/> for the specified <paramref name="hostName"/>.</returns>
      /// <param name="hostName">The name of the local or remote host on which the device resides. <c>null</c> refers to the local host.</param>
      /// <param name="deviceGuid">One of the <see cref="DeviceGuid"/> devices.</param>
      [SecurityCritical]
      public static IEnumerable<DeviceInfo> EnumerateDevices(string hostName, DeviceGuid deviceGuid)
      {
         return EnumerateDevicesCore(hostName, deviceGuid, true);
      }




      /// <summary>[AlphaFS] Enumerates all available devices on the local or remote host.</summary>
      [SecurityCritical]
      internal static IEnumerable<DeviceInfo> EnumerateDevicesCore(string hostName, DeviceGuid deviceGuid, bool getAllProperties)
      {
         if (Utils.IsNullOrWhiteSpace(hostName))
            hostName = Environment.MachineName;


         // CM_Connect_Machine()
         // MSDN Note: Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed.
         // You cannot access remote machines when running on these versions of Windows. 
         // http://msdn.microsoft.com/en-us/library/windows/hardware/ff537948%28v=vs.85%29.aspx


         SafeCmConnectMachineHandle safeMachineHandle;

         var lastError = NativeMethods.CM_Connect_Machine(Host.GetUncName(hostName), out safeMachineHandle);

         NativeMethods.IsValidHandle(safeMachineHandle, lastError);


         var classGuid = new Guid(Utils.GetEnumDescription(deviceGuid));


         // Start at the "Root" of the device tree of the specified machine.

         using (safeMachineHandle)
         using (var safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref classGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.SetupDiGetClassDevsExFlags.Present | NativeMethods.SetupDiGetClassDevsExFlags.DeviceInterface, IntPtr.Zero, hostName, IntPtr.Zero))
         {
            NativeMethods.IsValidHandle(safeHandle, Marshal.GetLastWin32Error());

            uint memberInterfaceIndex = 0;
            var interfaceStructSize = (uint)Marshal.SizeOf(typeof(NativeMethods.SP_DEVICE_INTERFACE_DATA));
            var dataStructSize = (uint)Marshal.SizeOf(typeof(NativeMethods.SP_DEVINFO_DATA));


            // Start enumerating device interfaces.

            while (true)
            {
               var interfaceData = new NativeMethods.SP_DEVICE_INTERFACE_DATA { cbSize = interfaceStructSize };

               var success = NativeMethods.SetupDiEnumDeviceInterfaces(safeHandle, IntPtr.Zero, ref classGuid, memberInterfaceIndex++, ref interfaceData);

               lastError = Marshal.GetLastWin32Error();

               if (!success)
               {
                  if (lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_NO_MORE_ITEMS)
                     NativeError.ThrowException(lastError, hostName);

                  break;
               }


               // Create DeviceInfo instance.

               var diData = new NativeMethods.SP_DEVINFO_DATA {cbSize = dataStructSize};

               var deviceInfo = new DeviceInfo(hostName) {DevicePath = GetDeviceInterfaceDetail(safeHandle, ref interfaceData, ref diData).DevicePath};


               if (getAllProperties)
               {
                  deviceInfo.InstanceId = GetDeviceInstanceId(safeMachineHandle, hostName, diData);

                  SetDeviceProperties(safeHandle, deviceInfo, diData);
               }

               else
                  SetMinimalDeviceProperties(safeHandle, deviceInfo, diData);


               yield return deviceInfo;
            }
         }
      }


      #region Private Helpers

      [SecurityCritical]
      private static string GetDeviceInstanceId(SafeCmConnectMachineHandle safeMachineHandle, string hostName, NativeMethods.SP_DEVINFO_DATA diData)
      {
         uint ptrPrevious;

         var lastError = NativeMethods.CM_Get_Parent_Ex(out ptrPrevious, diData.DevInst, 0, safeMachineHandle);

         if (lastError != Win32Errors.CR_SUCCESS)
            NativeError.ThrowException(lastError, hostName);


         using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize / 8)) // 512
         {
            lastError = NativeMethods.CM_Get_Device_ID_Ex(diData.DevInst, safeBuffer, (uint) safeBuffer.Capacity, 0, safeMachineHandle);

            if (lastError != Win32Errors.CR_SUCCESS)
               NativeError.ThrowException(lastError, hostName);


            // Device InstanceID, such as: "USB\VID_8087&PID_0A2B\5&2EDA7E1E&0&7", "SCSI\DISK&VEN_SANDISK&PROD_X400\4&288ED25&0&000200", ...

            return safeBuffer.PtrToStringUni();
         }
      }


      /// <summary>Builds a Device Interface Detail Data structure.</summary>
      /// <returns>An initialized NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA instance.</returns>
      [SecurityCritical]
      private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetDeviceInterfaceDetail(SafeHandle safeHandle, ref NativeMethods.SP_DEVICE_INTERFACE_DATA interfaceData, ref NativeMethods.SP_DEVINFO_DATA infoData)
      {
         var didd = new NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA {cbSize = (uint) (IntPtr.Size == 4 ? 6 : 8)};

         var success = NativeMethods.SetupDiGetDeviceInterfaceDetail(safeHandle, ref interfaceData, ref didd, (uint) Marshal.SizeOf(didd), IntPtr.Zero, ref infoData);

         var lastError = Marshal.GetLastWin32Error();

         if (!success)
            NativeError.ThrowException(lastError);

         return didd;
      }


      [SecurityCritical]
      private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum property)
      {
         var bufferSize = NativeMethods.DefaultFileBufferSize / 8; // 512

         while (true)
            using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize))
            {
               var success = NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref infoData, property, IntPtr.Zero, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero);

               var lastError = Marshal.GetLastWin32Error();

               if (success)
               {
                  var value = safeBuffer.PtrToStringUni();

                  return !Utils.IsNullOrWhiteSpace(value) ? value.Trim() : null;
               }


               // MSDN: SetupDiGetDeviceRegistryProperty returns ERROR_INVALID_DATA error code if
               // the requested property does not exist for a device or if the property data is not valid.

               if (lastError == Win32Errors.ERROR_INVALID_DATA)
                  return null;


               bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, property.ToString());
            }
      }



      [SecurityCritical]
      private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData)
      {
         SetMinimalDeviceProperties(safeHandle, deviceInfo, infoData);


         deviceInfo.CompatibleIds = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.CompatibleIds);

         deviceInfo.Driver = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Driver);

         deviceInfo.EnumeratorName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.EnumeratorName);

         deviceInfo.HardwareId = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.HardwareId);

         deviceInfo.LocationInformation = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.LocationInformation);

         deviceInfo.LocationPaths = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.LocationPaths);

         deviceInfo.Manufacturer = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Manufacturer);

         deviceInfo.Service = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Service);
      }


      [SecurityCritical]
      private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData)
      {
         deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.BaseContainerId));

         deviceInfo.ClassGuid = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.ClassGuid));

         deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class);

         deviceInfo.DeviceDescription = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceDescription);

         deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName);

         deviceInfo.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.PhysicalDeviceObjectName);
      }


      [SecurityCritical]
      internal static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandle safeBuffer, int bufferSize, string pathForException)
      {
         if (null != safeBuffer && !safeBuffer.IsClosed)
            safeBuffer.Close();


         switch ((uint) lastError)
         {
            case Win32Errors.ERROR_MORE_DATA:
            case Win32Errors.ERROR_INSUFFICIENT_BUFFER:
               bufferSize *= 2;
               break;


            default:
               NativeMethods.IsValidHandle(safeBuffer, lastError, string.Format(CultureInfo.InvariantCulture, "Buffer size: {0}. Path: {1}", bufferSize.ToString(CultureInfo.InvariantCulture), pathForException));
               break;
         }


         return bufferSize;
      }
      

      /// <summary>Repeatedly invokes InvokeIoControl with the specified input until enough memory has been allocated.</summary>
      [SecurityCritical]
      private static void InvokeIoControlUnknownSize<T>(SafeFileHandle handle, uint controlCode, T input, uint increment = 128)
      {
         var inputSize = (uint) Marshal.SizeOf(input);
         var outputLength = increment;

         do
         {
            var output = new byte[outputLength];
            uint bytesReturned;

            var success = NativeMethods.DeviceIoControlUnknownSize(handle, controlCode, input, inputSize, output, outputLength, out bytesReturned, IntPtr.Zero);

            var lastError = Marshal.GetLastWin32Error();
            if (!success)
            {
               switch ((uint) lastError)
               {
                  case Win32Errors.ERROR_MORE_DATA:
                  case Win32Errors.ERROR_INSUFFICIENT_BUFFER:
                     outputLength += increment;
                     break;

                  default:
                     if (lastError != Win32Errors.ERROR_SUCCESS)
                        NativeError.ThrowException(lastError);
                     break;
               }
            }

            else
               break;

         } while (true);
      }

      #endregion // Private Helpers


      #endregion // Enumerate Devices


      #region Compression

      /// <summary>[AlphaFS] Sets the NTFS compression state of a file or directory on a volume whose file system supports per-file and per-directory compression.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="isFolder">Specifies that <paramref name="path"/> is a file or directory.</param>
      /// <param name="path">A path that describes a folder or file to compress or decompress.</param>
      /// <param name="compress"><c>true</c> = compress, <c>false</c> = decompress</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void ToggleCompressionCore(KernelTransaction transaction, bool isFolder, string path, bool compress, PathFormat pathFormat)
      {
         using (var handle = File.CreateFileCore(transaction, isFolder, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.Modify, FileShare.None, true, false, pathFormat))

            InvokeIoControlUnknownSize(handle, NativeMethods.FSCTL_SET_COMPRESSION, compress ? 1 : 0);
      }

      #endregion // Compression


      #region Link

      /// <summary>[AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J").</summary>
      internal static void CreateDirectoryJunction(SafeFileHandle safeHandle, string directoryPath)
      {
         var targetDirBytes = Encoding.Unicode.GetBytes(Path.NonInterpretedPathPrefix + Path.GetRegularPathCore(directoryPath, GetFullPathOptions.AddTrailingDirectorySeparator, false));

         var header = new NativeMethods.ReparseDataBufferHeader
         {
            ReparseTag = ReparsePointTag.MountPoint,
            ReparseDataLength = (ushort) (targetDirBytes.Length + 12)
         };

         var mountPoint = new NativeMethods.MountPointReparseBuffer
         {
            SubstituteNameOffset = 0,
            SubstituteNameLength = (ushort) targetDirBytes.Length,
            PrintNameOffset = (ushort) (targetDirBytes.Length + UnicodeEncoding.CharSize),
            PrintNameLength = 0
         };

         var reparseDataBuffer = new NativeMethods.REPARSE_DATA_BUFFER
         {
            ReparseTag = header.ReparseTag,
            ReparseDataLength = header.ReparseDataLength,

            SubstituteNameOffset = mountPoint.SubstituteNameOffset,
            SubstituteNameLength = mountPoint.SubstituteNameLength,
            PrintNameOffset = mountPoint.PrintNameOffset,
            PrintNameLength = mountPoint.PrintNameLength,

            PathBuffer = new byte[NativeMethods.MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 16] // 16368
         };

         targetDirBytes.CopyTo(reparseDataBuffer.PathBuffer, 0);


         using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(reparseDataBuffer)))
         {
            safeBuffer.StructureToPtr(reparseDataBuffer, false);

            uint bytesReturned;
            var succes = NativeMethods.DeviceIoControl2(safeHandle, NativeMethods.FSCTL_SET_REPARSE_POINT, safeBuffer, (uint) (targetDirBytes.Length + 20), IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

            var lastError = Marshal.GetLastWin32Error();
            if (!succes)
               NativeError.ThrowException(lastError, directoryPath);
         }
      }


      /// <summary>[AlphaFS] Deletes an NTFS directory junction.</summary>
      internal static void DeleteDirectoryJunction(SafeFileHandle safeHandle)
      {
         var reparseDataBuffer = new NativeMethods.REPARSE_DATA_BUFFER
         {
            ReparseTag = ReparsePointTag.MountPoint,
            ReparseDataLength = 0,
            PathBuffer = new byte[NativeMethods.MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 16] // 16368
         };


         using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(reparseDataBuffer)))
         {
            safeBuffer.StructureToPtr(reparseDataBuffer, false);

            uint bytesReturned;
            var success = NativeMethods.DeviceIoControl2(safeHandle, NativeMethods.FSCTL_DELETE_REPARSE_POINT, safeBuffer, NativeMethods.REPARSE_DATA_BUFFER_HEADER_SIZE, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

            var lastError = Marshal.GetLastWin32Error();
            if (!success)
               NativeError.ThrowException(lastError);
         }
      }


      /// <summary>[AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system.</summary>
      /// <exception cref="NotAReparsePointException"/>
      /// <exception cref="UnrecognizedReparsePointException"/>
      [SecurityCritical]
      internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, string reparsePath)
      {
         using (var safeBuffer = GetLinkTargetData(safeHandle, reparsePath))
         {
            var header = safeBuffer.PtrToStructure<NativeMethods.ReparseDataBufferHeader>(0);

            var marshalReparseBuffer = (int) Marshal.OffsetOf(typeof(NativeMethods.ReparseDataBufferHeader), "data");

            var dataOffset = (int) (marshalReparseBuffer + (header.ReparseTag == ReparsePointTag.MountPoint
               ? Marshal.OffsetOf(typeof(NativeMethods.MountPointReparseBuffer), "data")
               : Marshal.OffsetOf(typeof(NativeMethods.SymbolicLinkReparseBuffer), "data")).ToInt64());

            var dataBuffer = new byte[NativeMethods.MAXIMUM_REPARSE_DATA_BUFFER_SIZE - dataOffset];


            switch (header.ReparseTag)
            {
               // MountPoint can be a junction or mounted drive (mounted drive starts with "\??\Volume").

               case ReparsePointTag.MountPoint:
                  var mountPoint = safeBuffer.PtrToStructure<NativeMethods.MountPointReparseBuffer>(marshalReparseBuffer);

                  safeBuffer.CopyTo(dataOffset, dataBuffer);

                  return new LinkTargetInfo(
                     Encoding.Unicode.GetString(dataBuffer, mountPoint.SubstituteNameOffset, mountPoint.SubstituteNameLength),
                     Encoding.Unicode.GetString(dataBuffer, mountPoint.PrintNameOffset, mountPoint.PrintNameLength));


               case ReparsePointTag.SymLink:
                  var symLink = safeBuffer.PtrToStructure<NativeMethods.SymbolicLinkReparseBuffer>(marshalReparseBuffer);

                  safeBuffer.CopyTo(dataOffset, dataBuffer);

                  return new SymbolicLinkTargetInfo(
                     Encoding.Unicode.GetString(dataBuffer, symLink.SubstituteNameOffset, symLink.SubstituteNameLength),
                     Encoding.Unicode.GetString(dataBuffer, symLink.PrintNameOffset, symLink.PrintNameLength), symLink.Flags);


               default:
                  throw new UnrecognizedReparsePointException(reparsePath);
            }
         }
      }


      /// <summary>[AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system.</summary>
      /// <exception cref="NotAReparsePointException"/>
      /// <exception cref="UnrecognizedReparsePointException"/>
      [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
      [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposing is controlled.")]
      [SecurityCritical]
      private static SafeGlobalMemoryBufferHandle GetLinkTargetData(SafeFileHandle safeHandle, string reparsePath)
      {
         var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.MAXIMUM_REPARSE_DATA_BUFFER_SIZE);

         while (true)
         {
            uint bytesReturned;
            var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero);

            var lastError = Marshal.GetLastWin32Error();
            if (!success)
            {
               switch ((uint) lastError)
               {
                  case Win32Errors.ERROR_MORE_DATA:
                  case Win32Errors.ERROR_INSUFFICIENT_BUFFER:

                     // Should not happen since we already use the maximum size.

                     if (safeBuffer.Capacity < bytesReturned)
                        safeBuffer.Close();
                     break;


                  default:
                     if (lastError != Win32Errors.ERROR_SUCCESS)
                        NativeError.ThrowException(lastError, reparsePath);
                     break;
               }
            }

            else
               break;
         }


         return safeBuffer;
      }

      #endregion // Link
   }
}


<|start_filename|>src/AlphaFS/NativeError.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.Policy;
using Alphaleonis.Win32.Filesystem;

namespace Alphaleonis.Win32
{
   internal static class NativeError
   {
      public static void ThrowException(int errorCode)
      {
         ThrowException((uint) errorCode, null, null);
      }

      
      public static void ThrowException(uint errorCode)
      {
         ThrowException(errorCode, null, null);
      }


      public static void ThrowException(int errorCode, string readPath)
      {
         ThrowException((uint) errorCode, readPath, null);
      }

      public static void ThrowException(int errorCode, bool? isFolder, string readPath)
      {
         if (errorCode == Win32Errors.ERROR_FILE_NOT_FOUND && null != isFolder && (bool) isFolder)
            errorCode = (int) Win32Errors.ERROR_PATH_NOT_FOUND;

         ThrowException((uint) errorCode, readPath, null);
      }


      public static void ThrowException(uint errorCode, string readPath)
      {
         ThrowException(errorCode, readPath, null);
      }


      public static void ThrowException(int errorCode, string readPath, string writePath)
      {
         ThrowException((uint) errorCode, readPath, writePath);
      }


      [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
      public static void ThrowException(uint errorCode, string readPath, string writePath)
      {
         if (null != readPath)
            readPath = Path.GetCleanExceptionPath(readPath);

         if (null != writePath)
            writePath = Path.GetCleanExceptionPath(writePath);

         var errorMessage = string.Format(CultureInfo.InvariantCulture, "({0}) {1}.", errorCode, new Win32Exception((int) errorCode).Message.Trim().TrimEnd('.').Trim());
        

         if (!Utils.IsNullOrWhiteSpace(readPath) && !Utils.IsNullOrWhiteSpace(writePath))
            errorMessage = string.Format(CultureInfo.InvariantCulture, "{0} | Read: [{1}] | Write: [{2}]", errorMessage, readPath, writePath);

         else
         {
            // Prevent messages like: "(87) The parameter is incorrect: []"
            if (!Utils.IsNullOrWhiteSpace(readPath ?? writePath))
               errorMessage = string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", errorMessage.TrimEnd('.'), readPath ?? writePath);
         }


         switch (errorCode)
         {
            case Win32Errors.ERROR_INVALID_DRIVE:
               throw new System.IO.DriveNotFoundException(errorMessage);


            case Win32Errors.ERROR_OPERATION_ABORTED:
               throw new OperationCanceledException(errorMessage);


            case Win32Errors.ERROR_FILE_NOT_FOUND:
               throw new System.IO.FileNotFoundException(errorMessage);


            case Win32Errors.ERROR_PATH_NOT_FOUND:
               throw new System.IO.DirectoryNotFoundException(errorMessage);


            case Win32Errors.ERROR_BAD_RECOVERY_POLICY:
               throw new PolicyException(errorMessage);


            case Win32Errors.ERROR_FILE_READ_ONLY:
            case Win32Errors.ERROR_ACCESS_DENIED:
            case Win32Errors.ERROR_NETWORK_ACCESS_DENIED:
               throw new UnauthorizedAccessException(errorMessage);


            case Win32Errors.ERROR_ALREADY_EXISTS:
            case Win32Errors.ERROR_FILE_EXISTS:
               throw new AlreadyExistsException(readPath ?? writePath, true);


            case Win32Errors.ERROR_DIR_NOT_EMPTY:
               throw new DirectoryNotEmptyException(errorMessage);


            case Win32Errors.ERROR_NOT_READY:
               throw new DeviceNotReadyException(errorMessage);


            case Win32Errors.ERROR_NOT_SAME_DEVICE:
               throw new NotSameDeviceException(errorMessage);


            #region Transactional

            case Win32Errors.ERROR_INVALID_TRANSACTION:
               throw new InvalidTransactionException(Resources.Transaction_Invalid, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTION_ALREADY_COMMITTED:
               throw new TransactionAlreadyCommittedException(Resources.Transaction_Already_Committed, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTION_ALREADY_ABORTED:
               throw new TransactionAlreadyAbortedException(Resources.Transaction_Already_Aborted, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTIONAL_CONFLICT:
               throw new TransactionalConflictException(Resources.Transactional_Conflict, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTION_NOT_ACTIVE:
               throw new TransactionException(Resources.Transaction_Not_Active, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTION_NOT_REQUESTED:
               throw new TransactionException(Resources.Transaction_Not_Requested, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTION_REQUEST_NOT_VALID:
               throw new TransactionException(Resources.Invalid_Transaction_Request, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE:
               throw new UnsupportedRemoteTransactionException(Resources.Invalid_Transaction_Request, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            #endregion // Transactional


            case Win32Errors.ERROR_SUCCESS:
            case Win32Errors.ERROR_SUCCESS_REBOOT_INITIATED:
            case Win32Errors.ERROR_SUCCESS_REBOOT_REQUIRED:
            case Win32Errors.ERROR_SUCCESS_RESTART_REQUIRED:
               // We should really never get here, throwing an exception for a successful operation.
               throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "{0} {1}", Resources.Exception_From_Successful_Operation, errorMessage));

            default:
               // We don't have a specific exception to generate for this error.               
               throw new System.IO.IOException(errorMessage, Win32Errors.GetHrFromWin32Error(errorCode));
         }
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize/AlphaFS_File.GetCompressedSize.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   partial class SizeTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_File_GetCompressedSize_LocalAndNetwork_Success()
      {
         AlphaFS_File_GetCompressedSize(false);
         AlphaFS_File_GetCompressedSize(true);
      }


      private void AlphaFS_File_GetCompressedSize(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var file = tempRoot.RandomTxtFileFullPath;

            Console.WriteLine("Input File Path: [{0}]\n", file);


            long streamLength;
            var tenNumbers = "0123456789";
            var thousand = 100 * tenNumbers.Length;
            var compressedSize = 4096;


            // Size: 9,76 KB(10.000 bytes)
            // Size on disk: 12,0 KB(12.288 bytes)
            using (var fs = System.IO.File.Create(file))
            {
               // According to NotePad++, creates a file type: "ANSI", which is reported as: "Unicode (UTF-8)".

               for (var count = 0; count < thousand; count ++)
                  fs.Write(UnitTestConstants.StringToByteArray(tenNumbers), 0, tenNumbers.Length);

               streamLength = fs.Length;
            }

            Console.WriteLine("\tFile size (uncompressed): {0:N0} bytes ({1})", streamLength, Alphaleonis.Utils.UnitSizeToText(streamLength));


            // Compress file.
            // Size on disk: 4,00 KB (4.096 bytes)
            Alphaleonis.Win32.Filesystem.File.Compress(file);


            var fileLength = Alphaleonis.Win32.Filesystem.File.GetCompressedSize(file);

            Console.WriteLine("\tFile size (compressed)  : {0:N0} bytes ({1})", fileLength, Alphaleonis.Utils.UnitSizeToText(fileLength));


            Assert.IsTrue(fileLength == compressedSize && fileLength != streamLength, "File should be [{0:N0}] bytes in size.", compressedSize);
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_WithMultipleSpacesAndSlashes.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class Directory_CreateDirectoryTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void Directory_CreateDirectory_WithMultipleSpacesAndSlashes_LocalAndNetwork_Success()
      {
         Directory_CreateDirectory_WithMultipleSpacesAndSlashes(false);
         Directory_CreateDirectory_WithMultipleSpacesAndSlashes(true);
      }


      private void Directory_CreateDirectory_WithMultipleSpacesAndSlashes(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.Directory.FullName;
            var subFolders = new[]
            {
               @"f�lder1",
               @"\ \",
               @"fold�r2 2",
               @"///",
               @" f�ld�r3 33"
            };


            var fullPath = folder + @"\" + subFolders[0] + subFolders[1] + subFolders[2] + subFolders[3] + subFolders[4];

            Console.WriteLine("Input Directory Path: [{0}]\n", fullPath);


            Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(fullPath);


            var count = 0;
            foreach (var dir in Alphaleonis.Win32.Filesystem.Directory.EnumerateFileSystemEntryInfos<Alphaleonis.Win32.Filesystem.DirectoryInfo>(folder, Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive))
            {
               Console.WriteLine("\tFolder name: \"{0}\"", dir.Name);

               switch (count)
               {
                  case 0:
                     Assert.IsTrue(dir.Name.Equals(subFolders[0]));
                     break;

                  case 1:
                     Assert.IsTrue(dir.Name.Equals(subFolders[2]));
                     break;

                  case 2:
                     Assert.IsTrue(dir.Name.Equals(subFolders[4]));
                     break;
               }

               count++;
            }
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Enumerations/DfsPropertyFlags.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Network
{
   /// <summary>A set of bit flags that describe specific properties of a DFS namespace, root, or link.</summary>
   [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags")]
   [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")]
   [Flags]
   public enum DfsPropertyFlags
   {
      /// <summary>No property flag.</summary>
      None = 0,

      /// <summary>DFS_PROPERTY_FLAG_INSITE_REFERRALS
      /// <para>
      ///   Scope: Domain roots, stand-alone roots, and links.
      ///   If this flag is set at the DFS root, it applies to all links; otherwise, the value of this flag is considered for each individual link.
      /// </para>
      /// <para>
      ///   When this flag is set, a DFS referral response from a DFS server for a DFS root or link with the "INSITE" option enabled contains only
      ///   those targets which are in the same site as the DFS client requesting the referral.
      ///   Targets in the two global priority classes are always returned, regardless of their site location.
      /// </para>
      /// </summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Insite")]
      InsiteReferrals = 1,

      /// <summary>DFS_PROPERTY_FLAG_ROOT_SCALABILITY
      /// <para>
      ///   Scope: The entire DFS namespace for a domain-based DFS namespace only.
      /// </para>
      /// <para>
      ///   By default, a DFS root target server polls the PDS to detect changes to the DFS metadata.
      ///   To prevent heavy server load on the PDC, root scalability can be enabled for the DFS namespace.
      ///   Setting this flag will cause the DFS server to poll the nearest domain controller instead of the PDC for DFS metadata changes for the common namespace.
      ///   Note that any changes made to the metadata must still occur on the PDC, however.
      /// </para>
      /// </summary>
      RootScalability = 2,

      /// <summary>DFS_PROPERTY_FLAG_SITE_COSTING
      /// <para>
      ///   Scope: The entire DFS namespace for both domain-based and stand-alone DFS namespaces.
      /// </para>
      /// <para>
      ///   By default, targets returned in a referral response from a DFS server to a DFS client for a DFS root or link
      ///   consists of two groups: targets in the same site as the client, and targets outside the site.
      /// </para>
      /// <para>
      ///   If site-costing is enabled for the Active Directory, the response can have more than two groups,
      ///   with each group containing targets with the same site cost for the specific DFS client requesting the referral.
      ///   The groups are ordered by increasing site cost. For more information about how site-costing is used to prioritize targets.
      /// </para>
      /// </summary>
      SiteCosting = 4,

      /// <summary>DFS_PROPERTY_FLAG_TARGET_FAILBACK
      /// <para>
      ///   Scope: Domain-based DFS roots, stand-alone DFS roots, and DFS links.
      ///   If this flag is set at the DFS root, it applies to all links; otherwise, the value of this flag is considered for each individual link.
      /// </para>
      /// <para>
      ///   When this flag is set, optimal target failback is enabled for V4 DFS clients,
      ///   allowing them to fail back to an optimal target after failing over to a non-optimal one.
      ///   The target failback setting is provided to the DFS client in a V4 referral response by a DFS server.
      /// </para>
      /// </summary>
      TargetFailback = 8,

      /// <summary>DFS_PROPERTY_FLAG_CLUSTER_ENABLED
      /// <para>Scope: Stand-alone DFS roots and links only.</para>
      /// <para>The DFS root is clustered to provide high availability for storage failover.</para>
      /// </summary>
      ClusterEnabled = 16,

      /// <summary>DFS_PROPERTY_FLAG_ABDE
      /// <para>Scope: Domain-based DFS roots and stand-alone DFS roots.</para>
      /// <para>When this flag is set, Access-Based Directory Enumeration (ABDE) mode support is enabled on the entire DFS root target share of the DFS namespace.</para>
      /// </summary>
      AccessBasedDirectoryEnumeration = 32
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_UserExplicitDenyOnDestinationFolder_ThrowsUnauthorizedAccessException.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class CopyTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_Copy_UserExplicitDenyOnDestinationFolder_ThrowsUnauthorizedAccessException_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_Copy_UserExplicitDenyOnDestinationFolder_ThrowsUnauthorizedAccessException(false);
         AlphaFS_Directory_Copy_UserExplicitDenyOnDestinationFolder_ThrowsUnauthorizedAccessException(true);
      }
      

      private void AlphaFS_Directory_Copy_UserExplicitDenyOnDestinationFolder_ThrowsUnauthorizedAccessException(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var srcFolder = tempRoot.CreateTree();
            var dstFolder = tempRoot.CreateDirectory();

            Console.WriteLine("Src Directory Path: [{0}]", srcFolder.FullName);
            Console.WriteLine("Dst Directory Path: [{0}]", dstFolder.FullName);
            

            var user = (Environment.UserDomainName + @"\" + Environment.UserName).TrimStart('\\');

            var rule = new System.Security.AccessControl.FileSystemAccessRule(user,
               System.Security.AccessControl.FileSystemRights.FullControl,
               System.Security.AccessControl.InheritanceFlags.ContainerInherit |
               System.Security.AccessControl.InheritanceFlags.ObjectInherit,
               System.Security.AccessControl.PropagationFlags.None,
               System.Security.AccessControl.AccessControlType.Deny);


            // Set DENY for current user.
            var dirSecurity = dstFolder.GetAccessControl();
            dirSecurity.AddAccessRule(rule);
            dstFolder.SetAccessControl(dirSecurity);


            try
            {
               UnitTestAssert.ThrowsException<UnauthorizedAccessException>(() => Alphaleonis.Win32.Filesystem.Directory.Copy(srcFolder.FullName, dstFolder.FullName));
            }
            finally
            {
               // Remove DENY for current user.
               dirSecurity = dstFolder.GetAccessControl();
               dirSecurity.RemoveAccessRule(rule);
               dstFolder.SetAccessControl(dirSecurity);
            }
         }
         
         Console.WriteLine();
      }


      // ╔═════════════╦═════════════╦═══════════════════════════════╦════════════════════════╦══════════════════╦═══════════════════════╦═════════════╦═════════════╗
      // ║             ║ folder only ║ folder, sub-folders and files ║ folder and sub-folders ║ folder and files ║ sub-folders and files ║ sub-folders ║    files    ║
      // ╠═════════════╬═════════════╬═══════════════════════════════╬════════════════════════╬══════════════════╬═══════════════════════╬═════════════╬═════════════╣
      // ║ Propagation ║ none        ║ none                          ║ none                   ║ none             ║ InheritOnly           ║ InheritOnly ║ InheritOnly ║
      // ║ Inheritance ║ none        ║ Container|Object              ║ Container              ║ Object           ║ Container|Object      ║ Container   ║ Object      ║
      // ╚═════════════╩═════════════╩═══════════════════════════════╩════════════════════════╩══════════════════╩═══════════════════════╩═════════════╩═════════════╝
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.GetDriveFormat.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Gets the name of the file system, such as NTFS or FAT32.</summary>
      /// <remarks>Use DriveFormat to determine what formatting a drive uses.</remarks>
      /// <param name="drivePath">
      ///   A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\".
      /// </param>
      /// <returns>The name of the file system on the specified drive or <c>null</c>  on failure or if not available.</returns>
      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      [SecurityCritical]
      public static string GetDriveFormat(string drivePath)
      {
         var fsName = new VolumeInfo(drivePath, true, true).FileSystemName;

         return Utils.IsNullOrWhiteSpace(fsName) ? null : fsName;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.ReplaceCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file and optionally ignores merge errors.</summary>
      /// <remarks>The Replace method replaces the contents of a specified file with the contents of another file. It also creates a backup of the file that was replaced.</remarks>
      /// <remarks>
      ///   If the <paramref name="sourceFileName"/> and <paramref name="destinationFileName"/> are on different volumes, this method will
      ///   raise an exception. If the <paramref name="destinationBackupFileName"/> is on a different volume from the source file, the backup
      ///   file will be deleted.
      /// </remarks>
      /// <remarks>
      ///   Pass null to the <paramref name="destinationBackupFileName"/> parameter if you do not want to create a backup of the file being
      ///   replaced.
      /// </remarks>
      /// <param name="sourceFileName">The name of a file that replaces the file specified by <paramref name="destinationFileName"/>.</param>
      /// <param name="destinationFileName">The name of the file being replaced.</param>
      /// <param name="destinationBackupFileName">The name of the backup file.</param>
      /// <param name="ignoreMetadataErrors">
      ///   <c>true</c> to ignore merge errors (such as attributes and access control lists (ACLs)) from the replaced file to the
      ///   replacement file; otherwise, <c>false</c>.
      /// </param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>      
      [SecurityCritical]
      internal static void ReplaceCore(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors, PathFormat pathFormat)
      {
         const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck;

         var sourceFileNameLp = sourceFileName;
         var destinationFileNameLp = destinationFileName;


         if (pathFormat != PathFormat.LongFullPath)
         {
            sourceFileNameLp = Path.GetExtendedLengthPathCore(null, sourceFileName, pathFormat, options);
            destinationFileNameLp = Path.GetExtendedLengthPathCore(null, destinationFileName, pathFormat, options);
         }


         // Pass null to the destinationBackupFileName parameter if you do not want to create a backup of the file being replaced.
         var destinationBackupFileNameLp = null == destinationBackupFileName
            ? null
            : Path.GetExtendedLengthPathCore(null, destinationBackupFileName, pathFormat, options);


         const int replacefileWriteThrough = 1;
         const int replacefileIgnoreMergeErrors = 2;


         var dwReplaceFlags = (FileSystemRights) replacefileWriteThrough;

         if (ignoreMetadataErrors)
            dwReplaceFlags |= (FileSystemRights) replacefileIgnoreMergeErrors;


         // ReplaceFile()
         // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
         // 2017-05-30: MSDN confirms LongPath usage: Starting with Windows 10, version 1607

         var success = NativeMethods.ReplaceFile(destinationFileNameLp, sourceFileNameLp, destinationBackupFileNameLp, dwReplaceFlags, IntPtr.Zero, IntPtr.Zero);

         var lastError = (uint) Marshal.GetLastWin32Error();
         if (!success)
            NativeError.ThrowException(lastError, sourceFileNameLp, destinationFileNameLp);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.EnumerateAlternateDataStreamsCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>[AlphaFS] Enumerates the streams of type :$DATA from the specified file or directory.</summary>
      /// <param name="transaction">The transaction.</param>
      /// <param name="isFolder">When <c>true</c> indicates the source is a directory; file otherwise.</param>
      /// <param name="path">The path to the file or directory to enumerate streams of.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>An enumeration of <see cref="AlternateDataStreamInfo"/> instances.</returns>
      [SecurityCritical]
      internal static IEnumerable<AlternateDataStreamInfo> EnumerateAlternateDataStreamsCore(KernelTransaction transaction, bool isFolder, string path, PathFormat pathFormat)
      {
         var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars | GetFullPathOptions.CheckAdditional);

         using (var buffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(NativeMethods.WIN32_FIND_STREAM_DATA))))

         using (var safeFindFileHandle = FindFirstStreamNative(transaction, pathLp, buffer))
         {
            if (null != safeFindFileHandle)
               while (true)
               {
                  yield return new AlternateDataStreamInfo(pathLp, buffer.PtrToStructure<NativeMethods.WIN32_FIND_STREAM_DATA>(0));

                  var success = NativeMethods.FindNextStreamW(safeFindFileHandle, buffer);

                  var lastError = Marshal.GetLastWin32Error();

                  if (!success)
                  {
                     if (lastError == Win32Errors.ERROR_HANDLE_EOF)
                        break;

                     NativeError.ThrowException(lastError, isFolder, pathLp);
                  }
               }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] 
      ///   Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total
      ///   amount of free space, and the total amount of free space available to the user that is associated with the calling thread.
      /// </summary>
      /// <remarks>The calling application must have FILE_LIST_DIRECTORY access rights for this directory.</remarks>
      /// <param name="drivePath">
      ///   A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\".
      /// </param>
      /// <returns>A <see ref="Alphaleonis.Win32.Filesystem.DiskSpaceInfo"/> class instance.</returns>
      [SecurityCritical]
      public static DiskSpaceInfo GetDiskFreeSpace(string drivePath)
      {
         return new DiskSpaceInfo(drivePath, null, true, true);
      }


      /// <summary>[AlphaFS] 
      ///   Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total
      ///   amount of free space, and the total amount of free space available to the user that is associated with the calling thread.
      /// </summary>
      /// <remarks>The calling application must have FILE_LIST_DIRECTORY access rights for this directory.</remarks>
      /// <param name="drivePath">
      ///   A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\".
      /// </param>
      /// <param name="spaceInfoType">
      ///   <c>null</c> gets both size- and disk cluster information. <c>true</c> Get only disk cluster information,
      ///   <c>false</c> Get only size information.
      /// </param>
      /// <returns>A <see ref="Alphaleonis.Win32.Filesystem.DiskSpaceInfo"/> class instance.</returns>
      [SecurityCritical]
      public static DiskSpaceInfo GetDiskFreeSpace(string drivePath, bool? spaceInfoType)
      {
         return new DiskSpaceInfo(drivePath, spaceInfoType, true, true);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationOptions.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>[AlphaFS] Directory enumeration options, flags that specify how a directory is to be enumerated.</summary>
   [Flags]
   public enum DirectoryEnumerationOptions
   {
      /// <summary>None (do not use).</summary>
      None = 0,

      /// <summary>Enumerate files only.</summary>
      Files = 1,

      /// <summary>Enumerate directories only.</summary>
      Folders = 2,

      /// <summary>Enumerate files and directories.</summary>
      FilesAndFolders = Files | Folders,

      /// <summary>Return full path as long full path (Unicode format), only valid when return type is <see cref="string"/>.</summary>
      AsLongPath = 4,

      /// <summary>Skip reparse points during directory enumeration.</summary>
      SkipReparsePoints = 8,

      /// <summary>Suppress any Exception that might be thrown as a result from a failure, such as ACLs protected directories or non-accessible reparse points.</summary>
      ContinueOnException = 16,

      /// <summary>Specifies whether to search the current directory, or the current directory and all subdirectories.</summary>
      Recursive = 32,

      /// <summary>Enumerates the directory without querying the short file name, improving overall enumeration speed.</summary>
      /// <remarks>This option is enabled by default if supported. This value is not supported until Windows Server 2008 R2 and Windows 7.</remarks>
      BasicSearch = 64,

      /// <summary>Enumerates the directory using a larger buffer for directory queries, which can increase performance of the find operation.</summary>
      /// <remarks>This option is enabled by default if supported. This value is not supported until Windows Server 2008 R2 and Windows 7.</remarks>
      LargeCache = 128
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateHardlink_And_EnumerateHardlinks.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_JunctionsLinksTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>

      [TestMethod]
      public void AlphaFS_File_CreateHardLink_And_EnumerateHardLinks_Local_Success()
      {
         AlphaFS_File_CreateHardLink_And_EnumerateHardLinks();
      }


      private void AlphaFS_File_CreateHardLink_And_EnumerateHardLinks()
      {
         using (var tempRoot = new TemporaryDirectory())
         {
            var hardlinkFolder = System.IO.Path.Combine(tempRoot.Directory.FullName, "Hardlinks");
            System.IO.Directory.CreateDirectory(hardlinkFolder);


            var file = System.IO.Path.Combine(tempRoot.Directory.FullName, "OriginalFile.txt");
            Console.WriteLine("Input File Path: [{0}]\n", file);

            // Create original file with text content.
            System.IO.File.WriteAllText(file, DateTime.Now.ToString(CultureInfo.CurrentCulture));


            // Create a random number of hardlinks to the original file.
            var numCreate = new Random().Next(1, 20);
            var hardlinks = new List<string>();

            Console.WriteLine("Created {0} hardlinks:", numCreate + 1);

            for (var i = 0; i < numCreate; i++)
            {
               var newfile = System.IO.Path.Combine(hardlinkFolder, i + "-Hardlink-" + tempRoot.RandomTxtFileName);

               Alphaleonis.Win32.Filesystem.File.CreateHardLink(newfile, file);

               hardlinks.Add(newfile);
            }


            var cnt = 0;
            foreach (var hardLink in Alphaleonis.Win32.Filesystem.File.EnumerateHardLinks(file))
               Console.WriteLine("\t\t#{0:000}\tHardlink: [{1}]", ++cnt, hardLink);

            Assert.AreEqual(numCreate + 1, cnt);


            using (var stream = System.IO.File.OpenRead(file))
            {
               var bhfi = Alphaleonis.Win32.Filesystem.File.GetFileInfoByHandle(stream.SafeFileHandle);

               Assert.AreEqual(numCreate + 1, bhfi.NumberOfLinks);

               Console.WriteLine("\n\n\tByHandleFileInfo for Input Path, see property: NumberOfLinks");
               UnitTestConstants.Dump(bhfi);
            }
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Security/ProcessContext.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Microsoft.Win32;

namespace Alphaleonis.Win32.Security
{
   /// <summary>[AlphaFS] Class to determine the context of the current process.</summary>
   public static class ProcessContext
   {
      #region Properties

      /// <summary>[AlphaFS] Determines if the current process is run in the context of an Administrator.</summary>
      /// <returns><c>true</c> if the current process is run in the context of an Administrator; otherwise, <c>false</c>.</returns>
      public static bool IsAdministrator
      {
         get
         {
            WindowsIdentity windowsIdentity;
            var principal = GetWindowsPrincipal(out windowsIdentity);

            using (windowsIdentity)
               return

                  // Local Administrator.
                  principal.IsInRole(WindowsBuiltInRole.Administrator) ||

                  // Domain Administrator.
                  principal.IsInRole(512);
         }
      }


      /// <summary>[AlphaFS] Determines if UAC is enabled and that the current process is in an elevated state.
      /// <para>If the current User is the default Administrator then the process is assumed to be in an elevated state.</para>
      /// <para>This assumption is made because by default, the default Administrator (disabled by default) gets all access rights without showing an UAC prompt.</para>
      /// </summary>
      /// <returns><c>true</c> if UAC is enabled and the current process is in an elevated state; otherwise, <c>false</c>.</returns>
      public static bool IsElevatedProcess
      {
         get
         {
            return IsUacEnabled && (GetProcessElevationType() == NativeMethods.TOKEN_ELEVATION_TYPE.TokenElevationTypeFull || IsAdministrator);
         }
      }


      /// <summary>[AlphaFS] Determines if UAC is enabled by reading the "EnableLUA" registry key of the local Computer.</summary>
      /// <returns><c>true</c> if the UAC status was successfully read from registry; otherwise, <c>false</c>.</returns>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Uac")]
      public static bool IsUacEnabled
      {
         get
         {
            using (var uacKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", false))

               return null != uacKey && uacKey.GetValue("EnableLUA").Equals(1);
         }
      }


      /// <summary>[AlphaFS] Determines if the current process is run in the context of a Windows Service.</summary>
      /// <returns><c>true</c> if the current process is run in the context of a Windows Service; otherwise, <c>false</c>.</returns>
      public static bool IsWindowsService
      {
         get
         {
            WindowsIdentity windowsIdentity;
            var principal = GetWindowsPrincipal(out windowsIdentity);

            using (windowsIdentity)
               return principal.IsInRole(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null)) ||
                      principal.IsInRole(new SecurityIdentifier(WellKnownSidType.ServiceSid, null));
         }
      }

      #endregion // Properties


      private static WindowsPrincipal GetWindowsPrincipal(out WindowsIdentity windowsIdentity)
      {
         windowsIdentity = WindowsIdentity.GetCurrent();

         if (null == windowsIdentity)
            throw new InvalidOperationException(Resources.GetCurrentWindowsIdentityFailed);

         return new WindowsPrincipal(windowsIdentity);
      }


      /// <summary>[AlphaFS] Retrieves the elevation type of the current process.</summary>
      /// <returns>A <see cref="NativeMethods.TOKEN_ELEVATION_TYPE"/> value.</returns>
      [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "GetTokenInformation")]
      [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "OpenProcessToken")]
      private static NativeMethods.TOKEN_ELEVATION_TYPE GetProcessElevationType()
      {
         SafeTokenHandle tokenHandle;

         var success = NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle, NativeMethods.TOKEN.TOKEN_READ, out tokenHandle);

         var lastError = Marshal.GetLastWin32Error();
         if (!success)
            throw new Win32Exception(lastError, string.Format(CultureInfo.CurrentCulture, "{0}: OpenProcessToken failed with error: {1}", MethodBase.GetCurrentMethod().Name, lastError.ToString(CultureInfo.CurrentCulture)));


         using (tokenHandle)
         using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(Enum.GetUnderlyingType(typeof(NativeMethods.TOKEN_ELEVATION_TYPE)))))
         {
            uint bytesReturned;
            success = NativeMethods.GetTokenInformation(tokenHandle, NativeMethods.TOKEN_INFORMATION_CLASS.TokenElevationType, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned);

            lastError = Marshal.GetLastWin32Error();

            if (!success)
               throw new Win32Exception(lastError, string.Format(CultureInfo.CurrentCulture, "{0}: GetTokenInformation failed with error: {1}", MethodBase.GetCurrentMethod().Name, lastError.ToString(CultureInfo.CurrentCulture)));


            return (NativeMethods.TOKEN_ELEVATION_TYPE) safeBuffer.ReadInt32();
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Device/Volume/Volume.VolumeLabel.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Volume
   {
      /// <summary>[AlphaFS] Deletes the label of the file system volume that is the root of the current directory.</summary>
      [SecurityCritical]
      public static void DeleteCurrentVolumeLabel()
      {
         SetVolumeLabel(null, null);
      }


      /// <summary>[AlphaFS] Deletes the label of a file system volume.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="rootPathName">The root directory of a file system volume. This is the volume the function will remove the label.</param>
      [SecurityCritical]
      public static void DeleteVolumeLabel(string rootPathName)
      {
         if (Utils.IsNullOrWhiteSpace(rootPathName))
            throw new ArgumentNullException("rootPathName");


         SetVolumeLabel(rootPathName, null);
      }


      /// <summary>[AlphaFS] Retrieve the label of a file system volume.</summary>
      /// <param name="volumePath">
      ///   A path to a volume. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\".
      /// </param>
      /// <returns>The the label of the file system volume. This function can return <c>string.Empty</c> since a volume label is generally not mandatory.</returns>
      [SecurityCritical]
      public static string GetVolumeLabel(string volumePath)
      {
         return new VolumeInfo(volumePath, true, true).Name;
      }


      /// <summary>[AlphaFS] Sets the label of the file system volume that is the root of the current directory.</summary>
      /// <exception cref="ArgumentNullException"/>
      /// <param name="volumeName">A name for the volume.</param>
      [SecurityCritical]
      public static void SetCurrentVolumeLabel(string volumeName)
      {
         if (Utils.IsNullOrWhiteSpace(volumeName))
            throw new ArgumentNullException("volumeName");


         var success = NativeMethods.SetVolumeLabel(null, volumeName);

         var lastError = Marshal.GetLastWin32Error();
         if (!success)
            NativeError.ThrowException(lastError, volumeName);
      }


      /// <summary>[AlphaFS] Sets the label of a file system volume.</summary>
      /// <param name="volumePath">
      ///   <para>A path to a volume. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\"</para>
      ///   <para>If this parameter is <c>null</c>, the function uses the current drive.</para>
      /// </param>
      /// <param name="volumeName">
      ///   <para>A name for the volume.</para>
      ///   <para>If this parameter is <c>null</c>, the function deletes any existing label</para>
      ///   <para>from the specified volume and does not assign a new label.</para>
      /// </param>
      [SecurityCritical]
      public static void SetVolumeLabel(string volumePath, string volumeName)
      {
         // rootPathName == null is allowed, means current drive.

         // Setting volume label only applies to Logical Drives pointing to local resources.
         //if (!Path.IsLocalPath(rootPathName))
         //return false;

         volumePath = Path.AddTrailingDirectorySeparator(volumePath, false);

         // NTFS uses a limit of 32 characters for the volume label as of Windows Server 2003.
         using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
         {
            var success = NativeMethods.SetVolumeLabel(volumePath, volumeName);

            var lastError = Marshal.GetLastWin32Error();
            if (!success)
               NativeError.ThrowException(lastError, volumePath, volumeName);
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Native Other/DFS_STORAGE_INFO_1.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>Contains information about a DFS target, including the DFS target server name and share name as well as the target's state and priority.</summary>
      /// <remarks>Minimum supported client: Windows Vista</remarks>
      /// <remarks>Minimum supported server: Windows Server 2008, Windows Server 2003 with SP1</remarks>
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      internal struct DFS_STORAGE_INFO_1
      {
         /// <summary>State of the target.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly DfsStorageStates State;

         /// <summary>The DFS root target or link target server name.</summary>
         [MarshalAs(UnmanagedType.LPWStr)] public readonly string ServerName;

         /// <summary>The DFS root target or link target share name.</summary>
         [MarshalAs(UnmanagedType.LPWStr)] public readonly string ShareName;

         /// <summary>DFS_TARGET_PRIORITY structure that contains a DFS target's priority class and rank.</summary>
         [MarshalAs(UnmanagedType.Struct)] public readonly DFS_TARGET_PRIORITY TargetPriority;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Exceptions/DeviceNotReadyException.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Serialization;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>[AlphaFS] The requested operation could not be completed because the device is not ready.</summary>
   [Serializable]
   public class DeviceNotReadyException : System.IO.IOException
   {
      private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_NOT_READY);
      private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_NOT_READY, new Win32Exception((int) Win32Errors.ERROR_NOT_READY).Message.Trim().TrimEnd('.').Trim());


      /// <summary>[AlphaFS] Initializes a new instance of the <see cref="DeviceNotReadyException"/> class.</summary>
      public DeviceNotReadyException() : base(string.Format(CultureInfo.InvariantCulture, "{0}.", ErrorText), ErrorCode)
      {
      }


      /// <summary>[AlphaFS] Initializes a new instance of the <see cref="DeviceNotReadyException"/> class.</summary>
      /// <param name="message">The message.</param>
      public DeviceNotReadyException(string message) : base(message, ErrorCode)
      {
      }


      /// <summary>[AlphaFS] Initializes a new instance of the <see cref="DeviceNotReadyException"/> class.</summary>
      /// <param name="path">The path to the file system object.</param>
      /// <param name="isPath">Always set to true when using this constructor.</param>
      [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "isPath")]
      public DeviceNotReadyException(string path, bool isPath) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, Path.GetCleanExceptionPath(path)), ErrorCode)
      {
      }


      /// <summary>[AlphaFS] Initializes a new instance of the <see cref="DeviceNotReadyException"/> class.</summary>
      /// <param name="path">The path to the device.</param>
      /// <param name="innerException">The inner exception.</param>
      public DeviceNotReadyException(string path, Exception innerException) : base(string.Format(CultureInfo.InvariantCulture, "{0}: [{1}]", ErrorText, Path.GetCleanExceptionPath(path)), innerException)
      {
      }


      /// <summary>[AlphaFS] Initializes a new instance of the <see cref="DeviceNotReadyException"/> class.</summary>
      /// <param name="info">The data for serializing or deserializing the object.</param>
      /// <param name="context">The source and destination for the object.</param>
      protected DeviceNotReadyException(SerializationInfo info, StreamingContext context) : base(info, context)
      {
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CreateJunctionCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Globalization;
using System.IO;
using System.Security;
using System.Security.AccessControl;
using Microsoft.Win32.SafeHandles;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). Overwriting a junction point of the same name is allowed.</summary>
      /// <returns>Returns the long path to the directory junction.</returns>
      /// <remarks>
      /// The directory must be empty and reside on a local volume.
      /// The directory date and time stamps from <paramref name="directoryPath"/> (the target) are copied to the directory junction.
      /// <para>
      ///   MSDN: A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories,
      ///   and a junction can link directories located on different local volumes on the same computer.
      ///   Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.
      /// </para>
      /// </remarks>
      /// <exception cref="AlreadyExistsException"/>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="junctionPath">The path of the junction point to create.</param>
      /// <param name="directoryPath">The path to the directory. If the directory does not exist it will be created.</param>
      /// <param name="overwrite"><c>true</c> to overwrite an existing junction point. The directory is removed and recreated.</param>
      /// <param name="copyTargetTimestamps"><c>true</c> to copy the target date and time stamps to the directory junction.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static string CreateJunctionCore(KernelTransaction transaction, string junctionPath, string directoryPath, bool overwrite, bool copyTargetTimestamps, PathFormat pathFormat)
      {
         if (pathFormat != PathFormat.LongFullPath)
         {
            Path.CheckSupportedPathFormat(directoryPath, true, true);
            Path.CheckSupportedPathFormat(junctionPath, true, true);

            directoryPath = Path.GetExtendedLengthPathCore(transaction, directoryPath, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator);
            junctionPath = Path.GetExtendedLengthPathCore(transaction, junctionPath, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator);

            pathFormat = PathFormat.LongFullPath;
         }


         // Directory Junction logic.


         // Check if drive letter is a mapped network drive.
         if (new DriveInfo(directoryPath).IsUnc)
            throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Network_Path_Not_Allowed, directoryPath), "directoryPath");

         if (new DriveInfo(junctionPath).IsUnc)
            throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Network_Path_Not_Allowed, junctionPath), "junctionPath");


         // Check for existing file.
         File.ThrowIOExceptionIfFsoExist(transaction, false, directoryPath, pathFormat);
         File.ThrowIOExceptionIfFsoExist(transaction, false, junctionPath, pathFormat);


         // Check for existing directory junction folder.
         if (File.ExistsCore(transaction, true, junctionPath, pathFormat))
         {
            if (overwrite)
            {
               DeleteDirectoryCore(transaction, null, junctionPath, true, true, true, pathFormat);

               CreateDirectoryCore(true, transaction, junctionPath, null, null, false, pathFormat);
            }

            else
            {
               // Ensure the folder is empty.
               if (!IsEmptyCore(transaction, junctionPath, pathFormat))
                  throw new DirectoryNotEmptyException(junctionPath, true);

               throw new AlreadyExistsException(junctionPath, true);
            }
         }


         // Create the folder and convert it to a directory junction.
         CreateDirectoryCore(true, transaction, junctionPath, null, null, false, pathFormat);

         using (var safeHandle = OpenDirectoryJunction(transaction, junctionPath, pathFormat))
            Device.CreateDirectoryJunction(safeHandle, directoryPath);


         // Copy the target date and time stamps to the directory junction.
         if (copyTargetTimestamps)
            File.CopyTimestampsCore(transaction, true, directoryPath, junctionPath, true, pathFormat);


         return junctionPath;
      }


      private static SafeFileHandle OpenDirectoryJunction(KernelTransaction transaction, string junctionPath, PathFormat pathFormat)
      {
         return File.CreateFileCore(transaction, true, junctionPath, ExtendedFileAttributes.BackupSemantics | ExtendedFileAttributes.OpenReparsePoint, null, FileMode.Open, FileSystemRights.WriteData, FileShare.ReadWrite, false, false, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Network/DfsStorageInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Network
{
   /// <summary>Contains information about a DFS root or link target in a DFS namespace or from the cache maintained by the DFS client.
   /// <para>This class cannot be inherited.</para>
   /// </summary>
   [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")]
   public sealed class DfsStorageInfo
   {
      #region Constructor

      /// <summary>Initializes a new instance of the <see cref="DfsStorageInfo"/> class, which acts as a wrapper for a DFS root or link target.</summary>
      public DfsStorageInfo()
      {
      }

      /// <summary>Initializes a new instance of the <see cref="DfsStorageInfo"/> class, which acts as a wrapper for a DFS root or link target.</summary>
      /// <param name="structure">An initialized <see cref="NativeMethods.DFS_STORAGE_INFO_1"/> instance.</param>
      internal DfsStorageInfo(NativeMethods.DFS_STORAGE_INFO_1 structure)
      {
         ServerName = structure.ServerName;
         ShareName = structure.ShareName;

         State = structure.State;

         TargetPriorityClass = structure.TargetPriority.TargetPriorityClass;
         TargetPriorityRank = structure.TargetPriority.TargetPriorityRank;
      }

      #endregion // Constructor

      #region Methods

      /// <summary>The share name of the DFS root target or link target.</summary>
      /// <returns>A string that represents this instance.</returns>
      public override string ToString()
      {
         return ShareName;
      }

      #endregion // Methods

      #region Properties

      /// <summary>The server name of the DFS root target or link target.</summary>
      public string ServerName { get; private set; }

      /// <summary>The share name of the DFS root target or link target.</summary>
      public string ShareName { get; private set; }

      /// <summary>An <see cref="DfsStorageStates"/> enum of the DFS root target or link target.</summary>
      public DfsStorageStates State { get; private set; }

      /// <summary>Contains a DFS target's priority class and rank.</summary>
      public DfsTargetPriorityClass TargetPriorityClass { get; private set; }

      /// <summary>Specifies the priority rank value of the target. The default value is 0, which indicates the highest priority rank within a priority class.</summary>
      public int TargetPriorityRank { get; private set; }

      #endregion // Properties
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.LocalToUncCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Network;
using System;
using System.Globalization;
using System.IO;
using System.Net.NetworkInformation;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>Converts a local path to a network share path, optionally returning it in a long path format and the ability to add or remove a trailing backslash.
      ///   <para>A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows".</para>
      ///   <para>If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing <see cref="DirectorySeparator"/> character.</para>
      /// </summary>
      /// <returns>On successful conversion a UNC path is returned.
      ///   <para>If the conversion fails, <paramref name="localPath"/> is returned.</para>
      ///   <para>If <paramref name="localPath"/> is an empty string or <c>null</c>, <c>null</c> is returned.</para>
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="PathTooLongException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="localPath">A local path, e.g.: "C:\Windows".</param>
      /// <param name="fullPathOptions">Options for controlling the full path retrieval.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter.</param>
      [SecurityCritical]
      internal static string LocalToUncCore(string localPath, GetFullPathOptions fullPathOptions, PathFormat pathFormat)
      {
         if (Utils.IsNullOrWhiteSpace(localPath))
            return null;

         if (pathFormat == PathFormat.RelativePath)
            CheckSupportedPathFormat(localPath, true, true);
         

         var addTrailingDirectorySeparator = (fullPathOptions & GetFullPathOptions.AddTrailingDirectorySeparator) != 0;
         var removeTrailingDirectorySeparator = (fullPathOptions & GetFullPathOptions.RemoveTrailingDirectorySeparator) != 0;

         if (addTrailingDirectorySeparator && removeTrailingDirectorySeparator)
            throw new ArgumentException(Resources.GetFullPathOptions_Add_And_Remove_DirectorySeparator_Invalid, "fullPathOptions");


         if (!removeTrailingDirectorySeparator && !addTrailingDirectorySeparator)
         {
            // Add a trailing backslash when "localPath" ends with a backslash.
            if (localPath.EndsWith(DirectorySeparator, StringComparison.Ordinal))
            {
               fullPathOptions &= ~GetFullPathOptions.RemoveTrailingDirectorySeparator; // Remove removal of trailing backslash.
               fullPathOptions |= GetFullPathOptions.AddTrailingDirectorySeparator;     // Add adding trailing backslash.
            }
         }


         var getAsLongPath = (fullPathOptions & GetFullPathOptions.AsLongPath) != 0;

         var returnUncPath = GetRegularPathCore(localPath, fullPathOptions | GetFullPathOptions.CheckInvalidPathChars, false);
         

         if (!IsUncPathCore(returnUncPath, true, false))
         {
            if (returnUncPath[0] == CurrentDirectoryPrefixChar || !IsPathRooted(returnUncPath, false))
               returnUncPath = GetFullPathCore(null, false, returnUncPath, GetFullPathOptions.None);


            var drive = GetPathRoot(returnUncPath, false);

            if (Utils.IsNullOrWhiteSpace(drive))
               return returnUncPath;
            

            var remoteInfo = Host.GetRemoteNameInfoCore(returnUncPath, true);


            // Network share.
            if (!Utils.IsNullOrWhiteSpace(remoteInfo.lpUniversalName))
               return getAsLongPath ? GetLongPathCore(remoteInfo.lpUniversalName, fullPathOptions) : GetRegularPathCore(remoteInfo.lpUniversalName, fullPathOptions, false);


            // Network root.
            if (!Utils.IsNullOrWhiteSpace(remoteInfo.lpConnectionName))
               return getAsLongPath ? GetLongPathCore(remoteInfo.lpConnectionName, fullPathOptions) : GetRegularPathCore(remoteInfo.lpConnectionName, fullPathOptions, false);


            // Split: localDrive[0] = "C", localDrive[1] = "\Windows"
            var localDrive = returnUncPath.Split(VolumeSeparatorChar);

            // Return: "\\localhost\C$\Windows"
            returnUncPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", Host.GetUncName(), DirectorySeparator, localDrive[0], NetworkDriveSeparator, localDrive[1]);
         }


         return getAsLongPath ? GetLongPathCore(returnUncPath, fullPathOptions) : GetRegularPathCore(returnUncPath, fullPathOptions, false);
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/DriveInfo.InitializeInstance.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AlphaFS.UnitTest
{
   public partial class DriveInfoTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void DriveInfo_InitializeInstance_LocalAndNetwork_Success()
      {
         DriveInfo_InitializeInstance(false);
         DriveInfo_InitializeInstance(true);
      }
      

      private void DriveInfo_InitializeInstance(bool isNetwork)
      {
         UnitTestConstants.PrintUnitTestHeader(isNetwork);
         
         var drive = UnitTestConstants.SysDrive[0].ToString();

         if (isNetwork)
            // Only using a drive letter results in a wrong UNC path.
            drive = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.SysDrive);

         Console.WriteLine("Input Drive Path: [{0}]", drive);


         var actual = new Alphaleonis.Win32.Filesystem.DriveInfo(drive);

         Assert.IsTrue(actual.IsReady);
         Assert.IsTrue(actual.IsVolume);

         if (isNetwork)
            Assert.IsTrue(actual.IsUnc);
         else
            Assert.IsFalse(actual.IsUnc);


         // System.IO.DriveInfo cannot handle UNC paths.

         if (!isNetwork)
         {
            // Even 1 byte more or less results in failure, so do these tests asap.
            
            var expected = new System.IO.DriveInfo(drive);
            

            Assert.AreEqual(expected.AvailableFreeSpace, actual.AvailableFreeSpace, "AvailableFreeSpace AlphaFS != System.IO");
            Assert.AreEqual(expected.TotalFreeSpace, actual.TotalFreeSpace, "TotalFreeSpace AlphaFS != System.IO");
            Assert.AreEqual(expected.TotalSize, actual.TotalSize, "TotalSize AlphaFS != System.IO");


            Assert.AreEqual(expected.DriveFormat, actual.DriveFormat, "DriveFormat AlphaFS != System.IO");
            Assert.AreEqual(expected.DriveType, actual.DriveType, "DriveType AlphaFS != System.IO");
            Assert.AreEqual(expected.IsReady, actual.IsReady, "IsReady AlphaFS != System.IO");
            Assert.AreEqual(expected.Name, actual.Name, "Name AlphaFS != System.IO");
            Assert.AreEqual(expected.RootDirectory.ToString(), actual.RootDirectory.ToString(), "RootDirectory AlphaFS != System.IO");
            Assert.AreEqual(expected.VolumeLabel, actual.VolumeLabel, "VolumeLabel AlphaFS != System.IO");


            UnitTestConstants.Dump(expected);
            Console.WriteLine();
         }


         UnitTestConstants.Dump(actual);

         UnitTestConstants.Dump(actual.DiskSpaceInfo);

         UnitTestConstants.Dump(actual.VolumeInfo);

         Console.WriteLine();
      }
   }
}


<|start_filename|>build/appveyor-util.cake<|end_filename|>
#l "rest-util.cake"
void DownloadAppVeyorArtifact(string apiUrl, string jobId, string artifactName, string sourceBuildVersion, FilePath targetFile)
{            
    var artifacts = RestInvoke<List<ArtifactInfo>>(apiUrl,  $"buildjobs/{jobId}/artifacts", Method.GET);

    ArtifactInfo matchingArtifact = null;
    foreach (var artifact in artifacts)
    {
        Verbose($"- Found artifact: {artifact.FileName} of type {artifact.Type}");
        if (artifact.FileName.Equals(artifactName, StringComparison.OrdinalIgnoreCase)) {
            if (matchingArtifact != null)
                throw new Exception($"Multiple artifacts matching the name \"{artifactName}\" were found.");
            else
                matchingArtifact = artifact;
        }
    }

    if (matchingArtifact == null)
        throw new FileNotFoundException($"Unable to find artifact named \"{artifactName}\" in build {sourceBuildVersion}.");
    
    Information($"Found matching artifact: {matchingArtifact.FileName}, type={matchingArtifact.Type}, size={matchingArtifact.Size}b");

    var url = apiUrl + $"/buildjobs/{jobId}/artifacts/{WebUtility.UrlEncode(matchingArtifact.FileName)}";          
    Information($"Downloading artifact {matchingArtifact.FileName} to {targetFile.FullPath}");
    DownloadFile(url, targetFile);
}

void PublishAppVeyorTestResult(FilePath trxFile, string appVeyorApiBaseUrl = "https://ci.appveyor.com/api")
{
    if (BuildSystem.IsRunningOnAppVeyor)
    {
        UploadFile($"{appVeyorApiBaseUrl}/testresults/mstest/{BuildSystem.AppVeyor.Environment.JobId}", trxFile);                
    }
}
class ArtifactInfo
{
    public string FileName { get; set; }
    public string Type { get; set; }
    public long Size{ get; set;}
    public DateTime Created { get; set; }
    public string RelativeName => System.IO.Path.GetFileName(FileName);
}

<|start_filename|>src/AlphaFS/Network/Enumerations/ConnectivityStates.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Network
{
   /// <summary>Specifies types of network connectivity state.</summary>    
   [Flags]
   public enum ConnectivityStates
   {
      /// <summary>The underlying network interfaces have no connectivity to any network.</summary>
      None = 0,

      /// <summary>There is connectivity to a network, but the service cannot detect any IPv4 Network Traffic.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")]
      IPv4NoTraffic = 1,

      /// <summary>There is connectivity to a network, but the service cannot detect any IPv6 Network Traffic.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")]
      IPv6NoTraffic = 2,

      /// <summary>There is connectivity to the local subnet using the IPv4 protocol.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")]
      IPv4Subnet = 16,

      /// <summary>There is connectivity to a routed network using the IPv4 protocol.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")]
      IPv4LocalNetwork = 32,

      /// <summary>There is connectivity to the Internet using the IPv4 protocol.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")]
      IPv4Internet = 64,

      /// <summary>There is connectivity to the local subnet using the IPv6 protocol.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")]
      IPv6Subnet = 256,

      /// <summary>There is connectivity to a local network using the IPv6 protocol.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")]
      IPv6LocalNetwork = 512,

      /// <summary>There is connectivity to the Internet using the IPv6 protocol.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")]
      IPv6Internet = 1024
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.WNet.DisconnectDrive.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Security;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>Cancels an existing network connection. You can also call the function to remove remembered network connections that are not currently connected.</summary>
      /// <param name="localName">The name of a local device to be disconnected, such as "F:".</param>
      [SecurityCritical]
      public static void DisconnectDrive(string localName)
      {
         ConnectDisconnectCore(new ConnectDisconnectArguments
         {
            LocalName = localName,
            IsDeviceMap = true,
            IsDisconnect = true
         });
      }

      
      /// <summary>Cancels an existing network connection. You can also call the function to remove remembered network connections that are not currently connected.</summary>
      /// <param name="localName">The name of a local device to be disconnected, such as "F:".</param>
      /// <param name="force">
      ///   Specifies whether the disconnection should occur if there are open files or jobs on the connection.
      ///   If this parameter is <c>false</c>, the function fails if there are open files or jobs.
      /// </param>
      /// <param name="updateProfile"><c>true</c> successful removal of network resource connections will be saved.</param>
      [SecurityCritical]
      public static void DisconnectDrive(string localName, bool force, bool updateProfile)
      {
         ConnectDisconnectCore(new ConnectDisconnectArguments
         {
            LocalName = localName,
            Prompt = force,
            UpdateProfile = updateProfile,
            IsDeviceMap = true,
            IsDisconnect = true
         });
      }
   }
}


<|start_filename|>src/AlphaFS/Network/NetworkInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;

namespace Alphaleonis.Win32.Network
{
   /// <summary>Represents a network on the local machine. It can also represent a collection of network connections with a similar network signature.</summary>
   [Serializable]
   public class NetworkInfo : IEquatable<NetworkInfo>
   {
      #region Private Fields

      [NonSerialized]
      private readonly NativeMethods.INetwork _network;

      #endregion // Private Fields


      #region Constructors

      internal NetworkInfo(NativeMethods.INetwork network)
      {
         _network = network;
      }

      #endregion // Constructors


      #region Properties

      /// <summary>Gets the category of a network. The categories are trusted, untrusted, or authenticated. This value of this property is not cached.</summary>
      public NetworkCategory Category
      {
         get { return _network.GetCategory(); }
      }


      /// <summary>Gets the network connections for the network. This value of this property is not cached.</summary>
      public IEnumerable<NetworkConnectionInfo> Connections
      {
         get
         {
            foreach (var connection in _network.GetNetworkConnections())

               yield return new NetworkConnectionInfo((NativeMethods.INetworkConnection) connection);
         }
      }


      /// <summary>Gets the local date and time when the network was connected. This value of this property is not cached.</summary>
      public DateTime ConnectionTime
      {
         get { return ConnectionTimeUtc.ToLocalTime(); }
      }


      /// <summary>Gets the date and time when the network was connected. This value of this property is not cached.</summary>
      public DateTime ConnectionTimeUtc
      {
         get
         {
            uint low, high, unused1, unused2;

            _network.GetTimeCreatedAndConnected(out unused1, out unused2, out low, out high);
            
            long time = high;

            // Shift the day info into the high order bits.
            time <<= 32;
            time |= low;

            return DateTime.FromFileTimeUtc(time);
         }
      }


      /// <summary>Gets the connectivity state of the network. This value of this property is not cached.</summary>
      /// <remarks>Connectivity provides information on whether the network is connected, and the protocols in use for network traffic.</remarks>
      public ConnectivityStates Connectivity
      {
         get { return _network.GetConnectivity(); }
      }


      /// <summary>Gets the local date and time when the network was created. This value of this property is not cached.</summary>
      public DateTime CreationTime
      {
         get { return CreationTimeUtc.ToLocalTime(); }
      }


      /// <summary>Gets the date and time when the network was created. This value of this property is not cached.</summary>
      public DateTime CreationTimeUtc
      {
         get
         {
            uint low, high, unused1, unused2;

            _network.GetTimeCreatedAndConnected(out low, out high, out unused1, out unused2);

            long time = high;

            // Shift the value into the high order bits.
            time <<= 32;
            time |= low;

            return DateTime.FromFileTimeUtc(time);
         }
      }


      /// <summary>Gets a description for the network. This value of this property is not cached.</summary>
      public string Description
      {
         get { return _network.GetDescription(); }

         // Should we allow this in AlphaFS?
         //private set { _network.SetDescription(value); }
      }


      /// <summary>Gets the domain type of the network. This value of this property is not cached.</summary>
      /// <remarks>The domain indictates whether the network is an Active Directory Network, and whether the machine has been authenticated by Active Directory.</remarks>
      public DomainType DomainType
      {
         get { return _network.GetDomainType(); }
      }


      /// <summary>Gets a value that indicates whether there is network connectivity. This value of this property is not cached.</summary>
      public bool IsConnected
      {
         get { return _network.IsConnected; }
      }


      /// <summary>Gets a value that indicates whether there is Internet connectivity. This value of this property is not cached.</summary>
      public bool IsConnectedToInternet
      {
         get { return _network.IsConnectedToInternet; }
      }


      /// <summary>Gets the name of the network. This value of this property is not cached.</summary>
      public string Name
      {
         get { return _network.GetName(); }

         // Should we allow this in AlphaFS?
         //private set { _network.SetName(value); }
      }


      /// <summary>Gets a unique identifier for the network. This value of this property is not cached.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")]
      public Guid NetworkId
      {
         get { return _network.GetNetworkId(); }
      }

      #endregion // Properties


      #region Methods
      
      /// <summary>Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber".</summary>
      /// <returns>A string that represents this instance.</returns>
      public override string ToString()
      {
         var description = !Utils.IsNullOrWhiteSpace(Description) && !Equals(Name, Description) ? " (" + Description + ")" : string.Empty;

         return null != Name ? string.Format(CultureInfo.CurrentCulture, "{0}{1}, {2}", Name, description, Category) : GetType().Name;
      }


      /// <summary>Serves as a hash function for a particular type.</summary>
      /// <returns>A hash code for the current Object.</returns>
      public override int GetHashCode()
      {
         return Utils.CombineHashCodesOf(NetworkId, Category);
      }
      

      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="other">Another <see cref="NetworkInfo"/> instance to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public bool Equals(NetworkInfo other)
      {
         return null != other && GetType() == other.GetType() &&
                Equals(DomainType, other.DomainType) &&
                Equals(NetworkId, other.NetworkId) &&
                Equals(Category, other.Category) &&
                Equals(CreationTime, other.CreationTime) &&
                Equals(ConnectionTime, other.ConnectionTime);
      }


      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="obj">Another object to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public override bool Equals(object obj)
      {
         var other = obj as NetworkInfo;

         return null != other && Equals(other);
      }


      /// <summary>Implements the operator ==</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator ==(NetworkInfo left, NetworkInfo right)
      {
         return ReferenceEquals(left, null) && ReferenceEquals(right, null) ||
                !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right);
      }


      /// <summary>Implements the operator !=</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator !=(NetworkInfo left, NetworkInfo right)
      {
         return !(left == right);
      }

      #endregion // Methods
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>System-Defined Device Interface Classes</summary>
   /// <remarks>http://msdn.microsoft.com/en-us/library/windows/hardware/ff541389%28v=vs.85%29.aspx</remarks>
   public enum DeviceGuid
   {
      #region 1394 and 61883 Devices

      /// <summary>The BUS1394_CLASS_GUID device interface class is defined for 1394 bus devices.</summary>
      [Description("6BDD1FC1-810F-11d0-BEC7-08002BE2092F")] Bus1394,

      /// <summary>The GUID_61883_CLASS device interface class is defined for devices in the 61883 device setup class.</summary>
      [Description("7EBEFBC0-3200-11d2-B4C2-00A0C9697D07")] Guid61883,

      #endregion // 1394 and 61883 Devices


      #region Battery and ACPI devices

      /// <summary>The GUID_DEVICE_APPLICATIONLAUNCH_BUTTON device interface class is defined for Advanced Configuration and Power Interface (ACPI) application start buttons.</summary>
      [Description("629758EE-986E-4D9E-8E47-DE27F8AB054D")] ApplicationLaunchButton,

      /// <summary>The GUID_DEVICE_BATTERY device interface class is defined for battery devices.</summary>
      [Description("72631E54-78A4-11D0-BCF7-00AA00B7B32A")] Battery,

      /// <summary>The GUID_DEVICE_LID device interface class is defined for Advanced Configuration and Power Interface (ACPI) lid devices.</summary>
      [Description("4AFA3D52-74A7-11d0-be5e-00A0C9062857")] Lid,

      /// <summary>The GUID_DEVICE_MEMORY device interface class is defined for Advanced Configuration and Power Interface (ACPI) memory devices.</summary>
      [Description("3FD0F03D-92E0-45FB-B75C-5ED8FFB01021")] Memory,

      /// <summary>The GUID_DEVICE_MESSAGE_INDICATOR device interface class is defined for Advanced Configuration and Power Interface (ACPI) message indicator devices.</summary>
      [Description("CD48A365-FA94-4CE2-A232-A1B764E5D8B4")] MessageIndicator,

      /// <summary>The GUID_DEVICE_PROCESSOR device interface class is defined for Advanced Configuration and Power Interface (ACPI) processor devices.</summary>
      [Description("97FADB10-4E33-40AE-359C-8BEF029DBDD0")] Processor,

      /// <summary>The GUID_DEVICE_SYS_BUTTON device interface classis defined for Advanced Configuration and Power Interface (ACPI) system power button devices.</summary>
      [Description("4AFA3D53-74A7-11d0-be5e-00A0C9062857")] SysButton,

      /// <summary>The GUID_DEVICE_THERMAL_ZONE device interface class is defined for Advanced Configuration and Power Interface (ACPI) thermal zone devices.</summary>
      [Description("4AFA3D51-74A7-11d0-be5e-00A0C9062857")] ThermalZone,

      #endregion // Battery and ACPI devices


      #region Bluetooth Devices

      /// <summary>The GUID_BTHPORT_DEVICE_INTERFACE device interface class is defined for Bluetooth radios.</summary>
      [Description("0850302A-B344-4fda-9BE9-90576B8D46F0")] Bluetooth,

      #endregion // Bluetooth Devices


      #region Display and Image Devices

      /// <summary>The GUID_DEVINTERFACE_BRIGHTNESS device interface class is defined for display adapter drivers that operate in the context of the Windows Vista Display Driver Model and support brightness control of monitor child devices.</summary>
      [Description("FDE5BBA4-B3F9-46FB-BDAA-0728CE3100B4")] Brightness,

      /// <summary>The GUID_DEVINTERFACE_DISPLAY_ADAPTER device interface class is defined for display views that are supported by display adapters.</summary>
      [Description("5B45201D-F2F2-4F3B-85BB-30FF1F953599")] DisplayAdapter,

      /// <summary>The GUID_DEVINTERFACE_I2C device interface class is defined for display adapter drivers that operate in the context of the Windows Vista Display Driver Model and perform I2C transactions with monitor child devices.</summary>
      [Description("2564AA4F-DDDB-4495-B497-6AD4A84163D7")] I2C,

      /// <summary>The GUID_DEVINTERFACE_IMAGE device interface class is defined for WIA devices and Still Image (STI) devices, including digital cameras and scanners.</summary>
      [Description("6BDD1FC6-810F-11D0-BEC7-08002BE2092F")] StillImage,

      /// <summary>The GUID_DEVINTERFACE_MONITOR device interface class is defined for monitor devices.</summary>
      [Description("E6F07B5F-EE97-4a90-B076-33F57BF4EAA7")] Monitor,

      /// <summary>The GUID_DEVINTERFACE_OPM device interface class is defined for display adapter drivers that operate in the context of the Windows Vista Display Driver Model and support output protection management (OPM) for monitor child devices.</summary>
      [Description("BF4672DE-6B4E-4BE4-A325-68A91EA49C09")] OutputProtectionManagement,

      /// <summary>The GUID_DEVINTERFACE_VIDEO_OUTPUT_ARRIVAL device interface class is defined for child devices of display devices.</summary>
      [Description("1AD9E4F0-F88D-4360-BAB9-4C2D55E564CD")] VideoOutputArrival,

      /// <summary>The GUID_DISPLAY_DEVICE_ARRIVAL device interface class is defined for display adapters.</summary>
      [Description("1CA05180-A699-450A-9A0C-DE4FBE3DDD89")] DisplayDeviceArrival,

      #endregion // Display and Image Devices


      #region Interactive Input Devices

      /// <summary>The GUID_DEVINTERFACE_HID device interface class is defined for HID collections.</summary>
      [Description("4D1E55B2-F16F-11CF-88CB-001111000030")] Hid,

      /// <summary>The GUID_DEVINTERFACE_KEYBOARD device interface class is defined for keyboard devices.</summary>
      [Description("4D1E55B2-F16F-11CF-88CB-001111000030")] Keyboard,

      /// <summary>The GUID_DEVINTERFACE_MOUSE device interface class is defined for mouse devices.</summary>
      [Description("378DE44C-56EF-11D1-BC8C-00A0C91405DD")] Mouse,

      #endregion // Interactive Input Devices


      #region Modem Devices

      /// <summary>The GUID_DEVINTERFACE_MODEM device interface class is defined for modem devices.</summary>
      [Description("2C7089AA-2E0E-11D1-B114-00C04FC2AAE4")] Modem,

      #endregion // Modem Devices


      #region Network Devices

      /// <summary>The GUID_DEVINTERFACE_NET device interface class is defined for network devices.</summary>
      [Description("CAC88484-7515-4C03-82E6-71A87ABAC361")] Network,

      #endregion // Network Devices


      #region Serial and Parallel Port Devices

      /// <summary>The GUID_DEVINTERFACE_COMPORT device interface class is defined for COM ports.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "ComPort")]
      [Description("86E0D1E0-8089-11D0-9CE4-08003E301F73")] ComPort,

      /// <summary>The GUID_DEVINTERFACE_PARALLEL device interface class is defined for parallel ports that support an IEEE 1284-compatible hardware interface.</summary>
      [Description("97F76EF0-F883-11D0-AF1F-0000F800845C")] Parallel,

      /// <summary>The GUID_DEVINTERFACE_PARCLASS device interface class is defined for devices that are attached to a parallel port.</summary>
      [Description("811FC6A5-F728-11D0-A537-0000F8753ED1")] ParallelClass,

      /// <summary>The GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR device interface class is defined for Plug and Play (PnP) serial ports.</summary>
      [Description("4D36E978-E325-11CE-BFC1-08002BE10318")] SerialEnumBusEnumerator,

      #endregion // Serial and Parallel Port Devices


      #region Storage Devices

      /// <summary>The GUID_DEVINTERFACE_CDCHANGER device interface class is defined for CD-ROM changer devices.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cdrom")]
      [Description("53F56312-B6BF-11D0-94F2-00A0C91EFB8B")] CdromChanger,

      /// <summary>The GUID_DEVINTERFACE_CDROM device interface class is defined for CD-ROM storage devices.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cdrom")]
      [Description("53F56308-B6BF-11D0-94F2-00A0C91EFB8B")] Cdrom,

      /// <summary>The GUID_DEVINTERFACE_DISK device interface class is defined for hard disk storage devices.</summary>
      [Description("53F56307-B6BF-11D0-94F2-00A0C91EFB8B")] Disk,

      /// <summary>The GUID_DEVINTERFACE_FLOPPY device interface class is defined for floppy disk storage devices.</summary> 
      [Description("53F56311-B6BF-11D0-94F2-00A0C91EFB8B")] Floppy,

      /// <summary>The GUID_DEVINTERFACE_MEDIUMCHANGER device interface class is defined for medium changer devices.</summary> 
      [Description("53F56310-B6BF-11D0-94F2-00A0C91EFB8B")] MediumChanger,

      /// <summary>The GUID_DEVINTERFACE_PARTITION device interface class is defined for partition devices.</summary> 
      [Description("53F5630A-B6BF-11D0-94F2-00A0C91EFB8B")] Partition,

      /// <summary>The GUID_DEVINTERFACE_STORAGEPORT device interface class is defined for storage port devices.</summary> 
      [Description("2ACCFE60-C130-11D2-B082-00A0C91EFB8B")] StoragePort,

      /// <summary>The GUID_DEVINTERFACE_TAPE device interface class is defined for tape storage devices.</summary> 
      [Description("53F5630B-B6BF-11D0-94F2-00A0C91EFB8B")] Tape,

      /// <summary>The GUID_DEVINTERFACE_VOLUME device interface class is defined for volume devices.</summary> 
      [Description("53F5630D-B6BF-11D0-94F2-00A0C91EFB8B")] Volume,

      /// <summary>The GUID_DEVINTERFACE_WRITEONCEDISK device interface class is defined for write-once disk devices.</summary> 
      [Description("53F5630C-B6BF-11D0-94F2-00A0C91EFB8B")] WriteOnceDisk,

      #endregion // Storage Devices


      #region USB Devices

      /// <summary>The GUID_DEVINTERFACE_USB_DEVICE device interface class is defined for USB devices that are attached to a USB hub.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")]
      [Description("A5DCBF10-6530-11D2-901F-00C04FB951ED")] UsbDevice,

      /// <summary>The GUID_DEVINTERFACE_USB_HOST_CONTROLLER device interface class is defined for USB host controller devices.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")]
      [Description("3ABF6F2D-71C4-462A-8A92-1E6861E6AF27")] UsbHostController,

      /// <summary>The GUID_DEVINTERFACE_USB_HUB device interface class is defined for USB hub devices.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")]
      [Description("F18A0E88-C30C-11D0-8815-00A0C906BED8")] UsbHub,

      #endregion // USB Devices


      #region Windows Portable devices

      /// <summary>The GUID_DEVINTERFACE_WPD device interface class is defined for Windows Portable Devices (WPD).</summary>
      /// <remarks>Available in Windows Vista, Windows XP, and later versions of Windows.</remarks>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wpd")]
      [Description("6AC27878-A6FA-4155-BA85-F98F491D4F33")] Wpd,

      /// <summary>The GUID_DEVINTERFACE_WPD_PRIVATE device interface class is defined for specialized Windows Portable Devices (WPD).</summary>
      /// <remarks>Available in Windows Vista, Windows XP, and later versions of Windows.</remarks>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wpd")]
      [Description("BA0C718F-4DED-49B7-BDD3-FABE28661211")] WpdPrivate

      #endregion // Windows Portable devices
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Path Class/Path Core Methods/Path.GetPathRootCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Path
   {
      /// <summary>Gets the root directory information of the specified path.</summary>
      /// <returns>
      ///   Returns the root directory of <paramref name="path"/>, such as "C:\",
      ///   or <c>null</c> if <paramref name="path"/> is <c>null</c>,
      ///   or an empty string if <paramref name="path"/> does not contain root directory information.
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <param name="path">The path from which to obtain root directory information.</param>
      /// <param name="checkInvalidPathChars"><c>true</c> will check <paramref name="path"/> for invalid path characters.</param>
      [SecurityCritical]
      internal static string GetPathRootCore(string path, bool checkInvalidPathChars)
      {
         if (null == path)
            return null;

         if (path.Trim().Length == 0)
            throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "path");


         var pathRp = GetRegularPathCore(path,checkInvalidPathChars ? GetFullPathOptions.CheckInvalidPathChars : GetFullPathOptions.None, false);

         var rootLengthPath = GetRootLength(path, false);

         var rootLengthPathRp = GetRootLength(pathRp, false);


         // Check if pathRp is an empty string.

         if (rootLengthPathRp == 0 && path.StartsWith(LongPathPrefix, StringComparison.Ordinal))

            return GetLongPathCore(path.Substring(0, rootLengthPath), GetFullPathOptions.None);


         return path.StartsWith(LongPathUncPrefix, StringComparison.OrdinalIgnoreCase) ? GetLongPathCore(pathRp.Substring(0, rootLengthPathRp), GetFullPathOptions.None) : path.Substring(0, rootLengthPath);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Shell32Info.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Contains Shell32 information about a file.</summary>
   [Serializable]
   [SecurityCritical]
   public sealed class Shell32Info
   {
      #region Constructors

      /// <summary>Initializes a Shell32Info instance.</summary>
      /// <remarks>Shell32 is limited to <c>MAX_PATH</c> length.</remarks>
      /// <remarks>This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations.</remarks>
      /// <param name="fileName">The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character.</param>
      public Shell32Info(string fileName) : this(fileName, PathFormat.RelativePath)
      {
      }

      /// <summary>Initializes a Shell32Info instance.</summary>
      /// <remarks>Shell32 is limited to <c>MAX_PATH</c> length.</remarks>
      /// <remarks>This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations.</remarks>
      /// <param name="fileName">The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      public Shell32Info(string fileName, PathFormat pathFormat)
      {
         if (Utils.IsNullOrWhiteSpace(fileName))
            throw new ArgumentNullException("fileName");

         // Shell32 is limited to <c>MAX_PATH</c> length.
         // Get a full path of regular format.

         FullPath = Path.GetExtendedLengthPathCore(null, fileName, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

         Initialize();
      }

      #endregion // Constructors

      
      #region Methods

      /// <summary>Gets an <see cref="IntPtr"/> handle to the Shell icon that represents the file.</summary>
      /// <param name="iconAttributes">Icon size <see cref="Shell32.FileAttributes.SmallIcon"/> or <see cref="Shell32.FileAttributes.LargeIcon"/>. Can also be combined with <see cref="Shell32.FileAttributes.AddOverlays"/> and others.</param>
      /// <returns>An <see cref="IntPtr"/> handle to the Shell icon that represents the file.</returns>
      /// <remarks>Caller is responsible for destroying this handle with DestroyIcon() when no longer needed.</remarks>
      [SecurityCritical]
      public IntPtr GetIcon(Shell32.FileAttributes iconAttributes)
      {
         return Shell32.GetFileIcon(FullPath, iconAttributes);
      }


      /// <summary>Gets the Shell command association from the registry.</summary>
      /// <param name="shellVerb">The shell verb.</param>
      /// <returns>
      ///   Returns the associated file- or protocol-related Shell command from the registry or <c>string.Empty</c> if no association can be
      ///   found.
      /// </returns>
      [SecurityCritical]
      public string GetVerbCommand(string shellVerb)
      {
         return GetString(_iQaNone, Shell32.AssociationString.Command, shellVerb);
      }


      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      [SecurityCritical]
      private static string GetString(NativeMethods.IQueryAssociations iQa, Shell32.AssociationString assocString, string shellVerb)
      {
         // GetString() throws Exceptions.
         try
         {
            // Use a large buffer to prevent calling this function twice.
            var size = NativeMethods.DefaultFileBufferSize;
            var buffer = new StringBuilder(size);

            iQa.GetString(Shell32.AssociationAttributes.NoTruncate | Shell32.AssociationAttributes.RemapRunDll, assocString, shellVerb, buffer, out size);

            return buffer.ToString();
         }
         catch
         {
            return string.Empty;
         }
      }


      private NativeMethods.IQueryAssociations _iQaNone;    // Retrieve info from Shell.
      private NativeMethods.IQueryAssociations _iQaByExe;   // Retrieve info from exe file.

      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      [SecurityCritical]
      private void Initialize()
      {
         if (Initialized)
            return;

         var iidIQueryAssociations = new Guid(NativeMethods.QueryAssociationsGuid);

         if (NativeMethods.AssocCreate(NativeMethods.ClsidQueryAssociations, ref iidIQueryAssociations, out _iQaNone) == Win32Errors.S_OK)
         {
            try
            {
               _iQaNone.Init(Shell32.AssociationAttributes.None, FullPath, IntPtr.Zero, IntPtr.Zero);

               if (NativeMethods.AssocCreate(NativeMethods.ClsidQueryAssociations, ref iidIQueryAssociations, out _iQaByExe) == Win32Errors.S_OK)
               {
                  _iQaByExe.Init(Shell32.AssociationAttributes.InitByExeName, FullPath, IntPtr.Zero, IntPtr.Zero);

                  Initialized = true;
               }
            }
            catch
            {
            }
         }
      }


      /// <summary>Refreshes the state of the object.</summary>
      [SecurityCritical]
      public void Refresh()
      {
         Association = Command = ContentType = DdeApplication = DefaultIcon = FriendlyAppName = FriendlyDocName = OpenWithAppName = null;
         Attributes = Shell32.GetAttributesOf.None;
         Initialized = false;
         Initialize();
      }


      /// <summary>Returns the path as a string.</summary>
      /// <returns>The path.</returns>      
      public override string ToString()
      {
         return FullPath;
      }

      #endregion // Methods


      #region Properties

      private string _association;

      /// <summary>Gets the Shell file or protocol association from the registry.</summary>
      public string Association
      {
         get
         {
            if (_association == null)
               _association = GetString(_iQaNone, Shell32.AssociationString.Executable, null);

            return _association;
         }

         private set { _association = value; }
      }

      
      private Shell32.GetAttributesOf _attributes;

      /// <summary>The attributes of the file object.</summary>
      public Shell32.GetAttributesOf Attributes
      {
         get
         {
            if (_attributes == Shell32.GetAttributesOf.None)
            {
               var fileInfo = Shell32.GetFileInfoCore(FullPath, FileAttributes.Normal, Shell32.FileAttributes.Attributes, false, true);
               _attributes = fileInfo.Attributes;
            }

            return _attributes;
         }

         private set { _attributes = value; }
      }


      private string _command;

      /// <summary>Gets the Shell command association from the registry.</summary>
      public string Command
      {
         get
         {
            if (_command == null)
               _command = GetString(_iQaNone, Shell32.AssociationString.Command, null);

            return _command;
         }

         private set { _command = value; }
      }


      private string _contentType;

      /// <summary>Gets the Shell command association from the registry.</summary>
      public string ContentType
      {
         get
         {
            if (_contentType == null)
               _contentType = GetString(_iQaNone, Shell32.AssociationString.ContentType, null);

            return _contentType;
         }

         private set { _contentType = value; }
      }


      private string _ddeApplication;

      /// <summary>Gets the Shell DDE association from the registry.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")]
      public string DdeApplication
      {
         get
         {
            if (_ddeApplication == null)
               _ddeApplication = GetString(_iQaNone, Shell32.AssociationString.DdeApplication, null);

            return _ddeApplication;
         }

         private set { _ddeApplication = value; }
      }


      private string _defaultIcon;

      /// <summary>Gets the Shell default icon association from the registry.</summary>
      public string DefaultIcon
      {
         get
         {
            if (_defaultIcon == null)
               _defaultIcon = GetString(_iQaNone, Shell32.AssociationString.DefaultIcon, null);

            return _defaultIcon;
         }

         private set { _defaultIcon = value; }
      }


      /// <summary>Represents the fully qualified path of the file.</summary>
      public string FullPath { get; private set; }


      private string _friendlyAppName;

      /// <summary>Gets the Shell friendly application name association from the registry.</summary>
      public string FriendlyAppName
      {
         get
         {
            if (_friendlyAppName == null)
               _friendlyAppName = GetString(_iQaByExe, Shell32.AssociationString.FriendlyAppName, null);

            return _friendlyAppName;
         }

         private set { _friendlyAppName = value; }
      }


      private string _friendlyDocName;

      /// <summary>Gets the Shell friendly document name association from the registry.</summary>
      public string FriendlyDocName
      {
         get
         {
            if (_friendlyDocName == null)
               _friendlyDocName = GetString(_iQaNone, Shell32.AssociationString.FriendlyDocName, null);

            return _friendlyDocName;
         }

         private set { _friendlyDocName = value; }
      }


      /// <summary>Reflects the initialization state of the instance.</summary>
      internal bool Initialized { get; set; }


      private string _openWithAppName;

      /// <summary>Gets the Shell "Open With" command association from the registry.</summary>
      public string OpenWithAppName
      {
         get
         {
            if (_openWithAppName == null)
               _openWithAppName = GetString(_iQaNone, Shell32.AssociationString.FriendlyAppName, null);

            return _openWithAppName;
         }

         private set { _openWithAppName = value; }
      }

      #endregion // Properties
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Methods/NativeMethods.BackupStreams.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      /// <summary>The BackupRead function can be used to back up a file or directory, including the security information.
      ///   <para>The function reads data associated with a specified file or directory into a buffer,</para>
      ///   <para>which can then be written to the backup medium using the WriteFile function.</para>
      /// </summary>
      /// <remarks>
      ///   <para>This function is not intended for use in backing up files encrypted under the Encrypted File System.</para>
      ///   <para>Use ReadEncryptedFileRaw for that purpose.</para>
      ///   <para>Minimum supported client: Windows XP [desktop apps only]</para>
      ///   <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
      /// </remarks>
      /// <param name="hFile">The file.</param>
      /// <param name="lpBuffer">The buffer.</param>
      /// <param name="nNumberOfBytesToRead">Number of bytes to reads.</param>
      /// <param name="lpNumberOfBytesRead">[out] Number of bytes reads.</param>
      /// <param name="bAbort">true to abort.</param>
      /// <param name="bProcessSecurity">true to process security.</param>
      /// <param name="lpContext">[out] The context.</param>
      /// <returns>
      ///   <para>If the function succeeds, the return value is nonzero.</para>
      ///   <para>If the function fails, the return value is zero, indicating that an I/O error occurred. To get extended error information,
      ///   call GetLastError.</para>
      /// </returns>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.Bool)]
      internal static extern bool BackupRead(SafeFileHandle hFile, SafeGlobalMemoryBufferHandle lpBuffer, [MarshalAs(UnmanagedType.U4)] uint nNumberOfBytesToRead, [MarshalAs(UnmanagedType.U4)] out uint lpNumberOfBytesRead, [MarshalAs(UnmanagedType.Bool)] bool bAbort, [MarshalAs(UnmanagedType.Bool)] bool bProcessSecurity, ref IntPtr lpContext);


      /// <summary>The BackupSeek function seeks forward in a data stream initially accessed by using the <see cref="BackupRead"/> or
      ///   <see cref="BackupWrite"/> function.
      ///   <para>The function reads data associated with a specified file or directory into a buffer, which can then be written to the backup
      ///   medium using the WriteFile function.</para>
      /// </summary>
      /// <remarks>
      ///   <para>Applications use the BackupSeek function to skip portions of a data stream that cause errors.</para>
      ///   <para>This function does not seek across stream headers. For example, this function cannot be used to skip the stream name.</para>
      ///   <para>If an application attempts to seek past the end of a substream, the function fails, the lpdwLowByteSeeked and
      ///   lpdwHighByteSeeked parameters</para>
      ///   <para>indicate the actual number of bytes the function seeks, and the file position is placed at the start of the next stream
      ///   header.</para>
      ///   <para>&#160;</para>
      ///   <para>Minimum supported client: Windows XP [desktop apps only]</para>
      ///   <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
      /// </remarks>
      /// <param name="hFile">The file.</param>
      /// <param name="dwLowBytesToSeek">The low bytes to seek.</param>
      /// <param name="dwHighBytesToSeek">The high bytes to seek.</param>
      /// <param name="lpdwLowBytesSeeked">[out] The lpdw low bytes seeked.</param>
      /// <param name="lpdwHighBytesSeeked">[out] The lpdw high bytes seeked.</param>
      /// <param name="lpContext">[out] The context.</param>
      /// <returns>
      ///   <para>If the function could seek the requested amount, the function returns a nonzero value.</para>
      ///   <para>If the function could not seek the requested amount, the function returns zero. To get extended error information, call
      ///   GetLastError.</para>
      /// </returns>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.Bool)]
      internal static extern bool BackupSeek(SafeFileHandle hFile, [MarshalAs(UnmanagedType.U4)] uint dwLowBytesToSeek, [MarshalAs(UnmanagedType.U4)] uint dwHighBytesToSeek, [MarshalAs(UnmanagedType.U4)] out uint lpdwLowBytesSeeked, [MarshalAs(UnmanagedType.U4)] out uint lpdwHighBytesSeeked, ref IntPtr lpContext);


      /// <summary>The BackupWrite function can be used to restore a file or directory that was backed up using <see cref="BackupRead"/>.
      ///   <para>Use the ReadFile function to get a stream of data from the backup medium, then use BackupWrite to write the data to the
      ///   specified file or directory.</para>
      ///   <para>&#160;</para>
      /// </summary>
      /// <remarks>
      ///   <para>This function is not intended for use in restoring files encrypted under the Encrypted File System. Use WriteEncryptedFileRaw
      ///   for that purpose.</para>
      ///   <para>Minimum supported client: Windows XP [desktop apps only]</para>
      ///   <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
      /// </remarks>
      /// <param name="hFile">The file.</param>
      /// <param name="lpBuffer">The buffer.</param>
      /// <param name="nNumberOfBytesToWrite">Number of bytes to writes.</param>
      /// <param name="lpNumberOfBytesWritten">[out] Number of bytes writtens.</param>
      /// <param name="bAbort">true to abort.</param>
      /// <param name="bProcessSecurity">true to process security.</param>
      /// <param name="lpContext">[out] The context.</param>
      /// <returns>
      ///   <para>If the function succeeds, the return value is nonzero.</para>
      ///   <para>If the function fails, the return value is zero, indicating that an I/O error occurred. To get extended error information,
      ///   call GetLastError.</para>
      /// </returns>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.Bool)]
      internal static extern bool BackupWrite(SafeFileHandle hFile, SafeGlobalMemoryBufferHandle lpBuffer, [MarshalAs(UnmanagedType.U4)] uint nNumberOfBytesToWrite, [MarshalAs(UnmanagedType.U4)] out uint lpNumberOfBytesWritten, [MarshalAs(UnmanagedType.Bool)] bool bAbort, [MarshalAs(UnmanagedType.Bool)] bool bProcessSecurity, ref IntPtr lpContext);
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Security;
using Alphaleonis.Win32.Filesystem;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>[AlphaFS] Enumerates sessions established on the local host.</summary>
      /// <returns>An <see cref="IEnumerable{SessionInfo}"/> collection from the local host.</returns>
      [SecurityCritical]
      public static IEnumerable<SessionInfo> EnumerateSessions()
      {
         return EnumerateSessionsCore(Environment.MachineName, null, null);
      }


      /// <summary>[AlphaFS] Enumerates sessions established on the specified <paramref name="hostName"/>.</summary>
      /// <returns>An <see cref="IEnumerable{SessionInfo}"/> collection from the specified <paramref name="hostName"/>.</returns>
      /// <param name="hostName">The DNS or NetBIOS name of the specified host. If this parameter is <c>null</c>, the local Computer is used.</param>
      [SecurityCritical]
      public static IEnumerable<SessionInfo> EnumerateSessions(string hostName)
      {
         return EnumerateSessionsCore(hostName, null, null);
      }


      /// <summary>[AlphaFS] Enumerates sessions established on the specified <paramref name="hostName"/>.</summary>
      /// <returns>An <see cref="IEnumerable{SessionInfo}"/> collection from the specified <paramref name="hostName"/>.</returns>
      /// <param name="hostName">The DNS or NetBIOS name of the specified host. If this parameter is <c>null</c>, the local Computer is used.</param>
      /// <param name="clientName">The name of the Computer session for which information is to be returned. If this parameter is <c>null</c>, information for all Computer sessions on the server is returned.</param>
      [SecurityCritical]
      public static IEnumerable<SessionInfo> EnumerateSessions(string hostName, string clientName)
      {
         return EnumerateSessionsCore(hostName, clientName, null);
      }


      /// <summary>[AlphaFS] Enumerates sessions established on the specified <paramref name="hostName"/>.</summary>
      /// <returns>An <see cref="IEnumerable{SessionInfo}"/> collection from the specified <paramref name="hostName"/>.</returns>
      /// <param name="hostName">The DNS or NetBIOS name of the specified host. If this parameter is <c>null</c>, the local Computer is used.</param>
      /// <param name="clientName">The name of the Computer session for which information is to be returned. If this parameter is <c>null</c>, information for all Computer sessions on the server is returned.</param>
      /// <param name="userName">The name of the user for which information is to be returned. If this parameter is <c>null</c>, information for all users is returned.</param>
      [SecurityCritical]
      public static IEnumerable<SessionInfo> EnumerateSessions(string hostName, string clientName, string userName)
      {
         return EnumerateSessionsCore(hostName, clientName, userName);
      }


      
      
      /// <summary>[AlphaFS] Enumerates sessions established on the specified <paramref name="hostName"/>.</summary>
      /// <returns>An <see cref="IEnumerable{SessionInfo}"/> collection from the specified <paramref name="hostName"/>.</returns>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="hostName">The DNS or NetBIOS name of the specified host. If this parameter is <c>null</c>, the local Computer is used.</param>
      /// <param name="clientName">The name of the Computer session for which information is to be returned. If this parameter is <c>null</c>, information for all Computer sessions on the server is returned.</param>
      /// <param name="userName">The name of the user for which information is to be returned. If this parameter is <c>null</c>, information for all users is returned.</param>
      [SecurityCritical]
      internal static IEnumerable<SessionInfo> EnumerateSessionsCore(string hostName, string clientName, string userName)
      {
         var fd = new FunctionData();
         var hasItems = false;


         // hostName is allowed to be null.
         // clientName is allowed to be null.
         // userName is allowed to be null.

         var stripUnc = !Utils.IsNullOrWhiteSpace(hostName) ? Path.GetRegularPathCore(hostName, GetFullPathOptions.CheckInvalidPathChars, false).Replace(Path.UncPrefix, string.Empty) : null;


         // Start with SESSION_INFO_502 structure.

         foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_502 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(stripUnc, SessionInfoLevel.Info502, structure),

            (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>

               NativeMethods.NetSessionEnum(stripUnc, clientName, userName, SessionInfoLevel.Info502, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true))
         {
            yield return sessionInfo;
            hasItems = true;
         }

         if (hasItems)
            yield break;


         // Fallback on SESSION_INFO_2 structure.

         foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_2 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(stripUnc, SessionInfoLevel.Info2, structure),

            (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>

               NativeMethods.NetSessionEnum(stripUnc, clientName, userName, SessionInfoLevel.Info2, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true))
         {
            yield return sessionInfo;
            hasItems = true;
         }

         if (hasItems)
            yield break;


         // Fallback on SHARE_INFO_1 structure.

         foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_1 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(stripUnc, SessionInfoLevel.Info1, structure),

            (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>

               NativeMethods.NetSessionEnum(stripUnc, clientName, userName, SessionInfoLevel.Info1, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true))
         {
            yield return sessionInfo;
            hasItems = true;
         }

         if (hasItems)
            yield break;


         // Fallback on SESSION_INFO_10 structure.

         foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_10 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(stripUnc, SessionInfoLevel.Info10, structure),

            (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>

               NativeMethods.NetSessionEnum(stripUnc, clientName, userName, SessionInfoLevel.Info10, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true))
         {
            yield return sessionInfo;
            hasItems = true;
         }

         if (hasItems)
            yield break;


         // Fallback on SESSION_INFO_0 structure.

         foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_0 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(stripUnc, SessionInfoLevel.Info0, structure),

            (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>

               NativeMethods.NetSessionEnum(stripUnc, clientName, userName, SessionInfoLevel.Info0, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true))
         {
            yield return sessionInfo;
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory.GetProperties.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
      ///   <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
      ///   <para><b>Total:</b> is the total number of enumerated objects.</para>
      ///   <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
      ///   <para><b>Size:</b> is the total size of enumerated objects.</para>
      ///   <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
      /// </summary>
      /// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
      /// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="path">The target directory.</param>
      [SecurityCritical]
      public static Dictionary<string, long> GetProperties(string path)
      {
         return GetPropertiesCore(null, path, null, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
      ///   <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
      ///   <para><b>Total:</b> is the total number of enumerated objects.</para>
      ///   <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
      ///   <para><b>Size:</b> is the total size of enumerated objects.</para>
      ///   <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
      /// </summary>
      /// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
      /// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="path">The target directory.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static Dictionary<string, long> GetProperties(string path, PathFormat pathFormat)
      {
         return GetPropertiesCore(null, path, null, pathFormat);
      }


      /// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
      ///   <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
      ///   <para><b>Total:</b> is the total number of enumerated objects.</para>
      ///   <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
      ///   <para><b>Size:</b> is the total size of enumerated objects.</para>
      ///   <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
      /// </summary>
      /// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
      /// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="path">The target directory.</param>
      /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
      [SecurityCritical]
      public static Dictionary<string, long> GetProperties(string path, DirectoryEnumerationOptions options)
      {
         return GetPropertiesCore(null, path, options, PathFormat.RelativePath);
      }


      /// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
      ///   <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
      ///   <para><b>Total:</b> is the total number of enumerated objects.</para>
      ///   <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
      ///   <para><b>Size:</b> is the total size of enumerated objects.</para>
      ///   <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
      /// </summary>
      /// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
      /// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="path">The target directory.</param>
      /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static Dictionary<string, long> GetProperties(string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
      {
         return GetPropertiesCore(null, path, options, pathFormat);
      }
   }
}


<|start_filename|>src/AlphaFS/Security/Native Other/SE_OBJECT_TYPE.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

namespace Alphaleonis.Win32.Security
{
   /// <summary>The SE_OBJECT_TYPE enumeration contains values that correspond to the types of Windows objects that support security.
   /// The functions, such as GetSecurityInfo and SetSecurityInfo, that set and retrieve the security information of an object, use these values to indicate the type of object.
   /// </summary>
   /// <remarks>
   /// <para>Minimum supported client: Windows XP [desktop apps only]</para>
   /// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
   /// </remarks>
   internal enum SE_OBJECT_TYPE
   {
      /// <summary>Unknown object type.</summary>
      SE_UNKNOWN_OBJECT_TYPE = 0,

      /// <summary>Indicates a file or directory. The name string that identifies a file or directory object can be in one of the following formats:
      ///   A relative path, such as FileName.dat or ..\FileName
      ///   An absolute path, such as FileName.dat, C:\DirectoryName\FileName.dat, or G:\RemoteDirectoryName\FileName.dat.
      ///   A UNC name, such as \\ComputerName\ShareName\FileName.dat.
      /// </summary>
      SE_FILE_OBJECT,

      /// <summary>Indicates a Windows service. A service object can be a local service, such as ServiceName, or a remote service, such as \\ComputerName\ServiceName.</summary>
      SE_SERVICE,

      /// <summary>Indicates a printer. A printer object can be a local printer, such as PrinterName, or a remote printer, such as \\ComputerName\PrinterName.</summary>
      SE_PRINTER,

      /// <summary>Indicates a registry key. A registry key object can be in the local registry, such as CLASSES_ROOT\SomePath or in a remote registry, such as \\ComputerName\CLASSES_ROOT\SomePath.
      /// The names of registry keys must use the following literal strings to identify the predefined registry keys: "CLASSES_ROOT", "CURRENT_USER", "MACHINE", and "USERS".
      /// </summary>
      SE_REGISTRY_KEY,

      /// <summary>Indicates a network share. A share object can be local, such as ShareName, or remote, such as \\ComputerName\ShareName.</summary>
      SE_LMSHARE,

      /// <summary>Indicates a local kernel object. The GetSecurityInfo and SetSecurityInfo functions support all types of kernel objects.
      /// The GetNamedSecurityInfo and SetNamedSecurityInfo functions work only with the following kernel objects: semaphore, event, mutex, waitable timer, and file mapping.</summary>
      SE_KERNEL_OBJECT,

      /// <summary>Indicates a window station or desktop object on the local computer. You cannot use GetNamedSecurityInfo and SetNamedSecurityInfo with these objects because the names of window stations or desktops are not unique.</summary>
      SE_WINDOW_OBJECT,

      /// <summary>Indicates a directory service object or a property set or property of a directory service object.
      /// The name string for a directory service object must be in X.500 form, for example: CN=SomeObject,OU=ou2,OU=ou1,DC=DomainName,DC=CompanyName,DC=com,O=internet</summary>
      SE_DS_OBJECT,

      /// <summary>Indicates a directory service object and all of its property sets and properties.</summary>
      SE_DS_OBJECT_ALL,

      /// <summary>Indicates a provider-defined object.</summary>
      SE_PROVIDER_DEFINED_OBJECT,

      /// <summary>Indicates a WMI object.</summary>
      SE_WMIGUID_OBJECT,

      /// <summary>Indicates an object for a registry entry under WOW64.</summary>
      SE_REGISTRY_WOW64_32KEY
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.EncryptDecryptFileCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Decrypts/encrypts a file or directory so that only the account used to encrypt the file can decrypt it.</summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryReadOnlyException"/>
      /// <exception cref="FileReadOnlyException"/>
      /// <exception cref="NotSupportedException"/>
      /// <param name="isFolder">Specifies that <paramref name="path"/> is a file or directory.</param>
      /// <param name="path">A path that describes a file to encrypt.</param>
      /// <param name="encrypt"><c>true</c> encrypt, <c>false</c> decrypt.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void EncryptDecryptFileCore(bool isFolder, string path, bool encrypt, PathFormat pathFormat)
      {
         if (pathFormat != PathFormat.LongFullPath)
         {
            path = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

            pathFormat = PathFormat.LongFullPath;
         }


         // MSDN: If lpFileName specifies a read-only file, the function fails and GetLastError returns ERROR_FILE_READ_ONLY.

         var attrs = GetAttributesExCore<NativeMethods.WIN32_FILE_ATTRIBUTE_DATA>(null, path, pathFormat, true);

         var isReadOnly = IsReadOnly(attrs.dwFileAttributes);
         var isHidden = IsHidden(attrs.dwFileAttributes);

         if (isReadOnly || isHidden)
         {
            if (isReadOnly)
               attrs.dwFileAttributes &= ~FileAttributes.ReadOnly;

            if (isHidden)
               attrs.dwFileAttributes &= ~FileAttributes.Hidden;

            SetAttributesCore(null, isFolder, path, attrs.dwFileAttributes, pathFormat);
         }


         // EncryptFile() / DecryptFile()
         // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

         var success = encrypt ? NativeMethods.EncryptFile(path) : NativeMethods.DecryptFile(path, 0);

         var lastError = Marshal.GetLastWin32Error();


         if (isReadOnly || isHidden)
         {
            if (isReadOnly)
               attrs.dwFileAttributes |= FileAttributes.ReadOnly;

            if (isHidden)
               attrs.dwFileAttributes |= FileAttributes.Hidden;

            SetAttributesCore(null, isFolder, path, attrs.dwFileAttributes, pathFormat);
         }


         if (!success)
         {
            switch ((uint) lastError)
            {
               case Win32Errors.ERROR_ACCESS_DENIED:

                  if (!string.Equals("NTFS", new DriveInfo(path).DriveFormat, StringComparison.OrdinalIgnoreCase))

                     throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "The drive does not support NTFS encryption: [{0}]", Path.GetPathRoot(path, false)));

                  break;


               case Win32Errors.ERROR_FILE_READ_ONLY:

                  if (isFolder)
                     throw new DirectoryReadOnlyException(path);

                  else
                     throw new FileReadOnlyException(path);


               default:
                  NativeError.ThrowException(lastError, isFolder, path);
                  break;
            }
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File CopyMove/File.CopyMoveLogic.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Checks if the <see cref="MoveOptions.CopyAllowed"/> flag is specified.</summary>
      internal static bool HasCopyAllowed(MoveOptions? moveOptions)
      {
         return Utils.IsNotNull(moveOptions) && (moveOptions & MoveOptions.CopyAllowed) != 0;
      }


      /// <summary>Checks if the <see cref="CopyOptions.CopySymbolicLink"/> flag is specified.</summary>
      internal static bool HasCopySymbolicLink(CopyOptions? copyOptions)
      {
         return Utils.IsNotNull(copyOptions) && (copyOptions & CopyOptions.CopySymbolicLink) != 0;
      }


      /// <summary>Checks if the <see cref="MoveOptions.DelayUntilReboot"/> flag is specified.</summary>
      internal static bool HasDelayUntilReboot(MoveOptions? moveOptions)
      {
         return Utils.IsNotNull(moveOptions) && (moveOptions & MoveOptions.DelayUntilReboot) != 0;
      }


      /// <summary>Checks if the <see cref="CopyOptions.CopyTimestamp"/> flag is specified.</summary>
      internal static bool HasCopyTimestamps(CopyOptions? copyOptions)
      {
         return Utils.IsNotNull(copyOptions) && (copyOptions & CopyOptions.CopyTimestamp) != 0;
      }


      /// <summary>Checks if the <see cref="MoveOptions.ReplaceExisting"/> flag is specified.</summary>
      internal static bool HasReplaceExisting(MoveOptions? moveOptions)
      {
         return Utils.IsNotNull(moveOptions) && (moveOptions & MoveOptions.ReplaceExisting) != 0;
      }


      /// <summary>Determine the Copy or Move action.</summary>
      /// <exception cref="NotSupportedException"/>
      internal static bool IsCopyAction(CopyMoveArguments cma)
      {
         // Determine Copy or Move action.

         var isMove = Utils.IsNotNull(cma.MoveOptions) && Equals(null, cma.CopyOptions);

         var isCopy = !isMove && Utils.IsNotNull(cma.CopyOptions);

         if (isCopy.Equals(isMove))
            throw new NotSupportedException(Resources.Cannot_Determine_Copy_Or_Move);

         return isCopy;
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.GetPropertiesCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Gets the properties of the particular directory without following any symbolic links or mount points.
      ///   <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
      ///   <para><b>Total:</b> is the total number of enumerated objects.</para>
      ///   <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
      ///   <para><b>Size:</b> is the total size of enumerated objects.</para>
      ///   <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
      /// </summary>
      /// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
      /// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The target directory.</param>
      /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static Dictionary<string, long> GetPropertiesCore(KernelTransaction transaction, string path, DirectoryEnumerationOptions? options, PathFormat pathFormat)
      {
         long total = 0;
         long size = 0;

         const string propFile = "File";
         const string propTotal = "Total";
         const string propSize = "Size";
         
         var typeOfAttrs = typeof(FileAttributes);
         var attributes = Enum.GetValues(typeOfAttrs);
         var props = Enum.GetNames(typeOfAttrs).OrderBy(attrs => attrs).ToDictionary<string, string, long>(name => name, name => 0);
         var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);


         foreach (var fsei in EnumerateFileSystemEntryInfosCore<FileSystemEntryInfo>(null, transaction, pathLp, Path.WildcardStarMatchAll, null, options,  null, PathFormat.LongFullPath))
         {
            total++;

            if (!fsei.IsDirectory)
               size += fsei.FileSize;

            var fsei1 = fsei;

            foreach (var attributeMarker in attributes.Cast<FileAttributes>().Where(attributeMarker => (fsei1.Attributes & attributeMarker) != 0))

               props[((attributeMarker & FileAttributes.Directory) != 0 ? FileAttributes.Directory : attributeMarker).ToString()]++;
         }

         // Adjust regular files count.
         props.Add(propFile, total - props[FileAttributes.Directory.ToString()] - props[FileAttributes.ReparsePoint.ToString()]);
         props.Add(propTotal, total);
         props.Add(propSize, size);

         return props;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateAlternateDataStreams.cs<|end_filename|>
﻿/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Globalization;
using System.Linq;

namespace AlphaFS.UnitTest
{
   public partial class EnumerationTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>

      [TestMethod]
      public void AlphaFS_Directory_EnumerateAlternateDataStreams_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_EnumerateAlternateDataStreams(false);
         AlphaFS_Directory_EnumerateAlternateDataStreams(true);
      }

      private void AlphaFS_Directory_EnumerateAlternateDataStreams(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = tempRoot.RandomDirectoryFullPath;

            Console.WriteLine("Input Directory Path: [{0}]", folder);


            var myStream = "ӍƔŞtrëƛɱ-" + tempRoot.RandomString;
            var myStream2 = "myStreamTWO-" + tempRoot.RandomString;
            var allStreams = new[] {myStream, myStream2};
            var streamStringContent = "(1) Computer: [" + Environment.MachineName + "]" + "\tHello there, " + Environment.UserName;

            Console.WriteLine("\n\tA directory is created and {0} streams are added.", allStreams.Length.ToString(CultureInfo.CurrentCulture));
            
            var di = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder);
            di.Create();


            const int defaultStreamsDirectory = 0; // The default number of data streams for a folder.
            var currentNumberofStreams = di.EnumerateAlternateDataStreams().Count();

            Assert.AreEqual(defaultStreamsDirectory, currentNumberofStreams, "Total amount of default streams do not match.");
            Assert.AreEqual(currentNumberofStreams, Alphaleonis.Win32.Filesystem.Directory.EnumerateAlternateDataStreams(folder).Count(), "Total amount of Directory.EnumerateAlternateDataStreams() streams do not match.");


            var stream1Name = folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream;
            var stream2Name = folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream2;


            // Create alternate data streams.
            // Because of the colon, you must supply a full path and use PathFormat.FullPath or PathFormat.LongFullPath,
            // to prevent a: "NotSupportedException: path is in an invalid format." exception.


            Alphaleonis.Win32.Filesystem.File.WriteAllLines(stream1Name, UnitTestConstants.StreamArrayContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);
            Alphaleonis.Win32.Filesystem.File.WriteAllText(stream2Name, streamStringContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);




            var newNumberofStreams = Alphaleonis.Win32.Filesystem.Directory.EnumerateAlternateDataStreams(folder).Count();
            Console.WriteLine("\n\tNew stream count: [{0}]", newNumberofStreams);


            // Enumerate all streams from the folder.

            foreach (var stream in di.EnumerateAlternateDataStreams())
            {
               UnitTestConstants.Dump(stream);

               Assert.IsNotNull(stream);
            }


            // Show the contents of our streams.

            Console.WriteLine();
            foreach (var streamName in allStreams)
            {
               Console.WriteLine("\n\tStream name: [{0}]", streamName);

               
               // Because of the colon, you must supply a full path and use PathFormat.FullPath or PathFormat.LongFullPath,
               // to prevent a: "NotSupportedException: path is in an invalid format." exception.

               foreach (var line in Alphaleonis.Win32.Filesystem.File.ReadAllLines(folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + streamName, Alphaleonis.Win32.Filesystem.PathFormat.FullPath))
                  Console.WriteLine("\t\t{0}", line);
            }


            // Check FileInfo instance data of the streams.

            var fileInfo1 = new Alphaleonis.Win32.Filesystem.FileInfo(stream1Name, Alphaleonis.Win32.Filesystem.PathFormat.LongFullPath);
            var fileInfo2 = new Alphaleonis.Win32.Filesystem.FileInfo(stream2Name, Alphaleonis.Win32.Filesystem.PathFormat.LongFullPath);

            Assert.AreEqual(myStream, fileInfo1.Name);
            Assert.AreEqual(myStream2, fileInfo2.Name);

            Assert.IsNull(fileInfo1.EntryInfo);
            Assert.IsNull(fileInfo2.EntryInfo);
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File CopyMove/File.Copy.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.IO;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      #region Obsolete

      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed.</summary>
      /// <remarks>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy. </param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="overwrite"><c>true</c> if the destination file should ignoring the read-only and hidden attributes and overwrite; otherwise, <c>false</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")]
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed.</summary>
      /// <remarks>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy. </param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="overwrite"><c>true</c> if the destination file should ignoring the read-only and hidden attributes and overwrite; otherwise, <c>false</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [Obsolete("To disable/enable overwrite, use other overload and use CopyOptions.None enum flag or remove CopyOptions.FailIfExists enum flag.")]
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }
      

      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. <see cref="CopyOptions"/> can be specified.</summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      /// <param name="preserveDates"><c>true</c> if original Timestamps must be preserved; otherwise, <c>false</c>.</param>
      [SecurityCritical]
      [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. <see cref="CopyOptions"/> can be specified.</summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      /// <param name="preserveDates"><c>true</c> if original Timestamps must be preserved; otherwise, <c>false</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed.  <see cref="CopyOptions"/> can be specified,
      /// and the possibility of notifying the application of its progress through a callback function.
      /// </summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      /// <param name="preserveDates"><c>true</c> if original Timestamps must be preserved; otherwise, <c>false</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed.  <see cref="CopyOptions"/> can be specified,
      /// and the possibility of notifying the application of its progress through a callback function.
      /// </summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      /// <param name="preserveDates"><c>true</c> if original Timestamps must be preserved; otherwise, <c>false</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      [Obsolete("Use other overload and add CopyOptions.CopyTimestamp enum flag.")]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = preserveDates ? copyOptions | CopyOptions.CopyTimestamp : copyOptions & ~CopyOptions.CopyTimestamp,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }

      #endregion // Obsolete

      
      #region .NET

      /// <summary>Copies an existing file to a new file. Overwriting a file of the same name is not allowed.</summary>
      /// <remarks>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory or an existing file.</param>
      [SecurityCritical]
      public static void Copy(string sourcePath, string destinationPath)
      {
         CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = CopyOptions.FailIfExists

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>Copies an existing file to a new file. Overwriting a file of the same name is allowed.</summary>
      /// <remarks>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy. </param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="overwrite"><c>true</c> if the destination file should ignoring the read-only and hidden attributes and overwrite; otherwise, <c>false</c>.</param>      
      [SecurityCritical]
      public static void Copy(string sourcePath, string destinationPath, bool overwrite)
      {
         CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists

         }, false, false, sourcePath, destinationPath, null);
      }

      #endregion // .NET


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed.</summary>
      /// <remarks>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy. </param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = CopyOptions.FailIfExists,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }

      /// <summary>
      /// [AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is
      /// allowed.
      /// </summary>
      /// <remarks>
      /// <para>The attributes of the original file are retained in the copied file.</para>
      /// <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this
      /// method.</para>
      /// <para>If two files have equivalent short file names then this method may fail and raise an
      /// exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException">.</exception>
      /// <exception cref="ArgumentNullException">.</exception>
      /// <exception cref="DirectoryNotFoundException">.</exception>
      /// <exception cref="FileNotFoundException">.</exception>
      /// <exception cref="IOException">.</exception>
      /// <exception cref="NotSupportedException">.</exception>
      /// <exception cref="UnauthorizedAccessException">.</exception>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="overwrite"><c>true</c> if the destination file should ignoring the read-only and
      /// hidden attributes and overwrite; otherwise, <c>false</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      /// <returns>
      /// Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.
      /// </returns>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, PathFormat pathFormat)
      {
         return CopyMoveCore(true, new CopyMoveArguments
         {
            CopyOptions = overwrite ? CopyOptions.None : CopyOptions.FailIfExists,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed.</summary>
      /// <remarks>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory or an existing file.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, int retry, int retryTimeout)
      {
         return CopyMoveCore(true, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            CopyOptions = CopyOptions.FailIfExists

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed.</summary>
      /// <remarks>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy. </param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, int retry, int retryTimeout, PathFormat pathFormat)
      {
         return CopyMoveCore(true, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            CopyOptions = CopyOptions.FailIfExists,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function.</summary>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <remarks>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy. </param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = CopyOptions.FailIfExists,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function.</summary>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <remarks>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy. </param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = CopyOptions.FailIfExists,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function.</summary>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <remarks>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy. </param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            CopyOptions = CopyOptions.FailIfExists,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is not allowed. Possibility of notifying the application of its progress through a callback function.</summary>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <remarks>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy. </param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            CopyOptions = CopyOptions.FailIfExists,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }
      



      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. <see cref="CopyOptions"/> can be specified.</summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = copyOptions

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. <see cref="CopyOptions"/> can be specified.</summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = copyOptions,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }
      

      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. <see cref="CopyOptions"/> can be specified.</summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout)
      {
         return CopyMoveCore(true, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            CopyOptions = copyOptions

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed. <see cref="CopyOptions"/> can be specified.</summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout, PathFormat pathFormat)
      {
         return CopyMoveCore(true, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            CopyOptions = copyOptions,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }
      

      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed.  <see cref="CopyOptions"/> can be specified,
      /// and the possibility of notifying the application of its progress through a callback function.
      /// </summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = copyOptions,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed.  <see cref="CopyOptions"/> can be specified,
      /// and the possibility of notifying the application of its progress through a callback function.
      /// </summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         return CopyMoveCore(false, new CopyMoveArguments
         {
            CopyOptions = copyOptions,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }
      

      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed.  <see cref="CopyOptions"/> can be specified,
      /// and the possibility of notifying the application of its progress through a callback function.
      /// </summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData)
      {
         return CopyMoveCore(true, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            CopyOptions = copyOptions,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData

         }, false, false, sourcePath, destinationPath, null);
      }


      /// <summary>[AlphaFS] Copies an existing file to a new file. Overwriting a file of the same name is allowed.  <see cref="CopyOptions"/> can be specified,
      /// and the possibility of notifying the application of its progress through a callback function.
      /// </summary>
      /// <remarks>
      ///   <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para>
      ///   <para>The attributes of the original file are retained in the copied file.</para>
      ///   <para>Whenever possible, avoid using short file names (such as <c>XXXXXX~1.XXX</c>) with this method.</para>
      ///   <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para>
      /// </remarks>
      /// <returns>Returns a <see cref="CopyMoveResult"/> class with details of the Copy action.</returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="FileNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="sourcePath">The file to copy.</param>
      /// <param name="destinationPath">The name of the destination file. This cannot be a directory.</param>
      /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied. This parameter can be <c>null</c>.</param>
      /// <param name="retry">The number of retries on failed copies.</param>
      /// <param name="retryTimeout">The wait time in seconds between retries.</param>
      /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <c>null</c>.</param>
      /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <c>null</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, int retry, int retryTimeout, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         return CopyMoveCore(true, new CopyMoveArguments
         {
            Retry = retry,
            RetryTimeout = retryTimeout,
            CopyOptions = copyOptions,
            ProgressHandler = progressHandler,
            UserProgressData = userProgressData,
            PathFormat = pathFormat

         }, false, false, sourcePath, destinationPath, null);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CreateDirectoryCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Creates a new directory with the attributes of a specified template directory (if one is specified). 
      ///   If the underlying file system supports security on files and directories, the function applies the specified security descriptor to the new directory.
      ///   The new directory retains the other attributes of the specified template directory.
      /// </summary>
      /// <returns>
      ///   <para>Returns an object that represents the directory at the specified path.</para>
      ///   <para>This object is returned regardless of whether a directory at the specified path already exists.</para>
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="returnNull">When <c>true</c> returns <c>null</c> instead of a <see cref="DirectoryInfo"/> instance.</param>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="templatePath">The path of the directory to use as a template when creating the new directory. May be <c>null</c> to indicate that no template should be used.</param>
      /// <param name="directorySecurity">The <see cref="DirectorySecurity"/> access control to apply to the directory, may be null.</param>
      /// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static DirectoryInfo CreateDirectoryCore(bool returnNull, KernelTransaction transaction, string path, string templatePath, ObjectSecurity directorySecurity, bool compress, PathFormat pathFormat)
      {
         var longPath = path;

         if (pathFormat != PathFormat.LongFullPath)
         {
            if (null == path)
               throw new ArgumentNullException("path");


            Path.CheckSupportedPathFormat(path, true, true);
            Path.CheckSupportedPathFormat(templatePath, true, true);

            longPath = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);

            pathFormat = PathFormat.LongFullPath;
         }


         if (!char.IsWhiteSpace(longPath[longPath.Length - 1]))
         {
            // Return DirectoryInfo instance if the directory specified by path already exists.

            if (File.ExistsCore(transaction, true, longPath, PathFormat.LongFullPath))

               // We are not always interested in a new DirectoryInfo instance.
               return returnNull ? null : new DirectoryInfo(transaction, longPath, PathFormat.LongFullPath);
         }


         // MSDN: .NET 3.5+: IOException: The directory specified by path is a file or the network name was not found.
         if (File.ExistsCore(transaction, false, longPath, PathFormat.LongFullPath))
            NativeError.ThrowException(Win32Errors.ERROR_ALREADY_EXISTS, longPath);


         var templatePathLp = Utils.IsNullOrWhiteSpace(templatePath)
            ? null
            : Path.GetExtendedLengthPathCore(transaction, templatePath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);
         

         var list = ConstructFullPath(transaction, longPath);
         
         // Directory security.
         using (var securityAttributes = new Security.NativeMethods.SecurityAttributes(directorySecurity))
         {
            // Create the directory paths.
            while (list.Count > 0)
            {
               var folderLp = list.Pop();

               // CreateDirectory() / CreateDirectoryEx()
               // 2013-01-13: MSDN confirms LongPath usage.

               if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista

                  ? (templatePathLp == null

                     ? NativeMethods.CreateDirectory(folderLp, securityAttributes)

                     : NativeMethods.CreateDirectoryEx(templatePathLp, folderLp, securityAttributes))

                  : NativeMethods.CreateDirectoryTransacted(templatePathLp, folderLp, securityAttributes, transaction.SafeHandle)))
               {
                  var lastError = Marshal.GetLastWin32Error();

                  switch ((uint) lastError)
                  {
                     // MSDN: .NET 3.5+: If the directory already exists, this method does nothing.
                     // MSDN: .NET 3.5+: IOException: The directory specified by path is a file.
                     case Win32Errors.ERROR_ALREADY_EXISTS:
                        if (File.ExistsCore(transaction, false, longPath, PathFormat.LongFullPath))
                           NativeError.ThrowException(lastError, longPath);

                        if (File.ExistsCore(transaction, false, folderLp, PathFormat.LongFullPath))
                           NativeError.ThrowException(Win32Errors.ERROR_PATH_NOT_FOUND, null, folderLp);
                        break;


                     case Win32Errors.ERROR_BAD_NET_NAME:
                        NativeError.ThrowException(Win32Errors.ERROR_BAD_NET_NAME, longPath);
                        break;


                     case Win32Errors.ERROR_DIRECTORY:
                        // MSDN: .NET 3.5+: NotSupportedException: path contains a colon character (:) that is not part of a drive label ("C:\").
                        throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Resources.Unsupported_Path_Format, longPath));


                     case Win32Errors.ERROR_ACCESS_DENIED:
                        // Report the parent folder, the inaccessible folder.
                        var parent = GetParent(folderLp);

                        NativeError.ThrowException(lastError, null != parent ? parent.FullName : folderLp);
                        break;


                     default:
                        NativeError.ThrowException(lastError, true, folderLp);
                        break;
                  }
               }

               else if (compress)
                  Device.ToggleCompressionCore(transaction, true, folderLp, true, PathFormat.LongFullPath);
            }


            // We are not always interested in a new DirectoryInfo instance.

            return returnNull ? null : new DirectoryInfo(transaction, longPath, PathFormat.LongFullPath);
         }
      }


      private static Stack<string> ConstructFullPath(KernelTransaction transaction, string path)
      {
         var longPathPrefix = Path.IsUncPathCore(path, false, false) ? Path.LongPathUncPrefix : Path.LongPathPrefix;
         path = Path.GetRegularPathCore(path, GetFullPathOptions.None, false);

         var length = path.Length;
         if (length >= 2 && Path.IsDVsc(path[length - 1], false))
            --length;

         var rootLength = Path.GetRootLength(path, false);
         if (length == 2 && Path.IsDVsc(path[1], false))
            throw new ArgumentException(Resources.Cannot_Create_Directory, "path");


         // Check if directories are missing.
         var list = new Stack<string>(100);

         if (length > rootLength)
         {
            for (var index = length - 1; index >= rootLength; --index)
            {
               var path1 = path.Substring(0, index + 1);
               var path2 = longPathPrefix + path1.TrimStart('\\');

               if (!File.ExistsCore(transaction, true, path2, PathFormat.LongFullPath))
                  list.Push(path2);

               while (index > rootLength && !Path.IsDVsc(path[index], false))
                  --index;
            }
         }

         return list;
      }
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/File.Open/File.OpenRead.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Globalization;
using System.Text;

namespace AlphaFS.UnitTest
{
   partial class FileTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void File_OpenRead_LocalAndNetwork_Success()
      {
         File_OpenRead(false);
         File_OpenRead(true);
      }


      private void File_OpenRead(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var file = tempRoot.RandomTxtFileFullPath;

            Console.WriteLine("Input File Path: [{0}]\n", file);


            System.IO.File.WriteAllText(file, DateTime.Now.ToString(CultureInfo.CurrentCulture));


            var sysIOStreamText = string.Empty;
            
            using (var stream = System.IO.File.OpenRead(file))
            {
               var b = new byte[15];
               var temp = new UTF8Encoding(true);

               while (stream.Read(b, 0, b.Length) > 0)
                  sysIOStreamText += temp.GetString(b);
            }


            var alphaFSStreamText = string.Empty;

            using (var stream = Alphaleonis.Win32.Filesystem.File.OpenRead(file))
            {
               var b = new byte[15];
               var temp = new UTF8Encoding(true);

               while (stream.Read(b, 0, b.Length) > 0)
                  alphaFSStreamText += temp.GetString(b);
            }


            Console.WriteLine("\tSystem IO: " + sysIOStreamText);
            Console.WriteLine("\tAlphaFS  : " + alphaFSStreamText);


            Assert.AreEqual(sysIOStreamText, alphaFSStreamText, "The content of the two files is not equal, but is expected to.");
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/File Class/File Core Methods/File.FindAllStreamsCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      [SecurityCritical]
      internal static long FindAllStreamsCore(KernelTransaction transaction, string pathLp)
      {
         var streamSizes = new Collection<long>();

         using (var buffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(NativeMethods.WIN32_FIND_STREAM_DATA))))
         using (var safeFindFileHandle = FindFirstStreamNative(transaction, pathLp, buffer))
         {
            if (null != safeFindFileHandle)
               while (true)
               {
                  streamSizes.Add(buffer.PtrToStructure<NativeMethods.WIN32_FIND_STREAM_DATA>(0).StreamSize);

                  var success = NativeMethods.FindNextStreamW(safeFindFileHandle, buffer);

                  var lastError = Marshal.GetLastWin32Error();

                  if (!success)
                  {
                     if (lastError == Win32Errors.ERROR_HANDLE_EOF)
                        break;

                     NativeError.ThrowException(lastError, pathLp);
                  }
               }
         }
         
         return streamSizes.Sum();
      }
   }
}


<|start_filename|>src/AlphaFS/Network/NetworkConnectionInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net.NetworkInformation;

namespace Alphaleonis.Win32.Network
{
   /// <summary>Represents a connection to a network.</summary>
   public class NetworkConnectionInfo
   {
      #region Private Fields

      private readonly NativeMethods.INetworkConnection _networkConnection;

      #endregion // Private Fields


      #region Constructors

      internal NetworkConnectionInfo(NativeMethods.INetworkConnection networkConnection)
      {
         _networkConnection = networkConnection;
      }

      #endregion // Constructors


      #region Properties

      /// <summary>Gets the unique identifier for this connection. This value of this property is not cached.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")]
      public Guid ConnectionId
      {
         get { return _networkConnection.GetConnectionId(); }
      }


      /// <summary>Gets a value that indicates the connectivity of this connection. This value of this property is not cached.</summary>
      public ConnectivityStates Connectivity
      {
         get { return _networkConnection.GetConnectivity(); }
      }


      /// <summary>Gets a value that indicates whether the network associated with this connection is an Active Directory network and whether the machine has been authenticated by Active Directory. This value of this property is not cached.</summary>
      public DomainType DomainType
      {
         get { return _networkConnection.GetDomainType(); }
      }


      /// <summary>Gets a value that indicates whether this connection has network connectivity. This value of this property is not cached.</summary>
      public bool IsConnected
      {
         get { return _networkConnection.IsConnected; }
      }


      /// <summary>Gets a value that indicates whether this connection has Internet access. This value of this property is not cached.</summary>
      public bool IsConnectedToInternet
      {
         get { return _networkConnection.IsConnectedToInternet; }
      }


      /// <summary>Retrieves an instance that represents the network associated with this connection. This value of this property is not cached.</summary>
      /// <returns>A <see cref="NetworkInfo"/> instance.</returns>
      public NetworkInfo NetworkInfo
      {
         get { return new NetworkInfo(_networkConnection.GetNetwork()); }
      }


      /// <summary>Gets the network interface for this connection. This value of this property is not cached.</summary>
      public NetworkInterface NetworkInterface
      {
         get
         {
            Guid guid;
            var adapterId = _networkConnection.GetAdapterId();
            
            
            foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
            {
#if NET35
               guid = new Guid(nic.Id);

#else
               if (!Guid.TryParse(nic.Id, out guid))
                  continue;
#endif

               if (Equals(adapterId, guid))
                  return nic;
            }


            return null;
         }
      }

      #endregion // Properties


      #region Methods

      /// <summary>Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber".</summary>
      /// <returns>A string that represents this instance.</returns>
      public override string ToString()
      {
         return null != NetworkInfo && null != NetworkInterface ? string.Format(CultureInfo.CurrentCulture, "{0} {1}", NetworkInfo.Name, NetworkInterface.Name) : GetType().Name;
      }


      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="obj">Another object to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public override bool Equals(object obj)
      {
         if (null == obj || GetType() != obj.GetType())
            return false;

         var other = obj as NetworkConnectionInfo;

         return null != other &&
                other.NetworkInfo == NetworkInfo &&
                other.NetworkInterface == NetworkInterface &&
                Equals(other.NetworkInfo.NetworkId, NetworkInfo.NetworkId) &&
                Equals(other.NetworkInterface.Id, NetworkInterface.Id);
      }


      /// <summary>Serves as a hash function for a particular type.</summary>
      /// <returns>A hash code for the current Object.</returns>
      public override int GetHashCode()
      {
         unchecked
         {
            return (null != NetworkInfo ? NetworkInfo.GetHashCode() : 0) + (null != NetworkInterface ? NetworkInterface.GetHashCode() : 0);
         }
      }


      /// <summary>Implements the operator ==</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator ==(NetworkConnectionInfo left, NetworkConnectionInfo right)
      {
         return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right);
      }


      /// <summary>Implements the operator !=</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator !=(NetworkConnectionInfo left, NetworkConnectionInfo right)
      {
         return !(left == right);
      }

      #endregion // Methods
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryCore.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary>
      /// <remarks>The RemoveDirectory function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed.</remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <exception cref="DirectoryReadOnlyException"/>
      /// <param name="transaction">The transaction.</param>
      /// <param name="fsEntryInfo">A FileSystemEntryInfo instance. Use either <paramref name="fsEntryInfo"/> or <paramref name="path"/>, not both.</param>
      /// <param name="path">The name of the directory to remove. Use either <paramref name="path"/> or <paramref name="fsEntryInfo"/>, not both.</param>
      /// <param name="recursive"><c>true</c> to remove all files and subdirectories recursively; <c>false</c> otherwise only the top level empty directory.</param>
      /// <param name="ignoreReadOnly"><c>true</c> overrides read only attribute of files and directories.</param>
      /// <param name="continueOnNotFound">When <c>true</c> does not throw an <see cref="DirectoryNotFoundException"/> when the directory does not exist.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void DeleteDirectoryCore(KernelTransaction transaction, FileSystemEntryInfo fsEntryInfo, string path, bool recursive, bool ignoreReadOnly, bool continueOnNotFound, PathFormat pathFormat)
      {
         if (null == fsEntryInfo)
         {
            if (null == path)
               throw new ArgumentNullException("path");
            
            fsEntryInfo = File.GetFileSystemEntryInfoCore(transaction, true, Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator), continueOnNotFound, pathFormat);

            if (null == fsEntryInfo)
               return;
         }


         PrepareDirectoryForDelete(transaction, fsEntryInfo, ignoreReadOnly);


         // Do not follow mount points nor symbolic links, but do delete the reparse point itself.
         // If directory is reparse point, disable recursion.

         if (recursive && !fsEntryInfo.IsReparsePoint)
         {
            // The stack will contain the entire folder structure to prevent any open directory handles because of enumeration.
            // The root folder is at the bottom of the stack.

            var dirs = new Stack<string>(NativeMethods.DefaultFileBufferSize);
            
            foreach (var fsei in EnumerateFileSystemEntryInfosCore<FileSystemEntryInfo>(null, transaction, fsEntryInfo.LongFullPath, Path.WildcardStarMatchAll, null, DirectoryEnumerationOptions.Recursive, null, PathFormat.LongFullPath))
            {
               PrepareDirectoryForDelete(transaction, fsei, ignoreReadOnly);

               if (fsei.IsDirectory)
                  dirs.Push(fsei.LongFullPath);

               else
                  File.DeleteFileCore(transaction, fsei.LongFullPath, ignoreReadOnly, fsei.Attributes, PathFormat.LongFullPath);
            }


            while (dirs.Count > 0)
               DeleteDirectoryNative(transaction, dirs.Pop(), ignoreReadOnly, continueOnNotFound, 0);
         }
         

         DeleteDirectoryNative(transaction, fsEntryInfo.LongFullPath, ignoreReadOnly, continueOnNotFound, fsEntryInfo.Attributes);
      }


      internal static void PrepareDirectoryForDelete(KernelTransaction transaction, FileSystemEntryInfo fsei, bool ignoreReadOnly)
      {
         // Check to see if the folder is a mount point and unmount it. Only then is it safe to delete the actual folder.

         if (fsei.IsMountPoint)

            DeleteJunctionCore(transaction, fsei, null, false, PathFormat.LongFullPath);


         // Reset attributes to Normal if we already know the facts.

         if (ignoreReadOnly && (fsei.IsReadOnly || fsei.IsHidden))

            File.SetAttributesCore(transaction, fsei.IsDirectory, fsei.LongFullPath, FileAttributes.Normal, PathFormat.LongFullPath);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Structures, Enumerations/StreamAttribute.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Attributes of data to facilitate cross-operating system transfer. This member can be one or more of the following values.</summary>
   [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")]
   [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
   public enum StreamAttribute
   {
      /// <summary>This backup stream has no special attributes.</summary>
      None = NativeMethods.STREAM_ATTRIBUTE.NONE,

      /// <summary>Attribute set if the stream contains data that is modified when read. Allows the backup application to know that verification of data will fail.</summary>
      ModifiedWhenRead = NativeMethods.STREAM_ATTRIBUTE.STREAM_MODIFIED_WHEN_READ,

      /// <summary>The backup stream contains security information. This attribute applies only to backup stream of type <see cref="StreamId.BackupSecurityData"/>.</summary>
      ContainsSecurity = NativeMethods.STREAM_ATTRIBUTE.STREAM_CONTAINS_SECURITY,

      /// <summary>Reserved.</summary>
      ContainsProperties = NativeMethods.STREAM_ATTRIBUTE.STREAM_CONTAINS_PROPERTIES,

      /// <summary>The backup stream is part of a sparse file stream. This attribute applies only to backup stream of type <see cref="StreamId.BackupData"/>, <see cref="StreamId.BackupAlternateData"/>, and <see cref="StreamId.BackupSparseBlock"/>.</summary>
      SparseAttribute = NativeMethods.STREAM_ATTRIBUTE.STREAM_SPARSE_ATTRIBUTE
   }
}


<|start_filename|>src/AlphaFS/Filesystem/CopyMoveArguments.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

namespace Alphaleonis.Win32.Filesystem
{
   internal struct CopyMoveArguments
   {
      public int Retry;
      public int RetryTimeout;

      public KernelTransaction Transaction;
      public string SourcePath;
      public string DestinationPath;

      public bool CopyTimestamps;

      public CopyOptions? CopyOptions;
      public MoveOptions? MoveOptions;

      public CopyMoveProgressRoutine ProgressHandler;
      public object UserProgressData;

      public PathFormat PathFormat;


      internal DirectoryEnumerationFilters DirectoryEnumerationFilters;
      internal string SourcePathLp;
      internal string DestinationPathLp;
      internal bool IsCopy;
      
      /// <summary>A Move action fallback using Copy + Delete.</summary>
      internal bool EmulateMove;

      /// <summary>A file/folder will be deleted or renamed on Computer startup.</summary>
      internal bool DelayUntilReboot;

      internal bool DeleteOnStartup;

      internal NativeMethods.NativeCopyMoveProgressRoutine Routine;

      internal bool PathsChecked;
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_Overwrite_DestinationDirectoryAlreadyExists.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class MoveTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Directory_Move_Overwrite_DestinationDirectoryAlreadyExists_LocalAndNetwork_Success()
      {
         AlphaFS_Directory_Move_Overwrite_DestinationDirectoryAlreadyExists(false);
         AlphaFS_Directory_Move_Overwrite_DestinationDirectoryAlreadyExists(true);
      }


      private void AlphaFS_Directory_Move_Overwrite_DestinationDirectoryAlreadyExists(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folderSrc = tempRoot.CreateTree();
            var folderDst = tempRoot.RandomDirectoryFullPath;

            Console.WriteLine("Src Directory Path: [{0}]", folderSrc.FullName);
            Console.WriteLine("Dst Directory Path: [{0}]", folderDst);
            

            Alphaleonis.Win32.Filesystem.Directory.Copy(folderSrc.FullName, folderDst);


            var dirEnumOptions = Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.FilesAndFolders | Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive;

            var props = Alphaleonis.Win32.Filesystem.Directory.GetProperties(folderSrc.FullName, dirEnumOptions);
            var sourceTotal = props["Total"];
            var sourceTotalFiles = props["File"];
            var sourceTotalSize = props["Size"];

            Console.WriteLine("\n\tTotal size: [{0}] - Total Folders: [{1}] - Files: [{2}]", Alphaleonis.Utils.UnitSizeToText(sourceTotalSize), sourceTotal - sourceTotalFiles, sourceTotalFiles);


            // Overwrite using MoveOptions.ReplaceExisting

            Alphaleonis.Win32.Filesystem.Directory.Move(folderSrc.FullName, folderDst, Alphaleonis.Win32.Filesystem.MoveOptions.ReplaceExisting);


            props = Alphaleonis.Win32.Filesystem.Directory.GetProperties(folderDst, dirEnumOptions);
            Assert.AreEqual(sourceTotal, props["Total"], "The number of total file system objects does not match, but is expected to.");
            Assert.AreEqual(sourceTotalFiles, props["File"], "The number of total files does not match, but is expected to.");
            Assert.AreEqual(sourceTotalSize, props["Size"], "The total file size does not match, but is expected to.");
         }


         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Methods/NativeMethods.Shell32.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      #region AssocXxx

      /// <summary>Returns a pointer to an IQueryAssociations object.</summary>
      /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns>
      /// <remarks>Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows 2000 Server [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint AssocCreate(Guid clsid, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IQueryAssociations ppv);

      /// <summary>Searches for and retrieves a file or protocol association-related string from the registry.</summary>
      /// <returns>Return value Type: HRESULT. Returns a standard COM error value, including the following: S_OK, E_POINTER and S_FALSE.</returns>
      /// <remarks>Minimum supported client: Windows 2000 Professional</remarks>
      /// <remarks>Minimum supported server: Windows 2000 Server</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "AssocQueryStringW"), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint AssocQueryString(Shell32.AssociationAttributes flags, Shell32.AssociationString str, [MarshalAs(UnmanagedType.LPWStr)] string pszAssoc, [MarshalAs(UnmanagedType.LPWStr)] string pszExtra, StringBuilder pszOut, [MarshalAs(UnmanagedType.U4)] out uint pcchOut);


      #region IQueryAssociations

      internal static readonly Guid ClsidQueryAssociations = new Guid("A07034FD-6CAA-4954-AC3F-97A27216F98A");
      internal const string QueryAssociationsGuid = "C46CA590-3C3F-11D2-BEE6-0000F805CA57";

      /// <summary>Exposes methods that simplify the process of retrieving information stored in the registry in association with defining a file type or protocol and associating it with an application.</summary>
      [Guid(QueryAssociationsGuid), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
      [SuppressUnmanagedCodeSecurity]
      internal interface IQueryAssociations
      {
         /// <summary>Initializes the IQueryAssociations interface and sets the root key to the appropriate ProgID.</summary>
         /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns>
         /// <remarks>Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows 2000 Server [desktop apps only]</remarks>
         void Init(Shell32.AssociationAttributes flags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssoc, IntPtr hkProgid, IntPtr hwnd);


         /// <summary>Searches for and retrieves a file or protocol association-related string from the registry.</summary>
         /// <returns>A standard COM error value, including the following: S_OK, E_POINTER, S_FALSE</returns>
         /// <remarks>Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only]</remarks>
         /// <remarks>Minimum supported server: Windows 2000 Server [desktop apps only]</remarks>
         void GetString(Shell32.AssociationAttributes flags, Shell32.AssociationString str, [MarshalAs(UnmanagedType.LPWStr)] string pwszExtra, StringBuilder pwszOut, [MarshalAs(UnmanagedType.I4)] out int pcchOut);
      }

      #endregion // IQueryAssociations

      #endregion // AssocXxx


      #region Path

      /// <summary>Determines whether a path to a file system object such as a file or folder is valid.</summary>
      /// <returns><c>true</c> if the file exists; otherwise, <c>false</c>. Call GetLastError for extended error information.</returns>
      /// <remarks>
      /// This function tests the validity of the path.
      /// A path specified by Universal Naming Convention (UNC) is limited to a file only; that is, \\server\share\file is permitted.
      /// A network share path to a server or server share is not permitted; that is, \\server or \\server\share.
      /// This function returns FALSE if a mounted remote drive is out of service.
      /// </remarks>
      /// <remarks>Minimum supported client: Windows 2000 Professional</remarks>
      /// <remarks>Minimum supported server: Windows 2000 Server</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "PathFileExistsW"), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.Bool)]
      internal static extern bool PathFileExists([MarshalAs(UnmanagedType.LPWStr)] string pszPath);


      /// <summary>Converts a file URL to a Microsoft MS-DOS path.</summary>
      /// <returns>Type: HRESULT
      /// If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
      /// </returns>
      /// <remarks>Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows 2000 Server [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "PathCreateFromUrlW"), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint PathCreateFromUrl([MarshalAs(UnmanagedType.LPWStr)] string pszUrl, StringBuilder pszPath, [MarshalAs(UnmanagedType.U4)] ref uint pcchPath, [MarshalAs(UnmanagedType.U4)] uint dwFlags);


      /// <summary>Creates a path from a file URL.</summary>
      /// <returns>Type: HRESULT
      /// If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
      /// </returns>
      /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint PathCreateFromUrlAlloc([MarshalAs(UnmanagedType.LPWStr)] string pszIn, out StringBuilder pszPath, [MarshalAs(UnmanagedType.U4)] uint dwFlags);


      /// <summary>Converts a Microsoft MS-DOS path to a canonicalized URL.</summary>
      /// <returns>Type: HRESULT
      /// Returns S_FALSE if pszPath is already in URL format. In this case, pszPath will simply be copied to pszUrl.
      /// Otherwise, it returns S_OK if successful or a standard COM error value if not.
      /// </returns>
      /// <remarks>
      /// UrlCreateFromPath does not support extended paths. These are paths that include the extended-length path prefix "\\?\".
      /// </remarks>
      /// <remarks>Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows 2000 Server [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "UrlCreateFromPathW"), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint UrlCreateFromPath([MarshalAs(UnmanagedType.LPWStr)] string pszPath, StringBuilder pszUrl, ref uint pcchUrl, [MarshalAs(UnmanagedType.U4)] uint dwFlags);


      /// <summary>Tests whether a URL is a specified type.</summary>
      /// <returns>
      /// Type: BOOL
      /// For all but one of the URL types, UrlIs returns <c>true</c> if the URL is the specified type, <c>true</c> otherwise.
      /// If UrlIs is set to <see cref="Shell32.UrlType.IsAppliable"/>, UrlIs will attempt to determine the URL scheme.
      /// If the function is able to determine a scheme, it returns <c>true</c>, or <c>false</c>.
      /// </returns>
      /// <remarks>Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows 2000 Server [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "UrlIsW"), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.Bool)]
      internal static extern bool UrlIs([MarshalAs(UnmanagedType.LPWStr)] string pszUrl, Shell32.UrlType urlIs);

      #endregion // Path


      /// <summary>Destroys an icon and frees any memory the icon occupied.</summary>
      /// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows 2000 Server [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("user32.dll", SetLastError = false)]
      [return: MarshalAs(UnmanagedType.Bool)]
      internal static extern bool DestroyIcon(IntPtr hIcon);


      /// <summary>Retrieves information about an object in the file system, such as a file, folder, directory, or drive root.</summary>
      /// <remarks>You should call this function from a background thread. Failure to do so could cause the UI to stop responding.</remarks>
      /// <remarks>Minimum supported client: Windows 2000 Professional [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows 2000 Server [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("shell32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SHGetFileInfoW"), SuppressUnmanagedCodeSecurity]
      internal static extern IntPtr ShGetFileInfo([MarshalAs(UnmanagedType.LPWStr)] string pszPath, FileAttributes dwFileAttributes, [MarshalAs(UnmanagedType.Struct)] out Shell32.FileInfo psfi, [MarshalAs(UnmanagedType.U4)] uint cbFileInfo, [MarshalAs(UnmanagedType.U4)] Shell32.FileAttributes uFlags);
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Other/FILE_INFO_BY_HANDLE_CLASS.cs<|end_filename|>
/* Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      /// <summary>Identifies the type of file information that GetFileInformationByHandleEx should retrieve or SetFileInformationByHandle should set.
      /// </summary>
      internal enum FILE_INFO_BY_HANDLE_CLASS
      {
         /// <summary>Minimal information for the file should be retrieved or set. Used for file handles.</summary>
         FILE_BASIC_INFO = 0,


         ///// <summary>Extended information for the file should be retrieved. Used for file handles. Use only when calling GetFileInformationByHandleEx.</summary>
         //FILE_STANDARD_INFO = 1,


         ///// <summary>The file name should be retrieved. Used for any handles. Use only when calling GetFileInformationByHandleEx.</summary>
         //FILE_NAME_INFO = 2,


         ///// <summary>The file name should be changed. Used for file handles. Use only when calling <see cref="SetFileInformationByHandle"/>.</summary>
         //FILE_RENAME_INFO = 3,


         ///// <summary>The file should be deleted. Used for any handles. Use only when calling <see cref="SetFileInformationByHandle"/>.</summary>
         //FILE_DISPOSITION_INFO = 4,


         ///// <summary>The file allocation information should be changed. Used for file handles. Use only when calling <see cref="SetFileInformationByHandle"/>.</summary>
         //FILE_ALLOCATION_INFO = 5,


         ///// <summary>The end of the file should be set. Use only when calling <see cref="SetFileInformationByHandle"/>.</summary>
         //FILE_END_OF_FILE_INFO = 6,


         ///// <summary>File stream information for the specified file should be retrieved. Used for any handles. Use only when calling GetFileInformationByHandleEx.</summary>
         //FILE_STREAM_INFO = 7,


         ///// <summary>File compression information should be retrieved. Used for any handles. Use only when calling GetFileInformationByHandleEx.</summary>
         //FILE_COMPRESSION_INFO = 8,


         ///// <summary>File attribute information should be retrieved. Used for any handles. Use only when calling GetFileInformationByHandleEx.</summary>
         //FILE_ATTRIBUTE_TAG_INFO = 9,


         /// <summary>Files in the specified directory should be retrieved. Used for directory handles. Use only when calling GetFileInformationByHandleEx.
         /// <remarks>
         /// The number of files returned for each call to GetFileInformationByHandleEx
         /// depends on the size of the buffer that is passed to the function.
         /// Any subsequent calls to GetFileInformationByHandleEx on the same handle
         /// will resume the enumeration operation after the last file is returned.
         /// </remarks>
         /// </summary>
         FILE_ID_BOTH_DIR_INFO = 10,


         ///// <summary>Identical to <see cref="FILE_ID_BOTH_DIR_INFO"/>, but forces the enumeration operation to start again from the beginning.</summary>
         //FILE_ID_BOTH_DIR_INFO = 11,


         ///// <summary>Priority hint information should be set. Use only when calling <see cref="SetFileInformationByHandle"/>.</summary>
         //FILE_IO_PRIORITY_HINT_INFO = 12,


         ///// <summary>File remote protocol information should be retrieved.Use for any handles. Use only when calling GetFileInformationByHandleEx.</summary>
         //FILE_REMOTE_PROTOCOL_INFO = 13,


         ///// <summary>Files in the specified directory should be retrieved. Used for directory handles. Use only when calling GetFileInformationByHandleEx.
         ///// <remarks>
         ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP:
         ///// This value is not supported before Windows 8 and Windows Server 2012
         ///// </remarks>
         ///// </summary>
         //FILE_FULL_DIR_INFO = 14,


         ///// <summary>Identical to <see cref="FILE_FULL_DIR_INFO"/>, but forces the enumeration operation to start again from the beginning. Use only when calling GetFileInformationByHandleEx.
         ///// <remarks>
         ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP:
         ///// This value is not supported before Windows 8 and Windows Server 2012
         ///// </remarks>
         ///// </summary>
         //FILE_FULL_DIR_INFO = 15,


         ///// <summary>File storage information should be retrieved. Use for any handles. Use only when calling GetFileInformationByHandleEx.
         ///// <remarks>
         ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP:
         ///// This value is not supported before Windows 8 and Windows Server 2012
         ///// </remarks>
         ///// </summary>
         //FILE_STORAGE_INFO = 16,


         ///// <summary>File alignment information should be retrieved. Use for any handles. Use only when calling GetFileInformationByHandleEx.
         ///// <remarks>
         ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP:
         ///// This value is not supported before Windows 8 and Windows Server 2012
         ///// </remarks>
         ///// </summary>
         //FILE_ALIGNMENT_INFO = 17,


         /// <summary>File information should be retrieved. Use for any handles. Use only when calling GetFileInformationByHandleEx.
         /// <remarks>
         /// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP:
         /// This value is not supported before Windows 8 and Windows Server 2012
         /// </remarks>
         /// </summary>
         FILE_ID_INFO = 18,


         ///// <summary>Files in the specified directory should be retrieved. Used for directory handles. Use only when calling GetFileInformationByHandleEx.
         ///// <remarks>
         ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP:
         ///// This value is not supported before Windows 8 and Windows Server 2012
         ///// </remarks>
         ///// </summary>
         //FILE_ID_EXTD_DIR_INFO = 19,


         ///// <summary>Identical to <see cref="FILE_ID_EXTD_DIR_INFO"/>, but forces the enumeration operation to start again from the beginning. Use only when calling GetFileInformationByHandleEx.
         ///// <remarks>
         ///// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP:
         ///// This value is not supported before Windows 8 and Windows Server 2012
         ///// </remarks>
         ///// </summary>
         //FILE_ID_EXTD_DIR_INFO = 20
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Structures, Enumerations/DiGetClassFlags.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      /// <summary>Specifies control options that filter the device information elements that are added to the device information set.</summary>
      [Flags]
      internal enum SetupDiGetClassDevsExFlags
      {
         /// <summary>DIGCF_DEFAULT
         /// <para>Return only the device that is associated with the system default device interface, if one is set, for the specified device interface classes.</para>
         /// </summary>
         Default = 1, // only valid with DIGCF_DEVICEINTERFACE

         /// <summary>DIGCF_PRESENT
         /// <para>Return only devices that are currently present.</para>
         /// </summary>
         Present = 2,

         /// <summary>DIGCF_ALLCLASSES
         /// <para>Return a list of installed devices for the specified device setup classes or device interface classes.</para>
         /// </summary>
         AllClasses = 4,

         /// <summary>DIGCF_PROFILE
         /// <para>Return only devices that are a part of the current hardware profile.</para>
         /// </summary>
         Profile = 8,

         /// <summary>DIGCF_DEVICEINTERFACE
         /// <para>
         /// Return devices that support device interfaces for the specified device interface classes.
         /// This flag must be set in the Flags parameter if the Enumerator parameter specifies a Device Instance ID. 
         /// </para>
         /// </summary>
         DeviceInterface = 16
      }
   }
}

<|start_filename|>src/AlphaFS/Filesystem/CopyMoveResult.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Class for CopyMoveResult that contains the results for the Copy or Move action.</summary>
   /// <remarks>Normally there is no need to manually instantiate and/or populate this class.</remarks>
   [Serializable]
   public sealed class CopyMoveResult
   {
      #region Private Fields

      [NonSerialized] internal readonly Stopwatch Stopwatch;

      #endregion // Private Fields
      

      #region Constructors

      /// <summary>Initializes a CopyMoveResult instance for the Copy or Move action.</summary>
      /// <param name="source">Indicates the full path to the source file or directory.</param>
      /// <param name="destination">Indicates the full path to the destination file or directory.</param>
      private CopyMoveResult(string source, string destination)
      {
         Source = source;

         Destination = destination;

         IsCopy = true;

         Retries = 0;

         Stopwatch = new Stopwatch();
      }


      internal CopyMoveResult(CopyMoveArguments cma, bool isFolder) : this(cma.SourcePath, cma.DestinationPath)
      {
         IsEmulatedMove = cma.EmulateMove;

         IsCopy = cma.IsCopy;

         IsDirectory = isFolder;

         TimestampsCopied = cma.CopyTimestamps;
      }


      internal CopyMoveResult(CopyMoveArguments cma, bool isFolder, string source, string destination) : this(source, destination)
      {
         IsEmulatedMove = cma.EmulateMove;

         IsCopy = cma.IsCopy;

         IsDirectory = isFolder;

         TimestampsCopied = cma.CopyTimestamps;
      }

      #endregion // Constructors


      #region Properties

      /// <summary>Indicates the duration of the Copy or Move action.</summary>
      public TimeSpan Duration
      {
         get { return TimeSpan.FromMilliseconds(Stopwatch.Elapsed.TotalMilliseconds); }
      }
      

      /// <summary>Indicates the destination file or directory.</summary>
      public string Destination { get; private set; }
      

      /// <summary>The error code encountered during the Copy or Move action.</summary>
      /// <value>0 (zero) indicates success.</value>
      public int ErrorCode { get; internal set; }


      /// <summary>The error message from the <see cref="ErrorCode"/> that was encountered during the Copy or Move action.</summary>
      /// <value>A message describing the error.</value>
      [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
      public string ErrorMessage { get { return new Win32Exception(ErrorCode).Message; } }


      /// <summary>When <c>true</c> indicates that the Copy or Move action was canceled.</summary>
      /// <value><c>true</c> when the Copy/Move action was canceled. Otherwise <c>false</c>.</value>
      public bool IsCanceled { get; internal set; }


      /// <summary>When <c>true</c> the action was a Copy, Move otherwise.</summary>
      /// <value><c>true</c> when the action was a Copy. Otherwise a Move action was performed.</value>
      public bool IsCopy { get; private set; }


      /// <summary>Gets a value indicating whether this instance represents a directory.</summary>
      /// <value><c>true</c> if this instance represents a directory; otherwise, <c>false</c>.</value>
      public bool IsDirectory { get; private set; }


      /// <summary>Indicates the Move action used a fallback of Copy + Delete actions.</summary>
      public bool IsEmulatedMove { get; private set; }


      /// <summary>Gets a value indicating whether this instance represents a file.</summary>
      /// <value><c>true</c> if this instance represents a file; otherwise, <c>false</c>.</value>
      public bool IsFile { get { return !IsDirectory; } }


      /// <summary>When <c>true</c> the action was a Move, Copy otherwise.</summary>
      /// <value><c>true</c> when the action was a Move. Otherwise a Copy action was performed.</value>
      public bool IsMove { get { return !IsCopy; } }


      /// <summary>The total number of retry attempts.</summary>
      public long Retries { get; internal set; }


      /// <summary>Indicates the source file or directory.</summary>
      public string Source { get; private set; }


      /// <summary>Indicates that the source date and timestamps have been applied to the destination file system objects.</summary>
      public bool TimestampsCopied { get; private set; }


      /// <summary>The total number of bytes copied.</summary>
      public long TotalBytes { get; internal set; }


      /// <summary>The total number of bytes copied, formatted as a unit size.</summary>
      public string TotalBytesUnitSize
      {
         get { return Utils.UnitSizeToText(TotalBytes); }
      }


      /// <summary>The total number of files copied.</summary>
      public long TotalFiles { get; internal set; }


      /// <summary>The total number of folders copied.</summary>
      public long TotalFolders { get; internal set; }

      #endregion // Properties
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.GetProcessForFileLock.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AlphaFS.UnitTest
{
   public partial class AlphaFS_File_LockTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_File_GetProcessForFileLock_LocalAndNetwork_Success()
      {
         AlphaFS_File_GetProcessForFileLock(false);
         AlphaFS_File_GetProcessForFileLock(true);
      }
      

      private void AlphaFS_File_GetProcessForFileLock(bool isNetwork)
      {
         var currentProcessId = System.Diagnostics.Process.GetCurrentProcess().Id;


         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var file = tempRoot.CreateFile();

            Console.WriteLine("Input File Path: [{0}]", file.FullName);


            using (file.CreateText())
            {
               var processes = Alphaleonis.Win32.Filesystem.File.GetProcessForFileLock(file.FullName);
               var processesFound = processes.Count;

               Console.WriteLine("\n\tProcesses found: [{0}]", processesFound);


               Assert.AreEqual(1, processesFound);


               foreach (var process in processes)
                  using (process)
                  {
                     UnitTestConstants.Dump(process);
                     Assert.IsTrue(process.Id == currentProcessId, "File was locked by a process other than the current process.");
                  }
            }
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.SMB.EnumerateShares.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security;
using Alphaleonis.Win32.Filesystem;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>Enumerates Server Message Block (SMB) shares from the local host.</summary>
      /// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
      /// <remarks>This method also enumerates hidden shares.</remarks>
      [SecurityCritical]
      public static IEnumerable<ShareInfo> EnumerateShares()
      {
         return EnumerateSharesCore(null, ShareType.All, false);
      }

      
      /// <summary>Enumerates Server Message Block (SMB) shares from the local host.</summary>
      /// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
      /// <remarks>This method also enumerates hidden shares.</remarks>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public static IEnumerable<ShareInfo> EnumerateShares(bool continueOnException)
      {
         return EnumerateSharesCore(null, ShareType.All, continueOnException);
      }

      
      /// <summary>Enumerates Server Message Block (SMB) shares from the local host.</summary>
      /// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
      /// <remarks>This method also enumerates hidden shares.</remarks>
      /// <param name="shareType">The type of the shared resource to retrieve.</param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public static IEnumerable<ShareInfo> EnumerateShares(ShareType shareType, bool continueOnException)
      {
         return EnumerateSharesCore(null, shareType, continueOnException);
      }

      
      /// <summary>Enumerates Server Message Block (SMB) shares from the specified <paramref name="host"/>.</summary>
      /// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
      /// <remarks>This method also enumerates hidden shares.</remarks>
      /// <param name="host">The DNS or NetBIOS name of the specified host.</param>
      [SecurityCritical]
      public static IEnumerable<ShareInfo> EnumerateShares(string host)
      {
         return EnumerateSharesCore(host, ShareType.All, false);
      }

      
      /// <summary>Enumerates Server Message Block (SMB) shares from the specified <paramref name="host"/>.</summary>
      /// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
      /// <remarks>This method also enumerates hidden shares.</remarks>
      /// <param name="host">The DNS or NetBIOS name of the specified host.</param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public static IEnumerable<ShareInfo> EnumerateShares(string host, bool continueOnException)
      {
         return EnumerateSharesCore(host, ShareType.All, continueOnException);
      }

      
      /// <summary>Enumerates Server Message Block (SMB) shares from the specified <paramref name="host"/>.</summary>
      /// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
      /// <remarks>This method also enumerates hidden shares.</remarks>
      /// <param name="host">The DNS or NetBIOS name of the specified host.</param>
      /// <param name="shareType">The type of the shared resource to retrieve.</param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      public static IEnumerable<ShareInfo> EnumerateShares(string host, ShareType shareType, bool continueOnException)
      {
         return EnumerateSharesCore(host, shareType, continueOnException);
      }




      /// <summary>Enumerates Server Message Block (SMB) shares from a local or remote host.</summary>
      /// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
      /// <remarks>This method also enumerates hidden shares.</remarks>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="host">The DNS or NetBIOS name of the specified host.</param>
      /// <param name="shareType">The type of the shared resource to retrieve.</param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      internal static IEnumerable<ShareInfo> EnumerateSharesCore(string host, ShareType shareType, bool continueOnException)
      {
         var fd = new FunctionData();
         var hasItems = false;
         var yieldAll = shareType == ShareType.All;


         // When host == null, the local computer is used.
         // However, the resulting OpenResourceInfo.Host property will be empty.
         // So, explicitly state Environment.MachineName to prevent this.
         // Furthermore, the UNC prefix: \\ is not required and always removed.
         var stripUnc = Utils.IsNullOrWhiteSpace(host) ? Environment.MachineName : Path.GetRegularPathCore(host, GetFullPathOptions.CheckInvalidPathChars, false).Replace(Path.UncPrefix, string.Empty);
         

         // Start with SHARE_INFO_503 structure.

         foreach (var shareInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_503 structure, SafeGlobalMemoryBufferHandle buffer) => new ShareInfo(stripUnc, ShareInfoLevel.Info503, structure),

            (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>

               NativeMethods.NetShareEnum(stripUnc, 503, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), continueOnException).Where(si => yieldAll || si.ShareType == shareType))
         {
            yield return shareInfo;
            hasItems = true;
         }

         if (hasItems)
            yield break;


         // Fallback on SHARE_INFO_2 structure.

         foreach (var shareInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_2 structure, SafeGlobalMemoryBufferHandle buffer) => new ShareInfo(stripUnc, ShareInfoLevel.Info2, structure),

            (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>

               NativeMethods.NetShareEnum(stripUnc, 2, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), continueOnException).Where(si => yieldAll || si.ShareType == shareType))
         {
            yield return shareInfo;
            hasItems = true;
         }

         if (hasItems)
            yield break;


         // Fallback on SHARE_INFO_1 structure.

         foreach (var shareInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_1 structure, SafeGlobalMemoryBufferHandle buffer) => new ShareInfo(stripUnc, ShareInfoLevel.Info1, structure),

            (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>

               NativeMethods.NetShareEnum(stripUnc, 1, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), continueOnException).Where(si => yieldAll || si.ShareType == shareType))
         {
            yield return shareInfo;
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryNative.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      private static void DeleteDirectoryNative(KernelTransaction transaction, string pathLp, bool ignoreReadOnly, bool continueOnNotFound, FileAttributes attributes)
      {

      startRemoveDirectory:

         var success = null == transaction || !NativeMethods.IsAtLeastWindowsVista

            // RemoveDirectory() / RemoveDirectoryTransacted()
            // 2014-09-09: MSDN confirms LongPath usage.

            // RemoveDirectory on a symbolic link will remove the link itself.

            ? NativeMethods.RemoveDirectory(pathLp)

            : NativeMethods.RemoveDirectoryTransacted(pathLp, transaction.SafeHandle);


         var lastError = Marshal.GetLastWin32Error();

         if (!success)
         {
            switch ((uint) lastError)
            {
               case Win32Errors.ERROR_DIR_NOT_EMPTY:
                  // MSDN: .NET 3.5+: IOException: The directory specified by path is not an empty directory. 
                  throw new DirectoryNotEmptyException(pathLp, true);


               case Win32Errors.ERROR_DIRECTORY:
                  // MSDN: .NET 3.5+: DirectoryNotFoundException: Path refers to a file instead of a directory.
                  if (File.ExistsCore(transaction, false, pathLp, PathFormat.LongFullPath))
                     throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", lastError, string.Format(CultureInfo.InvariantCulture, Resources.Target_Directory_Is_A_File, pathLp)));
                  break;


               case Win32Errors.ERROR_PATH_NOT_FOUND:
                  if (continueOnNotFound)
                     return;
                  break;


               case Win32Errors.ERROR_SHARING_VIOLATION:
                  // MSDN: .NET 3.5+: IOException: The directory is being used by another process or there is an open handle on the directory.
                  NativeError.ThrowException(lastError, pathLp);
                  break;


               case Win32Errors.ERROR_ACCESS_DENIED:

                  if (attributes == 0)
                  {
                     var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();

                     if (File.FillAttributeInfoCore(transaction, pathLp, ref attrs, false, true) == Win32Errors.NO_ERROR)

                        attributes = attrs.dwFileAttributes;
                  }


                  if (File.IsReadOnlyOrHidden(attributes))
                  {
                     // MSDN: .NET 3.5+: IOException: The directory specified by path is read-only.

                     if (ignoreReadOnly)
                     {
                        // Reset attributes to Normal.
                        File.SetAttributesCore(transaction, true, pathLp, FileAttributes.Normal, PathFormat.LongFullPath);

                        goto startRemoveDirectory;
                     }


                     // MSDN: .NET 3.5+: IOException: The directory is read-only.
                     throw new DirectoryReadOnlyException(pathLp);
                  }


                  // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission.
                  if (attributes == 0)
                     NativeError.ThrowException(lastError, File.IsDirectory(attributes), pathLp);

                  break;
            }

            // MSDN: .NET 3.5+: IOException:
            // A file with the same name and location specified by path exists.
            // The directory specified by path is read-only, or recursive is false and path is not an empty directory. 
            // The directory is the application's current working directory. 
            // The directory contains a read-only file.
            // The directory is being used by another process.

            NativeError.ThrowException(lastError, pathLp);
         }
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Methods/NativeMethods.KernelTransactions.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      /// <summary>
      ///   Creates a new transaction object.
      /// </summary>
      /// <remarks>
      ///   <para>Use the <see cref="CloseHandle"/> function to close the transaction handle. If the last transaction handle is closed
      ///   beforea client calls the CommitTransaction function with the transaction handle, then KTM rolls back the transaction.</para>
      ///   <para>Minimum supported client: Windows Vista</para>
      ///   <para>Minimum supported server:Windows Server 2008</para>
      /// </remarks>
      /// <returns>
      ///   <para>If the function succeeds, the return value is a handle to the transaction.</para>
      ///   <para>If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call the GetLastError
      ///   function.</para>
      /// </returns>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("ktmw32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      internal static extern SafeKernelTransactionHandle CreateTransaction([MarshalAs(UnmanagedType.LPStruct)] Security.NativeMethods.SecurityAttributes lpTransactionAttributes, IntPtr uow, [MarshalAs(UnmanagedType.U4)] uint createOptions, [MarshalAs(UnmanagedType.U4)] uint isolationLevel, [MarshalAs(UnmanagedType.U4)] uint isolationFlags, [MarshalAs(UnmanagedType.U4)] int timeout, [MarshalAs(UnmanagedType.LPWStr)] string description);

      /// <summary>Requests that the specified transaction be committed.</summary>
      /// <remarks>
      ///   <para>You can commit any transaction handle that has been opened or created using the TRANSACTION_COMMIT permission; any
      ///   application can commit a transaction, not just the creator.</para>
      ///   <para>This function can only be called if the transaction is still active, not prepared, pre-prepared, or rolled back.</para>
      ///   <para>Minimum supported client: Windows Vista</para>
      ///   <para>Minimum supported server:Windows Server 2008</para>
      /// </remarks>
      /// <returns>
      ///   <para>If the function succeeds, the return value is nonzero.</para>
      ///   <para>If the function fails, the return value is 0 (zero). To get extended error information, call the GetLastError function.</para>
      /// </returns>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("ktmw32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.Bool)]
      internal static extern bool CommitTransaction(SafeHandle hTrans);

      /// <summary>
      ///   Requests that the specified transaction be rolled back. This function is synchronous.      
      /// </summary>
      /// <returns>
      ///   <para>If the function succeeds, the return value is nonzero.</para>
      ///   <para>If the function fails, the return value is zero. To get extended error information, call the GetLastError function. </para>
      /// </returns>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("ktmw32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.Bool)]
      internal static extern bool RollbackTransaction(SafeHandle hTrans);
   }
}


<|start_filename|>tests/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetShort83PathAndGetLongFrom83ShortPath_FromFile.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Microsoft.Win32;

namespace AlphaFS.UnitTest
{
   public partial class PathTest
   {
      // Pattern: <class>_<function>_<scenario>_<expected result>


      [TestMethod]
      public void AlphaFS_Path_GetShort83PathAndGetLongFrom83ShortPath_FromFile_LocalAndNetwork_Success()
      {
         var isDisabled = (int) Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem", "NtfsDisable8dot3NameCreation", 0) > 0;
         if (isDisabled)
            UnitTestAssert.Inconclusive("NtfsDisable8dot3NameCreation is disabled in registry.");
         
         AlphaFS_Path_GetShort83PathAndGetLongFrom83ShortPath_FromFile(false);
         AlphaFS_Path_GetShort83PathAndGetLongFrom83ShortPath_FromFile(true);
      }


      private void AlphaFS_Path_GetShort83PathAndGetLongFrom83ShortPath_FromFile(bool isNetwork)
      {
         using (var tempRoot = new TemporaryDirectory(isNetwork))
         {
            var folder = System.IO.Path.Combine(tempRoot.Directory.FullName, "My Long Data File Or Directory");
            
            string short83Path;

            using (System.IO.File.Create(folder))
               short83Path = Alphaleonis.Win32.Filesystem.Path.GetShort83Path(folder);


            Console.WriteLine("Short 8.3 File Path: [{0}]", short83Path);
            
            Assert.IsTrue(!short83Path.Equals(folder));

            Assert.IsTrue(short83Path.EndsWith(@"~1"));



            var longFrom83Path = Alphaleonis.Win32.Filesystem.Path.GetLongFrom83ShortPath(short83Path);

            Console.WriteLine("Long path from 8.3 path: [{0}]", longFrom83Path);

            Assert.IsTrue(longFrom83Path.Equals(folder));

            Assert.IsFalse(longFrom83Path.EndsWith(@"~1"));
         }

         Console.WriteLine();
      }
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.DFS.GetDfsInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Net.NetworkInformation;
using System.Security;

namespace Alphaleonis.Win32.Network
{
   public static partial class Host
   {
      /// <summary>Gets information about a specified DFS root or link in a DFS namespace.</summary>
      /// <returns>A <see cref="DfsInfo"/> instance.</returns>
      /// <exception cref="NetworkInformationException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="dfsName">The Universal Naming Convention (UNC) path of a DFS root or link.</param>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")]
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "dfs")]
      [SecurityCritical]
      public static DfsInfo GetDfsInfo(string dfsName)
      {
         return GetDfsInfoCore(false, dfsName, null, null);
      }




      /// <summary>Retrieves information about a specified DFS root or link in a DFS namespace.</summary>
      /// <returns>A <see cref="DfsInfo"/> instance.</returns>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception>
      /// <param name="getFromClient">
      ///   <c>true</c> retrieves information about a Distributed File System (DFS) root or link from the cache maintained by the
      ///   DFS client. When <c>false</c> retrieves information about a specified Distributed File System (DFS) root or link in a
      ///   DFS namespace.
      /// </param>
      /// <param name="dfsName">The Universal Naming Convention (UNC) path of a DFS root or link.</param>
      /// <param name="serverName">
      ///   The name of the DFS root target or link target server. If <paramref name="getFromClient"/> is <c>false</c>, this
      ///   parameter is always <c>null</c>.
      /// </param>
      /// <param name="shareName">
      ///   The name of the share corresponding to the DFS root target or link target. If <paramref name="getFromClient"/> is
      ///   <c>false</c>, this parameter is always <c>null</c>.
      /// </param>
      [SecurityCritical]
      internal static DfsInfo GetDfsInfoCore(bool getFromClient, string dfsName, string serverName, string shareName)
      {
         if (!Filesystem.NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(new Win32Exception((int) Win32Errors.ERROR_OLD_WIN_VERSION).Message);


         if (Utils.IsNullOrWhiteSpace(dfsName))
            throw new ArgumentNullException("dfsName");


         serverName = !Utils.IsNullOrWhiteSpace(serverName) ? serverName : null;
         shareName = !Utils.IsNullOrWhiteSpace(shareName) ? shareName : null;

         SafeGlobalMemoryBufferHandle safeBuffer;


         // Level 9 = DFS_INFO_9

         var lastError = getFromClient ? NativeMethods.NetDfsGetClientInfo(dfsName, serverName, shareName, 9, out safeBuffer) : NativeMethods.NetDfsGetInfo(dfsName, null, null, 9, out safeBuffer);

         if (lastError == Win32Errors.NERR_Success)
            return new DfsInfo(safeBuffer.PtrToStructure<NativeMethods.DFS_INFO_9>(0));

         throw new NetworkInformationException((int)lastError);
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Link Stream/AlternateDataStreamInfo.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System;
using System.Globalization;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Information about an alternate data stream.</summary>  
   /// <seealso cref="O:Alphaleonis.Win32.Filesystem.File.EnumerateAlternateDataStreams"/> 
   [Serializable]
   public struct AlternateDataStreamInfo : IEquatable<AlternateDataStreamInfo>
   {
      #region Fields

      [NonSerialized] private readonly string _fullPath;
      [NonSerialized] private readonly string _streamName;
      
      #endregion // Fields


      #region Constructor

      internal AlternateDataStreamInfo(string fullPath, NativeMethods.WIN32_FIND_STREAM_DATA findData)
      {
         _fullPath = fullPath;

         Size = findData.StreamSize;

         _streamName = ParseStreamName(findData.cStreamName);
      }

      #endregion // Constructor


      #region Properties

      /// <summary>Gets the full path to the stream.</summary>
      /// <remarks>
      ///   This is a path in long path format that can be passed to <see cref="O:Alphaleonis.Win32.Filesystem.File.Open"/> to open the stream if
      ///   <see cref="PathFormat.FullPath"/> or <see cref="PathFormat.LongFullPath"/> is specified.
      /// </remarks>
      /// <value>The full path to the stream in long path format.</value>
      public string FullPath
      {
         get { return string.Format(CultureInfo.InvariantCulture, "{0}{1}", _fullPath, !Utils.IsNullOrWhiteSpace(StreamName) ? Path.StreamSeparator + StreamName : string.Empty); }
      }
      

      /// <summary>Gets the size of the stream.</summary>      
      public long Size { get; private set; }


      /// <summary>Gets the name of the alternate data stream.</summary>
      /// <remarks>This value is an empty string for the default stream (:$DATA), and for any other data stream it contains the name of the stream.</remarks>
      /// <value>The name of the stream.</value>
      public string StreamName
      {
         get { return _streamName; }
      }

      #endregion // Properties


      #region Methods

      /// <summary>Returns the hash code for this instance.</summary>
      /// <returns>A 32-bit signed integer that is the hash code for this instance.</returns>
      public override int GetHashCode()
      {
         return Utils.CombineHashCodesOf(StreamName, FullPath);
      }
      

      /// <summary>Determines whether the specified Object is equal to the current Object.</summary>
      /// <param name="other">Another <see cref="AlternateDataStreamInfo"/> instance to compare to.</param>
      /// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
      public bool Equals(AlternateDataStreamInfo other)
      {
         return GetType() == other.GetType() &&
                Equals(StreamName, other.StreamName) &&
                Equals(FullPath, other.FullPath) &&
                Equals(Size, other.Size);
      }


      /// <summary>Indicates whether this instance and a specified object are equal.</summary>
      /// <param name="obj">The object to compare with the current instance.</param>
      /// <returns>
      ///   true if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false.
      /// </returns>
      public override bool Equals(object obj)
      {
         return obj is AlternateDataStreamInfo && Equals((AlternateDataStreamInfo) obj);
      }


      // <summary>Implements the operator ==</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator ==(AlternateDataStreamInfo left, AlternateDataStreamInfo right)
      {
         return left.Equals(right);
      }


      /// <summary>Implements the operator !=</summary>
      /// <param name="left">A.</param>
      /// <param name="right">B.</param>
      /// <returns>The result of the operator.</returns>
      public static bool operator !=(AlternateDataStreamInfo left, AlternateDataStreamInfo right)
      {
         return !(left == right);
      }

      #endregion // Methods


      #region Private Methods

      private static string ParseStreamName(string streamName)
      {
         if (null == streamName || streamName.Length < 2)
            return string.Empty;

         if (streamName[0] != Path.StreamSeparatorChar)
            throw new ArgumentException(Resources.Invalid_Stream_Name, "streamName");

         
         var sb = new StringBuilder(streamName.Length);

         for (int i = 1, l = streamName.Length; i < l; i++)
         {
            if (streamName[i] == Path.StreamSeparatorChar)
               break;

            sb.Append(streamName[i]);
         }


         return sb.ToString();
      }

      #endregion // Private Methods
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Structures, Enumerations/FileEncryptionStatus.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Represents the encryption status of the specified file.</summary>
   public enum FileEncryptionStatus
   {
      /// <summary>The file can be encrypted.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Encryptable")]
      Encryptable = 0,

      /// <summary>The file is encrypted.</summary>
      Encrypted = 1,

      /// <summary>The file is a system file. System files cannot be encrypted.</summary>
      SystemFile = 2,

      /// <summary>The file is a root directory. Root directories cannot be encrypted.</summary>
      RootDirectory = 3,

      /// <summary>The file is a system directory. System directories cannot be encrypted.</summary>
      SystemDirectory = 4,

      /// <summary>The encryption status is unknown. The file may be encrypted.</summary>
      Unknown = 5,

      /// <summary>The file system does not support file encryption.</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Filesystem")]
      NoFilesystemSupport = 6,

      /// <summary>Reserved for future use.</summary>
      UserDisallowed = 7,

      /// <summary>The file is a read-only file.</summary>
      ReadOnly = 8
   }
}

<|start_filename|>src/AlphaFS/Filesystem/Structures, Enumerations/ReparsePointTag.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Diagnostics.CodeAnalysis;

namespace Alphaleonis.Win32.Filesystem
{
   /// <summary>Enumeration specifying the different reparse point tags.</summary>
   /// <remarks>
   ///   <para>Reparse tags, with the exception of IO_REPARSE_TAG_SYMLINK, are processed on the server and are not processed by a client after transmission over the wire.</para>
   ///   <para>Clients should treat associated reparse data as opaque data.</para>
   /// </remarks>
   public enum ReparsePointTag
   {
      /// <summary>The entry is not a reparse point.</summary>
      None = 0,

      /// <summary>IO_REPARSE_APPXSTREAM</summary>
      AppXStream = unchecked ((int) 3221225492),

      /// <summary>IO_REPARSE_TAG_CSV</summary>
      Csv = unchecked ((int) 2147483657),

      /// <summary>IO_REPARSE_TAG_DRIVER_EXTENDER
      /// <para>Used by Home server drive extender.</para>
      /// </summary>
      DriverExtender = unchecked ((int) 2147483653),

      /// <summary>IO_REPARSE_TAG_DEDUP</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dedup")]
      Dedup = unchecked ((int) 2147483667),

      /// <summary>IO_REPARSE_TAG_DFS
      /// <para>Used by the DFS filter.</para>
      /// </summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")]
      Dfs = unchecked ((int) 2147483658),

      /// <summary>IO_REPARSE_TAG_DFSR
      /// <para>Used by the DFS filter.</para>
      /// </summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfsr")]
      Dfsr = unchecked ((int) 2147483666),

      /// <summary>IO_REPARSE_TAG_FILTER_MANAGER
      /// <para>Used by filter manager test harness.</para>
      /// </summary>
      FilterManager = unchecked ((int) 2147483659),

      /// <summary>IO_REPARSE_TAG_HSM
      /// <para>(Obsolete) Used by legacy Hierarchical Storage Manager Product.</para>
      /// </summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hsm")]
      Hsm = unchecked ((int) 3221225476),

      /// <summary>IO_REPARSE_TAG_HSM2
      /// <para>(Obsolete) Used by legacy Hierarchical Storage Manager Product.</para>
      /// </summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hsm")]
      Hsm2 = unchecked ((int) 2147483654),

      /// <summary>IO_REPARSE_TAG_NFS
      /// <para>NFS symlinks, Windows 8 / SMB3 and later.</para>
      /// </summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nfs")]
      Nfs = unchecked ((int) 2147483668),

      /// <summary>IO_REPARSE_TAG_MOUNT_POINT
      /// <para>Used for mount point support.</para>
      /// </summary>
      MountPoint = unchecked ((int) 2684354563),

      /// <summary>IO_REPARSE_TAG_SIS
      /// <para>Used by single-instance storage (SIS) filter driver.</para>
      /// </summary>
      Sis = unchecked ((int) 2147483655),

      /// <summary>IO_REPARSE_TAG_SYMLINK
      /// <para>Used for symbolic link support.</para>
      /// </summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sym")]
      SymLink = unchecked ((int) 2684354572),

      /// <summary>IO_REPARSE_TAG_WIM</summary>
      [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wim")]
      Wim = unchecked ((int) 2147483656)
   }
}


<|start_filename|>src/AlphaFS/Network/Host Class/Host.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using Alphaleonis.Win32.Filesystem;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Path = Alphaleonis.Win32.Filesystem.Path;

namespace Alphaleonis.Win32.Network
{
   /// <summary>Provides static methods to retrieve network resource information from a local- or remote host.</summary>
   public static partial class Host
   {
      private static readonly NativeMethods.NetworkListManager Manager = new NativeMethods.NetworkListManager();

      internal delegate uint EnumerateNetworkObjectDelegate(FunctionData functionData, out SafeGlobalMemoryBufferHandle netApiBuffer, [MarshalAs(UnmanagedType.I4)] int prefMaxLen,
         [MarshalAs(UnmanagedType.U4)] out uint entriesRead, [MarshalAs(UnmanagedType.U4)] out uint totalEntries, [MarshalAs(UnmanagedType.U4)] out uint resumeHandle);


      /// <summary>Structure is used to pass additional data to the Win32 function.</summary>
      internal struct FunctionData
      {
         public int EnumType;
         public string ExtraData1;
         public string ExtraData2;
      }


      internal struct ConnectDisconnectArguments
      {
         /// <summary>Handle to a window that the provider of network resources can use as an owner window for dialog boxes.</summary>
         public IntPtr WinOwner;

         /// <summary>The name of a local device to be redirected, such as "F:". When <see cref="LocalName"/> is <c>null</c> or <c>string.Empty</c>, the last available drive letter will be used. Letters are assigned beginning with Z:, then Y: and so on.</summary>
         public string LocalName;

         /// <summary>A network resource to connect to/disconnect from, for example: \\server or \\server\share. The string can be up to <see cref="Filesystem.NativeMethods.MaxPath"/> characters in length.</summary>
         public string RemoteName;

         /// <summary>A <see cref="NetworkCredential"/> instance. Use either this or the combination of <see cref="UserName"/> and <see cref="Password"/>.</summary>
         public NetworkCredential Credential;

         /// <summary>The user name for making the connection. If <see cref="UserName"/> is <c>null</c>, the function uses the default user name. (The user context for the process provides the default user name)</summary>
         public string UserName;

         /// <summary>The password to be used for making the network connection. If <see cref="Password"/> is <c>null</c>, the function uses the current default password associated with the user specified by <see cref="UserName"/>.</summary>
         public string Password;

         /// <summary><c>true</c> always pops-up an authentication dialog box.</summary>
         public bool Prompt;

         /// <summary><c>true</c> successful network resource connections will be saved.</summary>
         public bool UpdateProfile;

         /// <summary>When the operating system prompts for a credential, the credential should be saved by the credential manager when true.</summary>
         public bool SaveCredentials;

         /// <summary><c>true</c> indicates that the operation concerns a drive mapping.</summary>
         public bool IsDeviceMap;

         /// <summary><c>true</c> indicates that the operation needs to disconnect from the network resource, otherwise connect.</summary>
         public bool IsDisconnect;
      }


      /// <summary>Connects to/disconnects from a network resource. The function can redirect a local device to a network resource.</summary>
      /// <returns>If <see cref="ConnectDisconnectArguments.LocalName"/> is <c>null</c> or <c>string.Empty</c>, returns the last available drive letter, null otherwise.</returns>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="arguments">The <see cref="ConnectDisconnectArguments"/>.</param>
      [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
      [SecurityCritical]
      internal static string ConnectDisconnectCore(ConnectDisconnectArguments arguments)
      {
         uint lastError;

         // Always remove backslash.
         if (!Utils.IsNullOrWhiteSpace(arguments.LocalName))
            arguments.LocalName = Path.RemoveTrailingDirectorySeparator(arguments.LocalName).ToUpperInvariant();

         
         if (!Utils.IsNullOrWhiteSpace(arguments.RemoteName))
         {
            if (!arguments.RemoteName.StartsWith(Path.UncPrefix, StringComparison.Ordinal))
               arguments.RemoteName = Path.UncPrefix + arguments.RemoteName;


            // Always remove backslash.
            if (!Utils.IsNullOrWhiteSpace(arguments.RemoteName))
               arguments.RemoteName = Path.RemoveTrailingDirectorySeparator(arguments.RemoteName);
         }

         
         // Disconnect

         if (arguments.IsDisconnect)
         {
            var force = arguments.Prompt; // Use value of prompt variable for force value.
            var target = arguments.IsDeviceMap ? arguments.LocalName : arguments.RemoteName;

            if (Utils.IsNullOrWhiteSpace(target))
               throw new ArgumentNullException(arguments.IsDeviceMap ? "localName" : "remoteName");


            lastError = NativeMethods.WNetCancelConnection(target, arguments.UpdateProfile ? NativeMethods.Connect.UpdateProfile : NativeMethods.Connect.None, force);

            if (lastError != Win32Errors.NO_ERROR)
               throw new NetworkInformationException((int) lastError);

            return null;
         }

         
         // Connect

         // arguments.LocalName is allowed to be null or empty.

         if (Utils.IsNullOrWhiteSpace(arguments.RemoteName) && !arguments.IsDeviceMap)
            throw new ArgumentNullException("arguments.RemoteName");
         

         // When supplied, use data from NetworkCredential instance.
         if (arguments.Credential != null)
         {
            arguments.UserName = Utils.IsNullOrWhiteSpace(arguments.Credential.Domain)
               ? arguments.Credential.UserName
               : string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", arguments.Credential.Domain, arguments.Credential.UserName);

            arguments.Password = arguments.Credential.Password;
         }


         // Assemble Connect arguments.
         var connect = NativeMethods.Connect.None;

         if (arguments.IsDeviceMap)
            connect = connect | NativeMethods.Connect.Redirect;

         if (arguments.Prompt)
            connect = connect | NativeMethods.Connect.Prompt | NativeMethods.Connect.Interactive;

         if (arguments.UpdateProfile)
            connect = connect | NativeMethods.Connect.UpdateProfile;

         if (arguments.SaveCredentials)
            connect = connect | NativeMethods.Connect.SaveCredentialManager;


         // Initialize structure.
         var resource = new NativeMethods.NETRESOURCE
         {
            lpLocalName = arguments.LocalName,
            lpRemoteName = arguments.RemoteName,
            dwType = NativeMethods.ResourceType.Disk
         };

         // Three characters for: "X:\0" (Drive X: with null terminator)
         uint bufferSize = 3;
         StringBuilder buffer;

         do
         {
            buffer = new StringBuilder((int) bufferSize);

            uint result;
            lastError = NativeMethods.WNetUseConnection(arguments.WinOwner, ref resource, arguments.Password, arguments.UserName, connect, buffer, out bufferSize, out result);

            switch (lastError)
            {
               case Win32Errors.NO_ERROR:
                  break;

               case Win32Errors.ERROR_MORE_DATA:
                  // MSDN, lpBufferSize: If the call fails because the buffer is not large enough,
                  // the function returns the required buffer size in this location.
                  //
                  // Windows 8 x64: bufferSize remains unchanged.

                  bufferSize = bufferSize * 2;
                  break;
            }

         } while (lastError == Win32Errors.ERROR_MORE_DATA);


         if (lastError != Win32Errors.NO_ERROR)
            throw new NetworkInformationException((int) lastError);


         return arguments.IsDeviceMap ? buffer.ToString() : null;
      }
      

      [SecurityCritical]
      internal static IEnumerable<TStruct> EnumerateNetworkObjectCore<TStruct, TNative>(FunctionData functionData, Func<TNative, SafeGlobalMemoryBufferHandle, TStruct> createTStruct, EnumerateNetworkObjectDelegate enumerateNetworkObject, bool continueOnException)
      {
         int objectSize;
         bool isString;

         switch (functionData.EnumType)
         {
            // Logical Drives
            case 1:
               isString = true;
               objectSize = 6; // Should always be 6.
               break;

            default:
               var objectType = typeof(TNative);
               isString = objectType == typeof(string);
               objectSize = isString ? 0 : Marshal.SizeOf(objectType);
               break;
         }


         uint lastError;
         do
         {
            uint entriesRead;
            uint totalEntries;
            uint resumeHandle;
            SafeGlobalMemoryBufferHandle buffer;

            lastError = enumerateNetworkObject(functionData, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle);

            using (buffer)
               switch (lastError)
               {
                  case Win32Errors.NERR_Success:
                  case Win32Errors.ERROR_MORE_DATA:
                     if (entriesRead > 0)
                     {
                        for (int i = 0, itemOffset = 0; i < entriesRead; i++, itemOffset += objectSize)

                           yield return (TStruct) (isString ? buffer.PtrToStringUni(itemOffset, 2) : (object) createTStruct(buffer.PtrToStructure<TNative>(itemOffset), buffer));
                     }
                     break;

                  
                  // Observed when SHARE_INFO_503 is requested but not supported/possible.
                  case Win32Errors.RPC_X_BAD_STUB_DATA:
                  case Win32Errors.ERROR_NOT_SUPPORTED:
                     yield break;


                  default:
                     if (lastError != Win32Errors.NO_ERROR && !continueOnException)
                        throw new NetworkInformationException((int) lastError);
                     break;
               }

         } while (lastError == Win32Errors.ERROR_MORE_DATA);
      }


      /// <summary>This method uses <see cref="NativeMethods.REMOTE_NAME_INFO"/> level to retrieve full REMOTE_NAME_INFO structure.</summary>
      /// <returns>A <see cref="NativeMethods.REMOTE_NAME_INFO"/> structure.</returns>
      /// <remarks>AlphaFS regards network drives created using SUBST.EXE as invalid.</remarks>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="PathTooLongException"/>
      /// <exception cref="NetworkInformationException"/>
      /// <param name="path">The local path with drive name.</param>
      /// <param name="continueOnException"><c>true</c> suppress any Exception that might be thrown as a result from a failure, such as unavailable resources.</param>
      [SecurityCritical]
      internal static NativeMethods.REMOTE_NAME_INFO GetRemoteNameInfoCore(string path, bool continueOnException)
      {
         if (Utils.IsNullOrWhiteSpace(path))
            throw new ArgumentNullException("path");


         path = Path.GetRegularPathCore(path, GetFullPathOptions.CheckInvalidPathChars, false);


         uint lastError;
         uint bufferSize = 1024;

         do
         {
            using (var buffer = new SafeGlobalMemoryBufferHandle((int) bufferSize))
            {
               // Structure: UNIVERSAL_NAME_INFO_LEVEL = 1 (not used in AlphaFS).
               // Structure: REMOTE_NAME_INFO_LEVEL    = 2

               lastError = NativeMethods.WNetGetUniversalName(path, 2, buffer, out bufferSize);

               if (lastError == Win32Errors.NO_ERROR)
                  return buffer.PtrToStructure<NativeMethods.REMOTE_NAME_INFO>(0);
            }

         } while (lastError == Win32Errors.ERROR_MORE_DATA);


         if (lastError != Win32Errors.NO_ERROR && !continueOnException)
            throw new NetworkInformationException((int) lastError);


         // Return an empty structure (all fields set to null).
         return new NativeMethods.REMOTE_NAME_INFO();
      }
   }
}


<|start_filename|>src/AlphaFS/Filesystem/Native Methods/NativeMethods.PathManagement.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      /// <summary>Retrieves the full path and file name of the specified file or directory.</summary>
      /// <returns>If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError.</returns>
      /// <remarks>The GetFullPathName function is not recommended for multithreaded applications or shared library code.</remarks>
      /// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetFullPathNameW"), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint GetFullPathName([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] uint nBufferLength, StringBuilder lpBuffer, IntPtr lpFilePart);

      /// <summary>Retrieves the full path and file name of the specified file or directory as a transacted operation.</summary>
      /// <returns>If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError.</returns>
      /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetFullPathNameTransactedW"), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint GetFullPathNameTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] uint nBufferLength, StringBuilder lpBuffer, IntPtr lpFilePart, SafeHandle hTransaction);

      /// <summary>Converts the specified path to its long form.</summary>
      /// <returns>
      /// If the function succeeds, the return value is nonzero.
      /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
      /// </returns>
      /// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetLongPathNameW"), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint GetLongPathName([MarshalAs(UnmanagedType.LPWStr)] string lpszShortPath, StringBuilder lpszLongPath, [MarshalAs(UnmanagedType.U4)] uint cchBuffer);

      /// <summary>Converts the specified path to its long form as a transacted operation.</summary>
      /// <returns>
      /// If the function succeeds, the return value is nonzero.
      /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
      /// </returns>
      /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
      /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetLongPathNameTransactedW"), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint GetLongPathNameTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpszShortPath, StringBuilder lpszLongPath, [MarshalAs(UnmanagedType.U4)] uint cchBuffer, SafeHandle hTransaction);

      /// <summary>Retrieves the short path form of the specified path.</summary>
      /// <returns>
      /// If the function succeeds, the return value is nonzero.
      /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
      /// </returns>
      /// <remarks>Minimum supported client: Windows XP</remarks>
      /// <remarks>Minimum supported server: Windows Server 2003</remarks>
      [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
      [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetShortPathNameW"), SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.U4)]
      internal static extern uint GetShortPathName([MarshalAs(UnmanagedType.LPWStr)] string lpszLongPath, StringBuilder lpszShortPath, [MarshalAs(UnmanagedType.U4)] uint cchBuffer);
   }
}


<|start_filename|>src/AlphaFS/Network/Native Other/STAT_WORKSTATION_0.cs<|end_filename|>
/*  Copyright (C) 2008-2018 <NAME>, <NAME>, <NAME>
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy 
 *  of this software and associated documentation files (the "Software"), to deal 
 *  in the Software without restriction, including without limitation the rights 
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 *  copies of the Software, and to permit persons to whom the Software is 
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *  THE SOFTWARE. 
 */

using System.Runtime.InteropServices;

namespace Alphaleonis.Win32.Network
{
   internal static partial class NativeMethods
   {
      /// <summary>Contains statistical information about the specified workstation.</summary>
      /// <remarks>
      /// <para>Minimum supported client: Windows XP [desktop apps only]</para>
      /// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
      /// </remarks>
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      internal struct STAT_WORKSTATION_0
      {
         /// <summary>
         /// <para>Specifies the time statistics collection started. This member also indicates when statistics for the workstations were last cleared.</para>
         /// <para>The value is stored as the number of seconds elapsed since 00:00:00, January 1, 1970.</para>
         /// </summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long StatisticsStartTime;

         
         /// <summary>Specifies the total number of bytes received by the workstation.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long BytesReceived;

         /// <summary>Specifies the total number of server message blocks (SMBs) received by the workstation.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long SmbsReceived;

         /// <summary>Specifies the total number of bytes that have been read by paging I/O requests.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long PagingReadBytesRequested;

         /// <summary>Specifies the total number of bytes that have been read by non-paging I/O requests.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long NonPagingReadBytesRequested;

         /// <summary>Specifies the total number of bytes that have been read by cache I/O requests.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long CacheReadBytesRequested;

         /// <summary>Specifies the total amount of bytes that have been read by disk I/O requests.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long NetworkReadBytesRequested;

         /// <summary>Specifies the total number of bytes transmitted by the workstation.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long BytesTransmitted;

         /// <summary>Specifies the total number of SMBs transmitted by the workstation.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long SmbsTransmitted;

         /// <summary>Specifies the total number of bytes that have been written by paging I/O requests.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long PagingWriteBytesRequested;

         /// <summary>Specifies the total number of bytes that have been written by non-paging I/O requests.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long NonPagingWriteBytesRequested;

         /// <summary>Specifies the total number of bytes that have been written by cache I/O requests.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long CacheWriteBytesRequested;

         /// <summary>Specifies the total number of bytes that have been written by disk I/O requests.</summary>
         [MarshalAs(UnmanagedType.U8)] public readonly long NetworkWriteBytesRequested;

         /// <summary>Specifies the total number of network operations that failed to begin.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint InitiallyFailedOperations;

         /// <summary>Specifies the total number of network operations that failed to complete.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint FailedCompletionOperations;

         /// <summary>Specifies the total number of read operations initiated by the workstation.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint ReadOperations;

         /// <summary>Specifies the total number of random access reads initiated by the workstation.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint RandomReadOperations;

         /// <summary>Specifies the total number of read requests the workstation has sent to servers.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint ReadSmbs;

         /// <summary>Specifies the total number of read requests the workstation has sent to servers that are greater than twice the size of the server's negotiated buffer size.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint LargeReadSmbs;

         /// <summary>Specifies the total number of read requests the workstation has sent to servers that are less than 1/4 of the size of the server's negotiated buffer size.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint SmallReadSmbs;

         /// <summary>Specifies the total number of write operations initiated by the workstation.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint WriteOperations;

         /// <summary>Specifies the total number of random access writes initiated by the workstation.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint RandomWriteOperations;

         /// <summary>Specifies the total number of write requests the workstation has sent to servers.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint WriteSmbs;

         /// <summary>Specifies the total number of write requests the workstation has sent to servers that are greater than twice the size of the server's negotiated buffer size.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint LargeWriteSmbs;

         /// <summary>Specifies the total number of write requests the workstation has sent to servers that are less than 1/4 of the size of the server's negotiated buffer size.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint SmallWriteSmbs;

         /// <summary>Specifies the total number of raw read requests made by the workstation that have been denied.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint RawReadsDenied;

         /// <summary>Specifies the total number of raw write requests made by the workstation that have been denied.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint RawWritesDenied;

         /// <summary>Specifies the total number of network errors received by the workstation.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint NetworkErrors;

         /// <summary>Specifies the total number of workstation sessions that were established.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint Sessions;

         /// <summary>Specifies the number of times the workstation attempted to create a session but failed.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint FailedSessions;

         /// <summary>Specifies the total number of connections that have failed.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint Reconnects;

         /// <summary>Specifies the total number of connections to servers supporting the PCNET dialect that have succeeded.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint CoreConnects;

         /// <summary>Specifies the total number of connections to servers supporting the LanManager 2.0 dialect that have succeeded.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint Lanman20Connects;

         /// <summary>Specifies the total number of connections to servers supporting the LanManager 2.1 dialect that have succeeded.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint Lanman21Connects;

         /// <summary>Specifies the total number of connections to servers supporting the NTLM dialect that have succeeded.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint LanmanNtConnects;

         /// <summary>Specifies the number of times the workstation was disconnected by a network server.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint ServerDisconnects;

         /// <summary>Specifies the total number of sessions that have expired on the workstation.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint HungSessions;

         /// <summary>Specifies the total number of network connections established by the workstation.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint UseCount;

         /// <summary>Specifies the total number of failed network connections for the workstation.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint FailedUseCount;

         /// <summary>Specifies the number of current requests that have not been completed.</summary>
         [MarshalAs(UnmanagedType.U4)] public readonly uint CurrentCommands;
      }
   }
}
