From cf06772b005bf68ec6db0c7ed2db56fb168c8311 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 30 Jan 2018 10:36:10 +0100 Subject: [PATCH 001/133] PhysicalDriveInfo - Work in progress. --- ....cs => AlphaFS_Device.EnumerateDevices.cs} | 28 +- .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 60 ++ ... AlphaFS_DeviceInfo.InitializeInstance.cs} | 14 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 5 +- AlphaFS.UnitTest/_Utils/UnitTestConstants.cs | 12 + AlphaFS/AlphaFS.csproj | 71 +- AlphaFS/Device/Device.Compression.cs | 44 ++ AlphaFS/Device/Device.DeviceEnumeration.cs | 182 +++++ .../Device/Device.EnumeratePhysicalDrives.cs | 40 + AlphaFS/Device/Device.GetPhysicalDriveInfo.cs | 204 +++++ .../Device/Device.GetPhysicalDriveNumber.cs | 81 ++ AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 89 +++ AlphaFS/Device/Device.cs | 513 ++++--------- AlphaFS/Device/DeviceInfo.cs | 20 +- AlphaFS/Device/DiskSpaceInfo.cs | 6 +- .../DriveInfo.EnumerateLogicalDrives.cs | 114 +++ .../DriveInfo/DriveInfo.GetDeviceInfo.cs | 139 ++++ .../DriveInfo/DriveInfo.GetFreeDriveLetter.cs | 59 ++ AlphaFS/Device/{ => DriveInfo}/DriveInfo.cs | 218 ++---- .../Device.CreateDirectoryJunction.cs | 80 ++ .../Device.DeleteDirectoryJunction.cs | 55 ++ .../Junctions, Links/Device.GetLinkTarget.cs | 126 ++++ AlphaFS/Device/PhysicalDriveInfo.cs | 120 +++ .../Volume/Volume.EnumerateVolumePathNames.cs | 30 +- .../Device/Volume/Volume.EnumerateVolumes.cs | 15 +- .../Volume/Volume.GetVolumeDeviceName.cs | 10 +- .../Volume/Volume.GetVolumeDisplayName.cs | 6 +- AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs | 79 +- AlphaFS/Device/Volume/VolumeInfo.cs | 173 +++-- AlphaFS/Filesystem/File Class/File.Create.cs | 8 +- .../File Class/File.OpenPhysicalDrive.cs | 49 ++ .../Native Methods/NativeMethods.Constants.cs | 27 +- .../NativeMethods.DeviceManagement.cs | 74 +- .../NativeMethods.EncryptedFileRaw.cs | 2 +- .../NativeMethods.FileManagement.cs | 4 +- .../Native Methods/NativeMethods.Utilities.cs | 24 +- .../NativeMethods.VolumeManagement.cs | 65 +- .../Filesystem/Native Other/DISK_EXTENT.cs | 43 ++ .../Filesystem/Native Other/IoControlCode.cs | 700 ++++++++++++++++++ AlphaFS/Filesystem/Native Other/IoMethod.cs | 45 ++ .../Native Other/STORAGE_BUS_TYPE.cs | 91 +++ .../Native Other/STORAGE_DEVICE_DESCRIPTOR.cs | 72 ++ .../Native Other/STORAGE_DEVICE_NUMBER.cs | 48 ++ .../Native Other/STORAGE_DEVICE_TYPE.cs | 267 +++++++ .../Native Other/STORAGE_PROPERTY_QUERY.cs | 48 ++ .../Native Other/VOLUME_DISK_EXTENTS.cs | 39 + .../CopyMoveProgressCallbackReason.cs | 0 .../CopyMoveProgressResult.cs | 0 .../CopyOptions.cs | 0 .../DeviceGuid.cs | 22 +- .../DiGetClassFlags.cs | 0 .../DirectoryEnumerationFilters.cs | 0 .../DirectoryEnumerationOptions.cs | 0 .../DosDeviceAttributes.cs | 0 .../EncryptedFileRawMode.cs | 0 .../ErrorMode.cs | 0 .../ExtendedFileAttributes.cs | 2 +- .../FileEncryptionStatus.cs | 0 .../FileIdInfo.cs | 18 +- .../FinalPathFormats.cs | 0 .../GetFullPathOptions.cs | 0 .../MoveOptions.cs | 0 .../PathFormat.cs | 0 .../ReparsePointTag.cs | 0 .../SetupDiGetDeviceRegistryPropertyEnum.cs | 0 .../StorageBusType.cs | 97 +++ .../StorageDeviceType.cs | 282 +++++++ .../SymbolicLinkTarget.cs | 0 .../SymbolicLinkType.cs | 0 AlphaFS/Resources.Designer.cs | 9 + AlphaFS/Resources.resx | 7 +- AlphaFS/Win32Errors.cs | 6 +- 72 files changed, 3758 insertions(+), 884 deletions(-) rename AlphaFS.UnitTest/AlphaFS Device Class/{AlphaFS_Device_EnumerateDevices.cs => AlphaFS_Device.EnumerateDevices.cs} (80%) create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs rename AlphaFS.UnitTest/AlphaFS Device Class/{AlphaFS_DeviceInfo_InitializeInstance.cs => AlphaFS_DeviceInfo.InitializeInstance.cs} (85%) create mode 100644 AlphaFS/Device/Device.Compression.cs create mode 100644 AlphaFS/Device/Device.DeviceEnumeration.cs create mode 100644 AlphaFS/Device/Device.EnumeratePhysicalDrives.cs create mode 100644 AlphaFS/Device/Device.GetPhysicalDriveInfo.cs create mode 100644 AlphaFS/Device/Device.GetPhysicalDriveNumber.cs create mode 100644 AlphaFS/Device/Device.GetVolumeDiskExtents.cs create mode 100644 AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs create mode 100644 AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs create mode 100644 AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs rename AlphaFS/Device/{ => DriveInfo}/DriveInfo.cs (59%) create mode 100644 AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs create mode 100644 AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs create mode 100644 AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs create mode 100644 AlphaFS/Device/PhysicalDriveInfo.cs create mode 100644 AlphaFS/Filesystem/File Class/File.OpenPhysicalDrive.cs create mode 100644 AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs create mode 100644 AlphaFS/Filesystem/Native Other/IoControlCode.cs create mode 100644 AlphaFS/Filesystem/Native Other/IoMethod.cs create mode 100644 AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs create mode 100644 AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs create mode 100644 AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs create mode 100644 AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs create mode 100644 AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs create mode 100644 AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/CopyMoveProgressCallbackReason.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/CopyMoveProgressResult.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/CopyOptions.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/DeviceGuid.cs (95%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/DiGetClassFlags.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/DirectoryEnumerationFilters.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/DirectoryEnumerationOptions.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/DosDeviceAttributes.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/EncryptedFileRawMode.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/ErrorMode.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/ExtendedFileAttributes.cs (99%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/FileEncryptionStatus.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/FileIdInfo.cs (92%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/FinalPathFormats.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/GetFullPathOptions.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/MoveOptions.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/PathFormat.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/ReparsePointTag.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/SetupDiGetDeviceRegistryPropertyEnum.cs (100%) create mode 100644 AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs create mode 100644 AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/SymbolicLinkTarget.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/SymbolicLinkType.cs (100%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device_EnumerateDevices.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs similarity index 80% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device_EnumerateDevices.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs index 29caec2e1..1efe1d062 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device_EnumerateDevices.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs @@ -28,34 +28,34 @@ namespace AlphaFS.UnitTest { public partial class AlphaFS_DeviceTest { + // Pattern: ___ + + [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"); - - Device_EnumerateDevices(false); - } - + Console.WriteLine("MSDN 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."); + UnitTestConstants.PrintUnitTestHeader(false); - private void Device_EnumerateDevices(bool isNetwork) - { - UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = UnitTestConstants.LocalHost; - var classCnt = 0; + var classCount = 0; foreach (var deviceClass in EnumMemberToList()) { - Console.WriteLine("\n#{0:000}\tClass: [{1}]", ++classCnt, deviceClass); + Console.WriteLine(); + Console.WriteLine("#{0:000}\tClass: [{1}]", ++classCount, deviceClass); + foreach (var device in Alphaleonis.Win32.Filesystem.Device.EnumerateDevices(tempPath, deviceClass)) + UnitTestConstants.Dump(device, -24); } - if (classCnt == 0) + + if (classCount == 0) Assert.Inconclusive("Nothing is enumerated, but it is expected."); } @@ -72,7 +72,7 @@ private static IEnumerable EnumMemberToList() var enumValArray = Enum.GetValues(enumType).Cast().OrderBy(e => e.ToString()).ToList(); var enumValList = new List(enumValArray.Count); - enumValList.AddRange(enumValArray.Select(val => (T) Enum.Parse(enumType, val.ToString()))); + enumValList.AddRange(enumValArray.Select(val => (T)Enum.Parse(enumType, val.ToString()))); return enumValList; } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs new file mode 100644 index 000000000..f9f8a6e76 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -0,0 +1,60 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_DeviceTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + + var driveCount = 0; + var drives = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDrives().ToList(); + + foreach (var drive in drives) + { + Console.WriteLine(); + Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]", ++driveCount, drive); + + UnitTestConstants.Dump(drive, -23); + + foreach (var volume in drive.Volumes) + UnitTestConstants.Dump(volume, -26, true); + + + Console.WriteLine(); + } + + + Assert.IsTrue(drives.Count > 0); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo_InitializeInstance.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo.InitializeInstance.cs similarity index 85% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo_InitializeInstance.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo.InitializeInstance.cs index 7222d21af..b16bea46c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo_InitializeInstance.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo.InitializeInstance.cs @@ -32,11 +32,7 @@ public partial class AlphaFS_DeviceTest [TestMethod] public void AlphaFS_DeviceInfo_InitializeInstance_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"); - DeviceInfo_InitializeInstance(false); - //DeviceInfo_InitializeInstance(true); } @@ -44,17 +40,21 @@ public void AlphaFS_DeviceInfo_InitializeInstance_Local_Success() private void DeviceInfo_InitializeInstance(bool isNetwork) { - UnitTestConstants.PrintUnitTestHeader(isNetwork); + Console.WriteLine("MSDN 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."); + + UnitTestConstants.PrintUnitTestHeader(false); + var deviceInfo = new Alphaleonis.Win32.Filesystem.DeviceInfo(isNetwork ? UnitTestConstants.LocalHost : string.Empty); UnitTestConstants.Dump(deviceInfo, -24); Assert.AreEqual(deviceInfo.HostName, UnitTestConstants.LocalHost); - Assert.AreEqual(deviceInfo.Class, null); + Assert.AreEqual(deviceInfo.DeviceClass, null); Assert.AreEqual(deviceInfo.ClassGuid, new Guid()); - + Console.WriteLine(); } } diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index a3a8abe1b..7cc3fc03d 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -149,6 +149,7 @@ + @@ -162,9 +163,9 @@ - + - + diff --git a/AlphaFS.UnitTest/_Utils/UnitTestConstants.cs b/AlphaFS.UnitTest/_Utils/UnitTestConstants.cs index 431088d92..d4d75b76e 100644 --- a/AlphaFS.UnitTest/_Utils/UnitTestConstants.cs +++ b/AlphaFS.UnitTest/_Utils/UnitTestConstants.cs @@ -42,12 +42,24 @@ public static partial class UnitTestConstants public const string EMspace = "\u3000"; #endif + /// The Computer name. public static readonly string LocalHost = Environment.MachineName; + + /// The User temp directory. For example "C:\Users\john\AppData\Local\Temp". public static readonly string TempFolder = Environment.GetEnvironmentVariable("Temp"); + + /// The Computer system drive. For example "C:". public static readonly string SysDrive = Environment.GetEnvironmentVariable("SystemDrive"); + + /// The Computer Windows directory. For example "C:\Windows". public static readonly string SysRoot = Environment.GetEnvironmentVariable("SystemRoot"); + + /// The Computer System32 directory. For example "C:\Windows\System32". public static readonly string SysRoot32 = System.IO.Path.Combine(SysRoot, "System32"); + + /// The User's app data directory. For example "C:\Users\john\AppData\Roaming". public static readonly string AppData = Environment.GetEnvironmentVariable("AppData"); + public static readonly string NotepadExe = System.IO.Path.Combine(SysRoot32, "notepad.exe"); public const string TextTrue = "IsTrue"; diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index a24adfae7..e7b8b541d 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -196,6 +196,19 @@ True + + + + + + + + + + + + + @@ -223,6 +236,7 @@ + @@ -298,13 +312,22 @@ + + + + + + + + + - - + + - + @@ -332,30 +355,30 @@ - - - - - - + + + + + + - + - - - + + + - - + + - + @@ -384,7 +407,7 @@ - + @@ -409,12 +432,12 @@ - + - + @@ -454,7 +477,7 @@ - + @@ -466,6 +489,8 @@ + + @@ -528,9 +553,9 @@ - + - + Code @@ -587,7 +612,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.Compression.cs b/AlphaFS/Device/Device.Compression.cs new file mode 100644 index 000000000..19348908b --- /dev/null +++ b/AlphaFS/Device/Device.Compression.cs @@ -0,0 +1,44 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace Alphaleonis.Win32.Filesystem +{ + /// Provides static methods to retrieve device resource information from a local or remote host. + public static partial class Device + { + /// [AlphaFS] Sets the NTFS compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. + /// The transaction. + /// A path that describes a folder or file to compress or decompress. + /// = compress, = decompress + /// Indicates the format of the path parameter(s). + [SecurityCritical] + internal static void ToggleCompressionCore(KernelTransaction transaction, string path, bool compress, PathFormat pathFormat) + { + using (var safeHandle = File.CreateFileCore(transaction, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.Modify, FileShare.None, true, false, pathFormat)) + + using (InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.FSCTL_SET_COMPRESSION, compress ? 1 : 0, path)) { } + } + } +} diff --git a/AlphaFS/Device/Device.DeviceEnumeration.cs b/AlphaFS/Device/Device.DeviceEnumeration.cs new file mode 100644 index 000000000..30a7b3d51 --- /dev/null +++ b/AlphaFS/Device/Device.DeviceEnumeration.cs @@ -0,0 +1,182 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Runtime.InteropServices; +using System.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + /// [AlphaFS] Enumerates all available devices on the local host. + /// instances of type from the local host. + /// One of the devices. + [SecurityCritical] + public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) + { + return EnumerateDevicesCore(null, null, deviceGuid); + } + + + /// [AlphaFS] Enumerates all available devices of type on the local or remote host. + /// instances of type for the specified . + /// The name of the local or remote host on which the device resides. refers to the local host. + /// One of the devices. + [SecurityCritical] + public static IEnumerable EnumerateDevices(string hostName, DeviceGuid deviceGuid) + { + return EnumerateDevicesCore(null, hostName, deviceGuid); + } + + + /// [AlphaFS] Enumerates all available devices on the local or remote host. + [SecurityCritical] + internal static IEnumerable EnumerateDevicesCore(SafeHandle safeHandle, string hostName, DeviceGuid interfaceGuid, bool getAllProperties = true) + { + SafeCmConnectMachineHandle safeMachineHandle; + var callerHandle = safeHandle != null; + var deviceGuid = new Guid(Utils.GetEnumDescription(interfaceGuid)); + + + // 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 + + + var lastError = NativeMethods.CM_Connect_Machine(Host.GetUncName(hostName), out safeMachineHandle); + + NativeMethods.IsValidHandle(safeMachineHandle, lastError); + + + using (safeMachineHandle) + { + // Start at the "Root" of the device tree of the specified machine. + + if (!callerHandle) + safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref deviceGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.SetupDiGetClassDevsExFlags.Present | NativeMethods.SetupDiGetClassDevsExFlags.DeviceInterface, IntPtr.Zero, hostName, IntPtr.Zero); + + + try + { + uint memberInterfaceIndex = 0; + var interfaceStructSize = Marshal.SizeOf(typeof(NativeMethods.SP_DEVICE_INTERFACE_DATA)); + var dataStructSize = Marshal.SizeOf(typeof(NativeMethods.SP_DEVINFO_DATA)); + + + // Start enumerating device interfaces. + + do + { + NativeMethods.IsValidHandle(safeHandle, Marshal.GetLastWin32Error()); + + + var interfaceData = new NativeMethods.SP_DEVICE_INTERFACE_DATA { cbSize = (uint)interfaceStructSize }; + + var success = NativeMethods.SetupDiEnumDeviceInterfaces(safeHandle, IntPtr.Zero, ref deviceGuid, 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 = (uint)dataStructSize }; + + var deviceInfo = new DeviceInfo(hostName) + { + ClassGuid = deviceGuid, + DevicePath = GetInterfaceDetails(safeHandle, ref interfaceData, ref diData).DevicePath + }; + + + if (getAllProperties) + { + SetDeviceProperties(safeHandle, deviceInfo, diData); + + deviceInfo.InstanceID = GetDeviceInstanceID(safeMachineHandle, hostName, diData); + } + + else + SetMinimalDeviceProperties(safeHandle, deviceInfo, diData); + + + yield return deviceInfo; + + } while (true); + } + finally + { + // Handle is ours, dispose. + if (!callerHandle && null != safeHandle && !safeHandle.IsClosed) + safeHandle.Close(); + } + } + } + + + [SecurityCritical] + private static string GetDeviceInstanceID(SafeCmConnectMachineHandle safeMachineHandle, string hostName, NativeMethods.SP_DEVINFO_DATA diData) + { + // CM_Get_Parent_Ex() + // Note: Using this function to access remote machines is not supported + // beginning with Windows 8 and Windows Server 2012, as this functionality has been removed. + // http://msdn.microsoft.com/en-us/library/windows/hardware/ff538615%28v=vs.85%29.aspx + + + uint ptrPrevious; + + var lastError = NativeMethods.CM_Get_Parent_Ex(out ptrPrevious, diData.DevInst, 0, safeMachineHandle); + + if (lastError != Win32Errors.CR_SUCCESS) + NativeError.ThrowException(lastError, hostName); + + + // Now we get the InstanceID of the USB level device. + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize / 4)) + { + // CM_Get_Device_ID_Ex() + // Note: Using this function to access remote machines is not supported beginning with Windows 8 and Windows Server 2012, + // as this functionality has been removed. + // http://msdn.microsoft.com/en-us/library/windows/hardware/ff538411%28v=vs.85%29.aspx + + 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. + + return safeBuffer.PtrToStringUni(); + } + } + } +} diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs new file mode 100644 index 000000000..521665ff3 --- /dev/null +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs @@ -0,0 +1,40 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + /// [AlphaFS] Enumerates the drive names of all physical drives on the Computer. + /// An IEnumerable of type that represents the physical drives on the Computer. + [SecurityCritical] + public static IEnumerable EnumeratePhysicalDrives() + { + foreach (var deviceInfo in EnumerateDevicesCore(null, null, DeviceGuid.Disk, false)) + { + yield return GetPhysicalDriveInfoCore(null, deviceInfo); + } + } + } +} diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs new file mode 100644 index 000000000..4ac53dced --- /dev/null +++ b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs @@ -0,0 +1,204 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; +using System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + /// [AlphaFS] Gets the hardware information such as the serial number, Vendor ID, Product ID. + /// A instance that represents the physical drive on the Computer. + /// + /// + /// + /// + /// The drive letter, such as C, D. + [SecurityCritical] + public static PhysicalDriveInfo GetPhysicalDriveInfo(char driveLetter) + { + return GetPhysicalDriveInfoCore(driveLetter, null); + } + + + /// Gets the hardware information such as the serial number, Vendor ID, Product ID. + /// A instance that represents the physical drive on the Computer. + /// + /// + /// + /// + /// + /// + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] + [SecurityCritical] + internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, DeviceInfo deviceInfo) + { + // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes + // without accessing that file or device, even if GENERIC_READ access would have been denied. + // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + //const int dwDesiredAccess = 0; + + // Requires elevation for: TotalNumberOfBytes + const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; + + const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; + + + SafeFileHandle safeHandle = null; + NativeMethods.STORAGE_DEVICE_NUMBER? driveNumber = null; + + + if (driveLetter.HasValue) + driveNumber = GetPhysicalDriveNumberCore((char)driveLetter); + + else if (null != deviceInfo) + { + safeHandle = File.OpenPhysicalDrive(deviceInfo.DevicePath, desiredAccess); + + driveNumber = GetStorageDeviceDriveNumber(safeHandle, deviceInfo.DevicePath); + } + + + if (!driveNumber.HasValue) + return null; + + + var deviceNumber = driveNumber.Value; + var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, deviceNumber.DeviceNumber.ToString(CultureInfo.InvariantCulture)); + var exceptionPath = string.Format(CultureInfo.InvariantCulture, "Device number: {0}. Drive: {1}", deviceNumber.DeviceNumber.ToString(CultureInfo.InvariantCulture), physicalDrive); + + var info = new PhysicalDriveInfo + { + DeviceNumber = deviceNumber.DeviceNumber, + PartitionNumber = deviceNumber.PartitionNumber + }; + + + + try + { + GetVolumeDiskExtents(physicalDrive, desiredAccess); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + + + if (null == safeHandle) + safeHandle = File.OpenPhysicalDrive(physicalDrive, desiredAccess); + + + using (safeHandle) + { + uint bytesReturned; + + var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY + { + PropertyId = 0, // StorageDeviceProperty, from STORAGE_PROPERTY_ID enum. + QueryType = 0, // PropertyStandardQuery, from STORAGE_QUERY_TYPE enum + }; + + + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, physicalDrive, NativeMethods.DefaultFileBufferSize / 4)) + { + var storageDescriptor = safeBuffer.PtrToStructure(0); + + + info.BusType = (StorageBusType)storageDescriptor.BusType; + + info.IsRemovable = storageDescriptor.RemovableMedia; + + info.SupportsCommandQueueing = storageDescriptor.CommandQueueing; + + + info.VendorID = safeBuffer.PtrToStringAnsi((int)storageDescriptor.VendorIdOffset).Trim(); + + info.ProductRevision = safeBuffer.PtrToStringAnsi((int)storageDescriptor.ProductRevisionOffset).Trim(); + + + // "FriendlyName" usually contains the name as shown in Windows Explorer, so let's use that. + + info.Name = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.FriendlyName) + ? deviceInfo.FriendlyName + : safeBuffer.PtrToStringAnsi((int)storageDescriptor.ProductIdOffset).Trim(); + + + //info.InstanceID = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.InstanceID) + // ? deviceInfo.InstanceID + // : string.Empty; + + + long serial; + + if (long.TryParse(safeBuffer.PtrToStringAnsi((int)storageDescriptor.SerialNumberOffset).Trim(), out serial)) + info.SerialNumber = serial; + } + + + if (elevatedAccess) + { + long diskSize; + + var success = NativeMethods.DeviceIoControl5(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, IntPtr.Zero, 0, out diskSize, (uint)Marshal.SizeOf(typeof(long)), out bytesReturned, IntPtr.Zero); + + var lastError = Marshal.GetLastWin32Error(); + if (!success) + NativeError.ThrowException(lastError, exceptionPath); + + info.TotalSize = diskSize; + } + } + + + // "FriendlyName" usually contains the name as shown in Windows Explorer, so let's use that. + + if (null == deviceInfo) + SetDeviceFriendlyName(info); + + + return info; + } + + + [SecurityCritical] + private static void SetDeviceFriendlyName(PhysicalDriveInfo info) + { + //foreach (var deviceInfo in EnumerateDevicesCore(null, null, DeviceGuid.Disk)) + //{ + // if (null != deviceInfo.InstanceID && deviceInfo.InstanceID.Equals(info.InstanceID, StringComparison.OrdinalIgnoreCase)) + // { + // if (!Utils.IsNullOrWhiteSpace(deviceInfo.FriendlyName)) + // { + // info.Name = deviceInfo.FriendlyName; + // return; + // } + // } + //} + } + } +} diff --git a/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs b/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs new file mode 100644 index 000000000..def8a766e --- /dev/null +++ b/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs @@ -0,0 +1,81 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + /// [AlphaFS] Gets the physical drive number that is related to the logical drive. + /// The physical drive number that is related to the logical drive, or -1 when the logical drive is a mapped network drive or CDRom. + /// + /// + /// + /// + /// The logical drive letter, such as C, D. + [SecurityCritical] + public static int GetPhysicalDriveNumber(char driveLetter) + { + var info = GetPhysicalDriveInfoCore(driveLetter, null); + + return null != info ? info.DeviceNumber : -1; + } + + + + + /// Gets the physical drive number that is related to the logical drive. + /// The physical drive number that is related to the logical drive, or -1 when the logical drive is a mapped network drive or CDRom. + /// + /// + /// + /// + /// The logical drive letter, such as C, D. + [SecurityCritical] + internal static NativeMethods.STORAGE_DEVICE_NUMBER? GetPhysicalDriveNumberCore(char driveLetter) + { + if (!char.IsLetter(driveLetter)) + throw new ArgumentException(Resources.Argument_must_be_a_drive_letter_from_a_z, "driveLetter"); + + + // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes + // without accessing that file or device, even if GENERIC_READ access would have been denied. + // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + const int dwDesiredAccess = 0; + + // Requires elevation. + //const FileSystemRights dwDesiredAccess = FileSystemRights.Read | FileSystemRights.Write; + + //const bool elevatedAccess = (dwDesiredAccess & FileSystemRights.Read) != 0 && (dwDesiredAccess & FileSystemRights.Write) != 0; + + + var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", Path.LogicalDrivePrefix, driveLetter.ToString(), Path.VolumeSeparator); + + + using (var safeHandle = File.OpenPhysicalDrive(physicalDrive, dwDesiredAccess)) + + return GetStorageDeviceDriveNumber(safeHandle, physicalDrive); + } + } +} diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs new file mode 100644 index 000000000..372d2d1d5 --- /dev/null +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -0,0 +1,89 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; +using Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + /// + /// + /// + /// + /// + /// + [SecurityCritical] + public static void GetVolumeDiskExtents(string physicalDrive, FileSystemRights desiredAccess) + { + var structure = GetVolumeDiskExtentsCore(physicalDrive, desiredAccess); + + Console.WriteLine("{0}: DiskNumber {1} ExtentLength {2} StartingOffset {3}", physicalDrive, structure.Extents[0].DiskNumber, structure.Extents[0].ExtentLength, structure.Extents[0].StartingOffset); + } + + + /// + /// + /// + /// + /// + /// + /// + [SecurityCritical] + public static void GetVolumeDiskExtents(SafeFileHandle safeHandle, string physicalDrive, FileSystemRights desiredAccess) + { + + } + + + /// + /// + /// + /// + /// + /// + [SecurityCritical] + private static NativeMethods.VOLUME_DISK_EXTENTS GetVolumeDiskExtentsCore(string physicalDrive, FileSystemRights desiredAccess) + { + using (var safeHandle = File.OpenPhysicalDrive(physicalDrive, desiredAccess)) + + using (var safeBuffer = GetDeviceIoData3(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, physicalDrive, 32)) + { + var offset = 0; + + var structure = safeBuffer.PtrToStructure(0); + + safeBuffer.PtrToStructure(0); + + //for (var i = 0; i < structure.NumberOfDiskExtents; i += offset) + //{ + // structure.Extents[i] = new NativeMethods.DISK_EXTENT[structure.NumberOfDiskExtents]; + //} + + + return structure; + } + } + } +} diff --git a/AlphaFS/Device/Device.cs b/AlphaFS/Device/Device.cs index a2b1de7d9..e6e9a7eb2 100644 --- a/AlphaFS/Device/Device.cs +++ b/AlphaFS/Device/Device.cs @@ -19,502 +19,245 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Network; -using Microsoft.Win32.SafeHandles; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; +using System.Globalization; using System.Runtime.InteropServices; using System.Security; -using System.Security.AccessControl; -using System.Text; +using System.Threading; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { - /// Provides static methods to retrieve device resource information from a local or remote host. - public static class Device + /// [AlphaFS] Provides static methods to retrieve device resource information from a local or remote host. + public static partial class Device { - #region Enumerate Devices + /// MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384 + internal const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384; - /// [AlphaFS] Enumerates all available devices on the local host. - /// instances of type from the local host. - /// One of the devices. - [SecurityCritical] - public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) - { - return EnumerateDevicesCore(null, null, deviceGuid); - } + /// REPARSE_DATA_BUFFER_HEADER_SIZE = 8 + internal const int REPARSE_DATA_BUFFER_HEADER_SIZE = 8; - /// [AlphaFS] Enumerates all available devices of type on the local or remote host. - /// instances of type for the specified . - /// The name of the local or remote host on which the device resides. refers to the local host. - /// One of the devices. - [SecurityCritical] - public static IEnumerable EnumerateDevices(string hostName, DeviceGuid deviceGuid) - { - return EnumerateDevicesCore(null, hostName, deviceGuid); - } - - - /// [AlphaFS] Enumerates all available devices on the local or remote host. + /// Builds a Device Interface Detail Data structure. + /// An initialized NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA instance. [SecurityCritical] - internal static IEnumerable EnumerateDevicesCore(SafeHandle safeHandle, string hostName, DeviceGuid deviceInterfaceGuid) + private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetInterfaceDetails(SafeHandle safeHandle, ref NativeMethods.SP_DEVICE_INTERFACE_DATA interfaceData, ref NativeMethods.SP_DEVINFO_DATA infoData) { - var callerHandle = safeHandle != null; - var deviceGuid = new Guid(Utils.GetEnumDescription(deviceInterfaceGuid)); - - - // 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); - - if (safeMachineHandle != null && safeMachineHandle.IsInvalid) - { - safeMachineHandle.Close(); - NativeError.ThrowException(lastError, Resources.Handle_Is_Invalid); - } - - using (safeMachineHandle) + var didd = new NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA { - // Start at the "Root" of the device tree of the specified machine. - if (!callerHandle) - safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref deviceGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.SetupDiGetClassDevsExFlags.Present | NativeMethods.SetupDiGetClassDevsExFlags.DeviceInterface, IntPtr.Zero, hostName, IntPtr.Zero); - - NativeMethods.IsValidHandle(safeHandle, Marshal.GetLastWin32Error()); - - - try - { - uint memberInterfaceIndex = 0; - var deviceInterfaceData = CreateDeviceInterfaceDataInstance(); - - // Start enumerating Device Interfaces. - while (NativeMethods.SetupDiEnumDeviceInterfaces(safeHandle, IntPtr.Zero, ref deviceGuid, memberInterfaceIndex++, ref deviceInterfaceData)) - { - lastError = Marshal.GetLastWin32Error(); - if (lastError != Win32Errors.NO_ERROR) - NativeError.ThrowException(lastError, hostName); - - - var deviceInfoData = CreateDeviceInfoDataInstance(); - var deviceInterfaceDetailData = GetDeviceInterfaceDetailDataInstance(safeHandle, deviceInterfaceData, deviceInfoData); - - // Get device interace details. - var success = NativeMethods.SetupDiGetDeviceInterfaceDetail(safeHandle, ref deviceInterfaceData, ref deviceInterfaceDetailData, NativeMethods.DefaultFileBufferSize, IntPtr.Zero, ref deviceInfoData); - - lastError = Marshal.GetLastWin32Error(); - if (!success) - NativeError.ThrowException(lastError, hostName); - - - // Create DeviceInfo instance. - // Set DevicePath property of DeviceInfo instance. - var deviceInfo = new DeviceInfo(hostName) {DevicePath = deviceInterfaceDetailData.DevicePath}; - - - // Current InstanceId is at the "USBSTOR" level, so we - // need up "move up" one level to get to the "USB" level. - uint ptrPrevious; - - // CM_Get_Parent_Ex() - // Note: Using this function to access remote machines is not supported - // beginning with Windows 8 and Windows Server 2012, as this functionality has been removed. - // http://msdn.microsoft.com/en-us/library/windows/hardware/ff538615%28v=vs.85%29.aspx - - lastError = NativeMethods.CM_Get_Parent_Ex(out ptrPrevious, deviceInfoData.DevInst, 0, safeMachineHandle); - if (lastError != Win32Errors.CR_SUCCESS) - NativeError.ThrowException(lastError, hostName); - - - // Now we get the InstanceID of the USB level device. - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize)) - { - // CM_Get_Device_ID_Ex() - // Note: Using this function to access remote machines is not supported beginning with Windows 8 and Windows Server 2012, - // as this functionality has been removed. - // http://msdn.microsoft.com/en-us/library/windows/hardware/ff538411%28v=vs.85%29.aspx - - lastError = NativeMethods.CM_Get_Device_ID_Ex(deviceInfoData.DevInst, safeBuffer, (uint)safeBuffer.Capacity, 0, safeMachineHandle); - if (lastError != Win32Errors.CR_SUCCESS) - NativeError.ThrowException(lastError, hostName); - - // Add to instance. - deviceInfo.InstanceId = safeBuffer.PtrToStringUni(); - } - - #region Get Registry Properties - - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize)) - { - uint regType; - string dataString; - var safeBufferCapacity = (uint) safeBuffer.Capacity; - + cbSize = (uint)(IntPtr.Size == 4 ? 6 : 8) + }; - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.BaseContainerId, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - { - dataString = safeBuffer.PtrToStringUni(); - if (!Utils.IsNullOrWhiteSpace(dataString)) - deviceInfo.BaseContainerId = new Guid(dataString); - } - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.ClassGuid, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - { - dataString = safeBuffer.PtrToStringUni(); - if (!Utils.IsNullOrWhiteSpace(dataString)) - deviceInfo.ClassGuid = new Guid(dataString); - } + 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); - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.Class = safeBuffer.PtrToStringUni(); - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.CompatibleIds, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.CompatibleIds = safeBuffer.PtrToStringUni(); + return didd; + } - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceDescription, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.DeviceDescription = safeBuffer.PtrToStringUni(); - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Driver, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.Driver = safeBuffer.PtrToStringUni(); + [SecurityCritical] + private static NativeMethods.STORAGE_DEVICE_NUMBER GetStorageDeviceDriveNumber(SafeFileHandle safeHandle, string path) + { + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, path)) - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.EnumeratorName, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.EnumeratorName = safeBuffer.PtrToStringUni(); + return safeBuffer.PtrToStructure(0); + } - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.FriendlyName = safeBuffer.PtrToStringUni(); - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.HardwareId, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.HardwareId = safeBuffer.PtrToStringUni(); + [SecurityCritical] + private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum property) + { + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize / 4)) + { + uint regDataType; - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.LocationInformation, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.LocationInformation = safeBuffer.PtrToStringUni(); + var success = NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref infoData, property, out regDataType, safeBuffer, (uint)safeBuffer.Capacity, IntPtr.Zero); - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.LocationPaths, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.LocationPaths = safeBuffer.PtrToStringUni(); + var lastError = Marshal.GetLastWin32Error(); - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Manufacturer, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.Manufacturer = safeBuffer.PtrToStringUni(); - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.PhysicalDeviceObjectName, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.PhysicalDeviceObjectName = safeBuffer.PtrToStringUni(); + // MSDN: SetupDiGetDeviceRegistryProperty returns the ERROR_INVALID_DATA error code if the requested property + // does not exist for a device or if the property data is not valid. - if (NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref deviceInfoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Service, out regType, safeBuffer, safeBufferCapacity, IntPtr.Zero)) - deviceInfo.Service = safeBuffer.PtrToStringUni(); - } + if (!success) + { + if (lastError != Win32Errors.ERROR_INVALID_DATA) + NativeError.ThrowException(lastError); - #endregion // Get Registry Properties + return string.Empty; + } - yield return deviceInfo; - // Get new structure instance. - deviceInterfaceData = CreateDeviceInterfaceDataInstance(); - } - } - finally - { - // Handle is ours, dispose. - if (!callerHandle && null != safeHandle) - safeHandle.Close(); - } + return safeBuffer.PtrToStringUni(); } } - #region Private Helpers - - /// Builds a DeviceInfo Data structure. - /// An initialized NativeMethods.SP_DEVINFO_DATA instance. + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] - private static NativeMethods.SP_DEVINFO_DATA CreateDeviceInfoDataInstance() + internal static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string path, int size = -1) { - var did = new NativeMethods.SP_DEVINFO_DATA(); - did.cbSize = (uint)Marshal.SizeOf(did); - - return did; - } + NativeMethods.IsValidHandle(safeHandle); + //var nativeOverlapped = new NativeOverlapped(); + var bufferSize = size > -1 ? size : Marshal.SizeOf(typeof(T)); - /// Builds a Device Interface Data structure. - /// An initialized NativeMethods.SP_DEVICE_INTERFACE_DATA instance. - [SecurityCritical] - private static NativeMethods.SP_DEVICE_INTERFACE_DATA CreateDeviceInterfaceDataInstance() - { - var did = new NativeMethods.SP_DEVICE_INTERFACE_DATA(); - did.cbSize = (uint)Marshal.SizeOf(did); + while (true) + { + uint bytesReturned; - return did; - } + var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); + var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); - /// Builds a Device Interface Detail Data structure. - /// An initialized NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA instance. - [SecurityCritical] - private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetDeviceInterfaceDetailDataInstance(SafeHandle safeHandle, NativeMethods.SP_DEVICE_INTERFACE_DATA deviceInterfaceData, NativeMethods.SP_DEVINFO_DATA deviceInfoData) - { - // Build a Device Interface Detail Data structure. - var didd = new NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA - { - cbSize = (uint) (IntPtr.Size == 4 ? 6 : 8) - }; + var lastError = Marshal.GetLastWin32Error(); - // Get device interace details. - var success = NativeMethods.SetupDiGetDeviceInterfaceDetail(safeHandle, ref deviceInterfaceData, ref didd, NativeMethods.DefaultFileBufferSize, IntPtr.Zero, ref deviceInfoData); + if (success) + return safeBuffer; - var lastError = Marshal.GetLastWin32Error(); - if (!success) - NativeError.ThrowException(lastError); - return didd; + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, path); + } } - /// Repeatedly invokes InvokeIoControl with the specified input until enough memory has been allocated. + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] - private static void InvokeIoControlUnknownSize(SafeFileHandle handle, uint controlCode, T input, uint increment = 128) + internal static SafeGlobalMemoryBufferHandle GetDeviceIoData3(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string path, int size = -1) { - //byte[] output; - //uint bytesReturned; - var inputSize = (uint) Marshal.SizeOf(input); - var outputLength = increment; + NativeMethods.IsValidHandle(safeHandle); - do + //var nativeOverlapped = new NativeOverlapped(); + var bufferSize = size > -1 ? size : Marshal.SizeOf(typeof(T)); + + while (true) { - var output = new byte[outputLength]; uint bytesReturned; - var success = NativeMethods.DeviceIoControlUnknownSize(handle, controlCode, input, inputSize, output, outputLength, out bytesReturned, IntPtr.Zero); + var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - var lastError = Marshal.GetLastWin32Error(); - if (!success) - { - switch ((uint) lastError) - { - case Win32Errors.ERROR_MORE_DATA: - case Win32Errors.ERROR_INSUFFICIENT_BUFFER: - outputLength += increment; - break; - - default: - NativeError.ThrowException(lastError); - break; - } - } - else - break; - - } while (true); + var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); + var lastError = Marshal.GetLastWin32Error(); - // 2017-06-28: Disabled; results are currently not used. + if (success) + return safeBuffer; - //// Return the result. - //if (output.Length == bytesReturned) - // return output; - //var res = new byte[bytesReturned]; - //Array.Copy(output, res, bytesReturned); - //return res; + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, path); + } } - #endregion // Private Helpers - - - #endregion // Enumerate Devices - - - #region Compression - /// [AlphaFS] Sets the NTFS compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. - /// The transaction. - /// A path that describes a folder or file to compress or decompress. - /// = compress, = decompress - /// Indicates the format of the path parameter(s). [SecurityCritical] - internal static void ToggleCompressionCore(KernelTransaction transaction, string path, bool compress, PathFormat pathFormat) + private static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandle safeBuffer, int bufferSize, string path) { - using (var handle = File.CreateFileCore(transaction, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.Modify, FileShare.None, true, false, pathFormat)) + if (null != safeBuffer && !safeBuffer.IsClosed) + safeBuffer.Close(); - InvokeIoControlUnknownSize(handle, NativeMethods.FSCTL_SET_COMPRESSION, compress ? 1 : 0); - } - #endregion // Compression + switch ((uint)lastError) + { + case Win32Errors.ERROR_MORE_DATA: + case Win32Errors.ERROR_INSUFFICIENT_BUFFER: + bufferSize = 2 * bufferSize; + break; - #region Link + default: + NativeMethods.IsValidHandle(safeBuffer, lastError, string.Format(CultureInfo.InvariantCulture, "Buffer size: {0}. Path: {1}", bufferSize.ToString(CultureInfo.InvariantCulture), path)); + break; + } - /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). - 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 - }; + return bufferSize; + } - 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, + /// Invokes InvokeIoControl with the specified input and specified size. + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] + [SecurityCritical] + internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string path, int size = -1) + { + NativeMethods.IsValidHandle(safeHandle); - PathBuffer = new byte[NativeMethods.MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 16] // 16368 - }; - - targetDirBytes.CopyTo(reparseDataBuffer.PathBuffer, 0); + var bufferSize = size > -1 ? size : Marshal.SizeOf(anyObject); - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(reparseDataBuffer))) + while (true) { - 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); - } - } + var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); + var success = NativeMethods.DeviceIoControlAnyObject(safeHandle, controlCode, anyObject, (uint)bufferSize, safeBuffer, (uint)safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); - /// [AlphaFS] Deletes an NTFS directory junction. - 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 - }; + var lastError = Marshal.GetLastWin32Error(); - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(reparseDataBuffer))) - { - safeBuffer.StructureToPtr(reparseDataBuffer, false); + if (success) + return safeBuffer; - 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); + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, path); } } - - /// [AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system. - /// - /// + [SecurityCritical] - internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, string reparsePath) + private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) { - using (var safeBuffer = GetLinkTargetData(safeHandle, reparsePath)) - { - var header = safeBuffer.PtrToStructure(0); - - var marshalReparseBuffer = (int) Marshal.OffsetOf(typeof(NativeMethods.ReparseDataBufferHeader), "data"); + deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.BaseContainerId)); - var dataOffset = (int) (marshalReparseBuffer + (header.ReparseTag == ReparsePointTag.MountPoint - ? Marshal.OffsetOf(typeof(NativeMethods.MountPointReparseBuffer), "data") - : Marshal.OffsetOf(typeof(NativeMethods.SymbolicLinkReparseBuffer), "data")).ToInt64()); + deviceInfo.CompatibleIds = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.CompatibleIds); - var dataBuffer = new byte[NativeMethods.MAXIMUM_REPARSE_DATA_BUFFER_SIZE - dataOffset]; + deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class); + deviceInfo.DeviceDescription = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceDescription); - switch (header.ReparseTag) - { - // MountPoint can be a junction or mounted drive (mounted drive starts with "\??\Volume"). + //deviceInfo.DeviceType = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceType); - case ReparsePointTag.MountPoint: - var mountPoint = safeBuffer.PtrToStructure(marshalReparseBuffer); + deviceInfo.Driver = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Driver); - safeBuffer.CopyTo(dataOffset, dataBuffer); + deviceInfo.EnumeratorName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.EnumeratorName); - return new LinkTargetInfo( - Encoding.Unicode.GetString(dataBuffer, mountPoint.SubstituteNameOffset, mountPoint.SubstituteNameLength), - Encoding.Unicode.GetString(dataBuffer, mountPoint.PrintNameOffset, mountPoint.PrintNameLength)); + deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); + deviceInfo.HardwareId = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.HardwareId); - case ReparsePointTag.SymLink: - var symLink = safeBuffer.PtrToStructure(marshalReparseBuffer); + deviceInfo.LocationInformation = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.LocationInformation); - safeBuffer.CopyTo(dataOffset, dataBuffer); + deviceInfo.LocationPaths = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.LocationPaths); - return new SymbolicLinkTargetInfo( - Encoding.Unicode.GetString(dataBuffer, symLink.SubstituteNameOffset, symLink.SubstituteNameLength), - Encoding.Unicode.GetString(dataBuffer, symLink.PrintNameOffset, symLink.PrintNameLength), symLink.Flags); + deviceInfo.Manufacturer = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Manufacturer); + deviceInfo.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.PhysicalDeviceObjectName); - default: - throw new UnrecognizedReparsePointException(reparsePath); - } - } + deviceInfo.Service = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Service); } - /// [AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system. - /// - /// - [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) + private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) { - 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. + deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class); - if (safeBuffer.Capacity < bytesReturned) - safeBuffer.Close(); - break; - } + //deviceInfo.DeviceType = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceType); - if (lastError != Win32Errors.ERROR_SUCCESS) - NativeError.ThrowException(lastError, reparsePath); - } - - else - break; - } - - - return safeBuffer; + deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); } - #endregion // Link + + //private static uint IOCTL_STORAGE_QUERY_PROPERTY = CTL_CODE((uint) NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE, 0x500, 0,0); + //private static uint CTL_CODE(uint deviceType, uint function, uint method, uint access) + //{ + // return (deviceType << 16) | (access << 14) | (function << 2) | method; + //} } } diff --git a/AlphaFS/Device/DeviceInfo.cs b/AlphaFS/Device/DeviceInfo.cs index 367c7a480..1697f3056 100644 --- a/AlphaFS/Device/DeviceInfo.cs +++ b/AlphaFS/Device/DeviceInfo.cs @@ -22,19 +22,18 @@ using Alphaleonis.Win32.Network; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Security; -using System.Security.Permissions; namespace Alphaleonis.Win32.Filesystem { /// Provides access to information of a device, on a local or remote host. - [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)] [SerializableAttribute] [SecurityCritical] public sealed class DeviceInfo { #region Constructors - + /// Initializes a DeviceInfo class. [SecurityCritical] public DeviceInfo() @@ -63,7 +62,7 @@ public IEnumerable EnumerateDevices(DeviceGuid deviceGuid) { return Device.EnumerateDevicesCore(null, HostName, deviceGuid); } - + #endregion // Methods @@ -74,7 +73,7 @@ public IEnumerable EnumerateDevices(DeviceGuid deviceGuid) /// Represents the name of the device setup class that a device instance belongs to. - public string Class { get; internal set; } + public string DeviceClass { get; internal set; } /// Represents the of the device setup class that a device instance belongs to. @@ -93,6 +92,10 @@ public IEnumerable EnumerateDevices(DeviceGuid deviceGuid) public string DevicePath { get; internal set; } + ///// Represents the device type of a device instance. + //public string DeviceType { get; internal set; } + + /// Represents the registry entry name of the driver key for a device instance. public string Driver { get; internal set; } @@ -113,8 +116,9 @@ public IEnumerable EnumerateDevices(DeviceGuid deviceGuid) public string HostName { get; internal set; } - /// Gets the instance Id of the device. - public string InstanceId { get; internal set; } + /// Gets the instance ID of the device. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] + public string InstanceID { get; internal set; } /// Represents the bus-specific physical location of a device instance. @@ -129,7 +133,7 @@ public IEnumerable EnumerateDevices(DeviceGuid deviceGuid) public string Manufacturer { get; internal set; } - /// Encapsulates the physical device location information provided by a device's firmware to Windows. + /// Encapsulates the physical device location (PDO) information provided by a device's firmware to Windows. public string PhysicalDeviceObjectName { get; internal set; } diff --git a/AlphaFS/Device/DiskSpaceInfo.cs b/AlphaFS/Device/DiskSpaceInfo.cs index 95646b3e5..76945c489 100644 --- a/AlphaFS/Device/DiskSpaceInfo.cs +++ b/AlphaFS/Device/DiskSpaceInfo.cs @@ -65,7 +65,7 @@ public DiskSpaceInfo(string drivePath) DriveName = Path.AddTrailingDirectorySeparator(drivePath, false); } - + /// Initializes a DiskSpaceInfo instance. /// 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 /// gets both size- and disk cluster information. Get only disk cluster information, Get only size information. @@ -79,8 +79,8 @@ public DiskSpaceInfo(string drivePath, bool? spaceInfoType, bool refresh, bool c else { - _initGetSpaceInfo = (bool) !spaceInfoType; - _initGetClusterInfo = (bool) spaceInfoType; + _initGetSpaceInfo = (bool)!spaceInfoType; + _initGetClusterInfo = (bool)spaceInfoType; } _continueOnAccessError = continueOnException; diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs new file mode 100644 index 000000000..88887f724 --- /dev/null +++ b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs @@ -0,0 +1,114 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + public sealed partial class DriveInfo + { + /// Enumerates the drive names of all logical drives on the Computer. + /// An IEnumerable of type that represents the logical drives on the Computer. + /// Retrieve logical drives as known by the Environment. + /// Retrieve only when accessible (IsReady) logical drives. + [SecurityCritical] + internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvironment, bool isReady) + { + // Get from Environment. + + if (fromEnvironment) + { + var drivesEnv = isReady + ? Environment.GetLogicalDrives().Where(ld => File.ExistsCore(null, true, ld, PathFormat.FullPath)) + : Environment.GetLogicalDrives().Select(ld => ld); + + foreach (var drive in drivesEnv) + { + // Optionally check Drive .IsReady. + if (isReady) + { + if (File.ExistsCore(null, true, drive, PathFormat.FullPath)) + yield return new DriveInfo(drive); + } + + else + yield return new DriveInfo(drive); + } + + yield break; + } + + + // Get through NativeMethod. + + var lastError = NativeMethods.GetLogicalDrives(); + + // MSDN: GetLogicalDrives(): If the function fails, the return value is zero. + if (lastError == Win32Errors.ERROR_SUCCESS) + NativeError.ThrowException(lastError); + + + var drives = lastError; + var count = 0; + while (drives != 0) + { + if ((drives & 1) != 0) + ++count; + + drives >>= 1; + } + + var result = new string[count]; + char[] root = { 'A', Path.VolumeSeparatorChar }; + + drives = lastError; + count = 0; + + while (drives != 0) + { + if ((drives & 1) != 0) + { + var drive = new string(root); + + if (isReady) + { + // Optionally check Drive .IsReady property. + if (File.ExistsCore(null, true, drive, PathFormat.FullPath)) + yield return new DriveInfo(drive); + } + else + { + // Ready or not. + yield return new DriveInfo(drive); + } + + result[count++] = drive; + } + + drives >>= 1; + root[0]++; + } + } + } +} diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs new file mode 100644 index 000000000..019127990 --- /dev/null +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs @@ -0,0 +1,139 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.IO; +using System.Linq; +using System.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + public sealed partial class DriveInfo + { + /// Retrieves information about the file system and volume associated with the specified root file or directorystream. + [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; + + case 3: + // DriveType + return null == _volumeInfo ? (object)string.Empty : _volumeInfo.DriveType; + } + + break; + + + // Volume related. + case 1: + if (mode == 0) + { + // DosDeviceName + return _dosDeviceName ?? (_dosDeviceName = Volume.QueryDosDevice(_name).FirstOrDefault()); + } + + break; + + #endregion // Volume + + + #region Drive + + // Drive related. + case 2: + if (mode == 0) + { + // RootDirectory + return _rootDirectory ?? (_rootDirectory = new DirectoryInfo(null, _name, PathFormat.RelativePath)); + } + + break; + + + // DiskSpaceInfo related. + case 3: + if (mode == 0) + { + // AvailableFreeSpace, TotalFreeSpace, TotalSize, DiskSpaceInfo + if (!_initDsie) + { + _dsi.Refresh(); + _initDsie = true; + } + } + + break; + + #endregion // Drive + + + #region Physical Drive + + // Physical Drive related. + case 4: + if (mode == 0) + { + return IsUnc + ? null + : (_physicalDriveInfo ?? (_physicalDriveInfo = Device.GetPhysicalDriveInfoCore(_name[0], null))); + } + + return null; + + #endregion // Physical Drive + } + //} + //catch + //{ + //} + + return type == 0 && mode > 0 ? string.Empty : null; + } + } +} diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs new file mode 100644 index 000000000..eb992855e --- /dev/null +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs @@ -0,0 +1,59 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 sealed partial class DriveInfo + { + /// [AlphaFS] Gets the first available drive letter on the local system. + /// A drive letter as . When no drive letters are available, an exception is thrown. + /// The letters "A" and "B" are reserved for floppy drives and will never be returned by this function. + public static char GetFreeDriveLetter() + { + return GetFreeDriveLetter(false); + } + + + /// [AlphaFS] Gets an available drive letter on the local system. + /// When get the last available drive letter. When gets the first available drive letter. + /// A drive letter as . When no drive letters are available, an exception is thrown. + /// The letters "A" and "B" are reserved for floppy drives and will never be returned by this function. + /// No drive letters available. + [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] + public static char GetFreeDriveLetter(bool getLastAvailable) + { + var freeDriveLetters = "CDEFGHIJKLMNOPQRSTUVWXYZ".Except(EnumerateLogicalDrivesCore(false, false).Select(d => d.Name[0])); + + try + { + return getLastAvailable ? freeDriveLetters.Last() : freeDriveLetters.First(); + } + catch + { + throw new ArgumentOutOfRangeException(Resources.No_Drive_Letters_Available); + } + } + } +} diff --git a/AlphaFS/Device/DriveInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.cs similarity index 59% rename from AlphaFS/Device/DriveInfo.cs rename to AlphaFS/Device/DriveInfo/DriveInfo.cs index 7b19e186d..c9176a258 100644 --- a/AlphaFS/Device/DriveInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.cs @@ -20,7 +20,6 @@ */ using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; @@ -36,19 +35,25 @@ namespace Alphaleonis.Win32.Filesystem /// [Serializable] [SecurityCritical] - public sealed class DriveInfo + public sealed partial class DriveInfo { + #region Private Fields + [NonSerialized] private readonly VolumeInfo _volumeInfo; [NonSerialized] private readonly DiskSpaceInfo _dsi; + [NonSerialized] private PhysicalDriveInfo _physicalDriveInfo; [NonSerialized] private bool _initDsie; - [NonSerialized] private DriveType? _driveType; + [NonSerialized] private readonly string _name; [NonSerialized] private string _dosDeviceName; [NonSerialized] private DirectoryInfo _rootDirectory; - [NonSerialized] private readonly string _name; + + #endregion // Private Fields #region Constructors + #region .NET + /// Provides access to information on the specified drive. /// /// @@ -73,18 +78,28 @@ public DriveInfo(string driveName) _name = Path.AddTrailingDirectorySeparator(driveName, false); - // Initiate VolumeInfo() lazyload instance. + + // Initiate VolumeInfo lazyload instance. _volumeInfo = new VolumeInfo(_name, false, true); - // Initiate DiskSpaceInfo() lazyload instance. + + // Initiate DiskSpaceInfo lazyload instance. _dsi = new DiskSpaceInfo(_name, null, false, true); + + + // Initiate PhysicalDriveInfo lazyload instance. + _physicalDriveInfo = null; } + #endregion // .NET + #endregion // Constructors #region Properties + #region .NET + /// Indicates the amount of available free space on a drive. /// The amount of free space available on the drive, in bytes. /// This property indicates the amount of free space available on the drive. Note that this number may be different from the number because this property takes into account disk quotas. @@ -93,15 +108,17 @@ public long AvailableFreeSpace get { GetDeviceInfo(3, 0); + return null == _dsi ? 0 : _dsi.FreeBytesAvailable; } } + /// Gets the name of the file system, such as NTFS or FAT32. /// Use DriveFormat to determine what formatting a drive uses. public string DriveFormat { - get { return (string) GetDeviceInfo(0, 1); } + get { return (string)GetDeviceInfo(0, 1); } } @@ -113,7 +130,7 @@ public string DriveFormat /// public DriveType DriveType { - get { return (DriveType) GetDeviceInfo(2, 0); } + get { return (DriveType)GetDeviceInfo(0, 3); } } @@ -130,7 +147,7 @@ public DriveType DriveType /// public bool IsReady { - get { return File.ExistsCore(null, true, Name, PathFormat.LongFullPath); } + get { return File.ExistsCore(null, true, _name, PathFormat.LongFullPath); } } @@ -147,9 +164,10 @@ public string Name /// A DirectoryInfo object that contains the root directory of the drive. public DirectoryInfo RootDirectory { - get { return (DirectoryInfo) GetDeviceInfo(2, 1); } + get { return (DirectoryInfo)GetDeviceInfo(2, 0); } } + /// Gets the total amount of free space available on a drive. /// The total free space available on a drive, in bytes. /// This property indicates the total amount of free space available on the drive, not just what is available to the current user. @@ -158,6 +176,7 @@ public long TotalFreeSpace get { GetDeviceInfo(3, 0); + return null == _dsi ? 0 : _dsi.TotalNumberOfFreeBytes; } } @@ -171,6 +190,7 @@ public long TotalSize get { GetDeviceInfo(3, 0); + return null == _dsi ? 0 : _dsi.TotalNumberOfBytes; } } @@ -184,16 +204,21 @@ public long TotalSize /// public string VolumeLabel { - get { return (string) GetDeviceInfo(0, 2); } - set { Volume.SetVolumeLabel(Name, value); } + get { return (string)GetDeviceInfo(0, 2); } + + set { Volume.SetVolumeLabel(_name, value); } } + #endregion // .NET + + /// [AlphaFS] Returns the instance. public DiskSpaceInfo DiskSpaceInfo { get { GetDeviceInfo(3, 0); + return _dsi; } } @@ -202,14 +227,17 @@ public DiskSpaceInfo DiskSpaceInfo /// [AlphaFS] The MS-DOS device name. public string DosDeviceName { - get { return (string) GetDeviceInfo(1, 0); } + get { return (string)GetDeviceInfo(1, 0); } } /// [AlphaFS] Indicates if this drive is a SUBST.EXE / DefineDosDevice drive mapping. public bool IsDosDeviceSubstitute { - get { return !Utils.IsNullOrWhiteSpace(DosDeviceName) && DosDeviceName.StartsWith(Path.NonInterpretedPathPrefix, StringComparison.OrdinalIgnoreCase); } + get + { + return !Utils.IsNullOrWhiteSpace(DosDeviceName) && DosDeviceName.StartsWith(Path.NonInterpretedPathPrefix, StringComparison.OrdinalIgnoreCase); + } } @@ -219,9 +247,9 @@ 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); + _name.StartsWith(Path.UncPrefix, StringComparison.Ordinal) && DriveType == DriveType.NoRootDirectory && DriveFormat.Equals(DriveType.Unknown.ToString(), StringComparison.OrdinalIgnoreCase); } } @@ -233,14 +261,21 @@ public bool IsVolume } - /// [AlphaFS] Contains information about a file-system volume. - /// A VolumeInfo object that contains file-system volume information of the drive. - public VolumeInfo VolumeInfo + /// [AlphaFS] Contains information about the physical drive. + /// A object that contains information of the physical drive. + public PhysicalDriveInfo PhysicalDriveInfo { - get { return (VolumeInfo) GetDeviceInfo(0, 0); } + get { return (PhysicalDriveInfo)GetDeviceInfo(4, 0); } } + /// [AlphaFS] Contains information about a file system volume. + /// A object that contains file system volume information of the drive. + public VolumeInfo VolumeInfo + { + get { return (VolumeInfo)GetDeviceInfo(0, 0); } + } + #endregion // Properties @@ -253,7 +288,7 @@ public VolumeInfo VolumeInfo [SecurityCritical] public static DriveInfo[] GetDrives() { - return Directory.EnumerateLogicalDrivesCore(false, false).ToArray(); + return EnumerateLogicalDrivesCore(false, false).ToArray(); } @@ -268,147 +303,16 @@ public override string ToString() #endregion // .NET - /// [AlphaFS] Enumerates the drive names of all logical drives on the Computer. - /// Retrieve logical drives as known by the Environment. - /// Retrieve only when accessible (IsReady) logical drives. - /// - /// An IEnumerable of type that represents - /// the logical drives on the Computer. - /// - [SecurityCritical] - public static IEnumerable EnumerateDrives(bool fromEnvironment, bool isReady) - { - return Directory.EnumerateLogicalDrivesCore(fromEnvironment, isReady); - } - - - /// [AlphaFS] Gets the first available drive letter on the local system. - /// A drive letter as . When no drive letters are available, an exception is thrown. - /// The letters "A" and "B" are reserved for floppy drives and will never be returned by this function. - public static char GetFreeDriveLetter() + /// [AlphaFS] Refreshes the state of the object. + public void Refresh() { - return GetFreeDriveLetter(false); - } + _physicalDriveInfo = null; + _volumeInfo.Refresh(); - /// Gets an available drive letter on the local system. - /// When get the last available drive letter. When gets the first available drive letter. - /// A drive letter as . When no drive letters are available, an exception is thrown. - /// The letters "A" and "B" are reserved for floppy drives and will never be returned by this function. - /// No drive letters available. - [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); - } + _dsi.Refresh(); } #endregion // Methods - - - #region Private Methods - - /// Retrieves information about the file system and volume associated with the specified root file or directorystream. - [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.QueryDosDevice(Name).FirstOrDefault()); - } - - 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 } } diff --git a/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs b/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs new file mode 100644 index 000000000..f1a33086f --- /dev/null +++ b/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs @@ -0,0 +1,80 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Runtime.InteropServices; +using System.Text; + +namespace Alphaleonis.Win32.Filesystem +{ + /// Provides static methods to retrieve device resource information from a local or remote host. + public static partial class Device + { + /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). + 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[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 success = NativeMethods.DeviceIoControl2(safeHandle, NativeMethods.IoControlCode.FSCTL_SET_REPARSE_POINT, safeBuffer, (uint)(targetDirBytes.Length + 20), IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); + + var lastError = Marshal.GetLastWin32Error(); + if (!success) + NativeError.ThrowException(lastError, directoryPath); + } + } + } +} diff --git a/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs b/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs new file mode 100644 index 000000000..07bbfbb38 --- /dev/null +++ b/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs @@ -0,0 +1,55 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Runtime.InteropServices; + +namespace Alphaleonis.Win32.Filesystem +{ + /// Provides static methods to retrieve device resource information from a local or remote host. + public static partial class Device + { + /// [AlphaFS] Deletes an NTFS directory junction. + internal static void DeleteDirectoryJunction(SafeFileHandle safeHandle) + { + var reparseDataBuffer = new NativeMethods.REPARSE_DATA_BUFFER + { + ReparseTag = ReparsePointTag.MountPoint, + ReparseDataLength = 0, + PathBuffer = new byte[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.IoControlCode.FSCTL_DELETE_REPARSE_POINT, safeBuffer, REPARSE_DATA_BUFFER_HEADER_SIZE, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); + + var lastError = Marshal.GetLastWin32Error(); + if (!success) + NativeError.ThrowException(lastError); + } + } + } +} diff --git a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs new file mode 100644 index 000000000..b8e39cc2c --- /dev/null +++ b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs @@ -0,0 +1,126 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Provides static methods to retrieve device resource information from a local or remote host. + public static partial class Device + { + /// [AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system. + /// + /// + [SecurityCritical] + internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, string reparsePath) + { + using (var safeBuffer = GetLinkTargetData(safeHandle, reparsePath)) + { + var header = safeBuffer.PtrToStructure(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[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(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(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); + } + } + } + + + /// [AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system. + /// + /// + [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(MAXIMUM_REPARSE_DATA_BUFFER_SIZE); + + while (true) + { + uint bytesReturned; + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.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; + } + + if (lastError != Win32Errors.ERROR_SUCCESS) + NativeError.ThrowException(lastError, reparsePath); + } + + else + break; + } + + + return safeBuffer; + } + } +} diff --git a/AlphaFS/Device/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo.cs new file mode 100644 index 000000000..e4fb0875b --- /dev/null +++ b/AlphaFS/Device/PhysicalDriveInfo.cs @@ -0,0 +1,120 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; +using System.Linq; +using System.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + /// Provides access to information of a physical drive. + [Serializable] + [SecurityCritical] + public sealed class PhysicalDriveInfo + { + [NonSerialized] private string _productID; + [NonSerialized] private string _vendorID; + [NonSerialized] private IEnumerable _volumes; + + + /// Initializes a PhysicalDriveInfo instance. + public PhysicalDriveInfo() + { + SerialNumber = -1; + TotalSize = -1; + } + + + /// Returns the product ID of the physical drive. + /// A string that represents this instance. + public override string ToString() + { + return !Utils.IsNullOrWhiteSpace(Name) ? Name : BusType.ToString(); + } + + + /// The bus type of the physical drive. + public StorageBusType BusType { get; internal set; } + + + /// The index number of the physical drive. + public int DeviceNumber { get; internal set; } + + + /// Indicates the partition number of the device is returned in this member, if the device can be partitioned. Otherwise, -1 is returned. + public int PartitionNumber { get; internal set; } + + + /// Indicates if the physical drive supports multiple outstanding commands (SCSI tagged queuing or equivalent). When false the physical drive does not support SCSI-tagged queuing or the equivalent. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Queueing")] + public bool SupportsCommandQueueing { get; internal set; } + + + /// Indicates if the physical drive is removable. When true the physical drive's media (if any) is removable. If the device has no media, this member should be ignored. When false the physical drive's media is not removable. + public bool IsRemovable { get; internal set; } + + + /// Returns the product ID or, when not available, the direct disk access (RAW I/O) path of the physical drive. + public string Name + { + get { return !Utils.IsNullOrWhiteSpace(_productID) ? _productID : Path.PhysicalDrivePrefix + DeviceNumber.ToString(CultureInfo.InvariantCulture); } + + internal set { _productID = value; } + } + + + /// The product revision of the physical drive. + public string ProductRevision { get; internal set; } + + + /// Gets the serial number of the physical drive. If the physical drive has no serial number, this member is -1. + public long SerialNumber { get; internal set; } + + + /// The total size of the physical drive. If the session is not elevated, this member is -1. + public long TotalSize { get; internal set; } + + + /// The Vendor ID of the physical drive. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] + public string VendorID + { + get { return !Utils.IsNullOrWhiteSpace(_vendorID) ? _vendorID : string.Empty; } + + internal set + { + // SanDisk X400 M.2 2280 256GB reports VendorID as: "(" + + _vendorID = null != value && value.Length > 1 ? value : string.Empty; + } + } + + + /// The Volumes located on the physical drive. + public IEnumerable Volumes + { + get { return _volumes ?? (_volumes = Volume.EnumerateVolumes()); } + } + } +} diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs index 4b16f1fd8..be595a13c 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs @@ -33,26 +33,26 @@ public static partial class Volume /// An enumerable collection of containing the path names for the specified volume. /// /// - /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. + /// A volume path: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". [SecurityCritical] public static IEnumerable 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); - + var requiredLength = 50; + var buffer = new StringBuilder(requiredLength); - uint requiredLength = 10; - var cBuffer = new char[requiredLength]; + volumeGuid = Path.AddTrailingDirectorySeparator(volumeGuid, false); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) - while (!NativeMethods.GetVolumePathNamesForVolumeName(volName, cBuffer, (uint)cBuffer.Length, out requiredLength)) + while (!NativeMethods.GetVolumePathNamesForVolumeName(volumeGuid, buffer, (uint)buffer.Capacity, out requiredLength)) { var lastError = Marshal.GetLastWin32Error(); @@ -60,7 +60,7 @@ public static IEnumerable EnumerateVolumePathNames(string volumeGuid) { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: - cBuffer = new char[requiredLength]; + buffer = new StringBuilder(requiredLength); break; default: @@ -69,21 +69,7 @@ public static IEnumerable EnumerateVolumePathNames(string volumeGuid) } } - - 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; - } - } - } + yield return buffer.ToString(); } } } diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs index 26f5e92d5..6e988e02a 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; @@ -30,22 +29,22 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { - /// [AlphaFS] Returns an enumerable collection of volumes on the computer. - /// An enumerable collection of volume names on the computer. + /// [AlphaFS] Returns an enumerable collection of volumes on the computer. + /// An enumerable collection of volume names on the computer. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public static IEnumerable EnumerateVolumes() { - var buffer = new StringBuilder(NativeMethods.MaxPathUnicode); + var buffer = new StringBuilder(50); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) using (var handle = NativeMethods.FindFirstVolume(buffer, (uint)buffer.Capacity)) { var lastError = Marshal.GetLastWin32Error(); - var throwException = lastError != Win32Errors.ERROR_NO_MORE_FILES && lastError != Win32Errors.ERROR_PATH_NOT_FOUND; + var throwException = lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_NO_MORE_FILES && lastError != Win32Errors.ERROR_MORE_DATA; - if (!NativeMethods.IsValidHandle(handle, lastError, String.Empty, throwException)) + if (!NativeMethods.IsValidHandle(handle, lastError, string.Empty, throwException)) yield break; yield return buffer.ToString(); @@ -55,9 +54,9 @@ public static IEnumerable EnumerateVolumes() { lastError = Marshal.GetLastWin32Error(); - throwException = lastError != Win32Errors.ERROR_NO_MORE_FILES && lastError != Win32Errors.ERROR_PATH_NOT_FOUND && lastError != Win32Errors.ERROR_MORE_DATA; + throwException = lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_NO_MORE_FILES && lastError != Win32Errors.ERROR_MORE_DATA; - if (!NativeMethods.IsValidHandle(handle, lastError, String.Empty, throwException)) + if (!NativeMethods.IsValidHandle(handle, lastError, string.Empty, throwException)) yield break; yield return buffer.ToString(); diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs index 677276e33..3168b432c 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs @@ -53,7 +53,7 @@ public static string GetVolumeDeviceName(string volumeName) return volumeName.Substring(Path.GlobalRootPrefix.Length); - + // Volume @@ -68,8 +68,14 @@ public static string GetVolumeDeviceName(string volumeName) // Logical Drive + // Check for Logical Drives: C:, D:, ... else - doQueryDos = Path.IsLogicalDriveCore(volumeName, PathFormat.LongFullPath); + { + // Don't use char.IsLetter() here as that can be misleading. + // The only valid drive letters are: a-z and A-Z. + var c = volumeName[0]; + doQueryDos = volumeName[1] == Path.VolumeSeparatorChar && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'); + } if (doQueryDos) diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs index 1d4c2eecb..ae2acfb17 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs @@ -30,7 +30,7 @@ public static partial class Volume { /// [AlphaFS] Gets the shortest display name for the specified . /// This method basically returns the shortest string returned by - /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. + /// A volume path: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// /// The shortest display name for the specified volume found, or if no display names were found. /// @@ -49,8 +49,10 @@ public static string GetVolumeDisplayName(string volumeName) { } + var result = smallestMountPoint[0][0] == Path.WildcardStarMatchAllChar ? null : smallestMountPoint[0]; - return Utils.IsNullOrWhiteSpace(result) ? null : result; + + return !Utils.IsNullOrWhiteSpace(result) ? result : null; } } } diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs b/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs index ed3eee4b3..0a24df8fe 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs @@ -29,66 +29,67 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { - /// [AlphaFS] - /// Retrieves a volume path for the volume that is associated with the specified volume mount point (drive letter, - /// volume GUID path, or mounted folder). - /// - /// - /// - /// The path of a mounted folder (for example, "Y:\MountX\") or a drive letter (for example, "X:\"). - /// + /// [AlphaFS] Retrieves a volume path for the volume that is associated with the specified volume mount point (drive letter, volume GUID path, or mounted folder). /// The unique volume name of the form: "\\?\Volume{GUID}\". - [SuppressMessage("Microsoft.Interoperability", "CA1404:CallGetLastErrorImmediatelyAfterPInvoke", Justification = "Marshal.GetLastWin32Error() is manipulated.")] + /// SMB does not support volume management functions. + /// Mount points aren't supported by ReFS volumes. + /// + /// The path of a mounted folder (for example, "Y:\MountX\") or a drive letter (for example, "X:\"). + [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, volumeMountPoint, GetFullPathOptions.AsLongPath | GetFullPathOptions.AddTrailingDirectorySeparator | GetFullPathOptions.FullCheck); + var volumeGuid = new StringBuilder(100); var uniqueName = new StringBuilder(100); + bool success = false; + int lastError = 0; + - try + using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { - 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. + // NTFS Curiosities (part 2): Volumes, volume names and mount points: Are volume names really unique? + // https://blogs.msdn.microsoft.com/adioltean/2005/04/17/ntfs-curiosities-part-2-volumes-volume-names-and-mount-points/ + // + // Interesting read why one would call GetVolumeNameForVolumeMountPoint() twice: + // + // Bottom line is: if you have disk/volume migrations, then you can expect multiple volume names for the same volume. + // But whatever it happens, there is always a unique volume name for the current boot session. You can obtain this unique name by calling + // GetVolumeNameForVolumeMountPoint once on your root, get the volume name, and then call GetVolumeNameForVolumeMountPoint again. + // This will always return the unique volume name. - 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 + // GetVolumeNameForVolumeMountPoint() + // 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists. - : null; - } - } - finally - { - var lastError = (uint)Marshal.GetLastWin32Error(); + success = NativeMethods.GetVolumeNameForVolumeMountPoint(volumeMountPoint, volumeGuid, (uint)volumeGuid.Capacity); + + lastError = Marshal.GetLastWin32Error(); + + if (!success) + NativeError.ThrowException(lastError, volumeMountPoint); + + + // The string must end with a trailing backslash. + + success = NativeMethods.GetVolumeNameForVolumeMountPoint(Path.AddTrailingDirectorySeparator(volumeGuid.ToString(), false), uniqueName, (uint)uniqueName.Capacity); - switch (lastError) - { - case Win32Errors.ERROR_INVALID_NAME: - NativeError.ThrowException(lastError, volumeMountPoint); - break; + lastError = Marshal.GetLastWin32Error(); - case Win32Errors.ERROR_MORE_DATA: - // (1) When GetVolumeNameForVolumeMountPoint() succeeds, lastError is set to Win32Errors.ERROR_MORE_DATA. - break; + if (!success) + NativeError.ThrowException(lastError, volumeMountPoint); - 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; - } + return success ? uniqueName.ToString() : null; } } } diff --git a/AlphaFS/Device/Volume/VolumeInfo.cs b/AlphaFS/Device/Volume/VolumeInfo.cs index 630b01ba1..b15d4832f 100644 --- a/AlphaFS/Device/Volume/VolumeInfo.cs +++ b/AlphaFS/Device/Volume/VolumeInfo.cs @@ -22,6 +22,7 @@ using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; @@ -29,14 +30,20 @@ namespace Alphaleonis.Win32.Filesystem { /// Contains information about a filesystem Volume. - [SerializableAttribute] + [Serializable] [SecurityCritical] public sealed class VolumeInfo { + #region Private Fields + [NonSerialized] private readonly bool _continueOnAccessError; [NonSerialized] private readonly SafeFileHandle _volumeHandle; [NonSerialized] private NativeMethods.VOLUME_INFO_FLAGS _volumeInfoAttributes; + #endregion // Private Fields + + + #region Constructors /// Initializes a VolumeInfo instance. /// @@ -91,6 +98,8 @@ public VolumeInfo(string driveName, bool refresh, bool continueOnException) : th [SecurityCritical] public VolumeInfo(SafeFileHandle volumeHandle) { + NativeMethods.IsValidHandle(volumeHandle); + _volumeHandle = volumeHandle; } @@ -108,75 +117,7 @@ public VolumeInfo(SafeFileHandle volumeHandle, bool refresh, bool continueOnExce Refresh(); } - - - - /// Refreshes the state of the object. - 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; - } + #endregion // Constructors /// Returns the full path of the volume. @@ -187,7 +128,7 @@ public override string ToString() } - + #region Properties /// The specified volume supports preserved case of file names when it places a name on disk. public bool CasePreservedNames @@ -217,6 +158,15 @@ public bool DirectAccess } + /// Gets the drive type. + /// One of the values. + /// + /// The DriveType property indicates whether a drive is any of: CDRom, Fixed, Unknown, Network, NoRootDirectory, + /// Ram, Removable, or Unknown. Values are listed in the enumeration. + /// + internal DriveType DriveType { get; private set; } + + /// Gets the name of the file system, for example, the FAT file system or the NTFS file system. /// The name of the file system. public string FileSystemName { get; private set; } @@ -232,10 +182,7 @@ public string Guid { get { - if (Utils.IsNullOrWhiteSpace(_guid)) - _guid = !Utils.IsNullOrWhiteSpace(FullPath) ? Volume.GetUniqueVolumeNameForPath(FullPath) : null; - - return _guid; + return _guid ?? (_guid = !Utils.IsNullOrWhiteSpace(FullPath) ? Volume.GetUniqueVolumeNameForPath(FullPath) : null); } } @@ -265,14 +212,14 @@ public bool PersistentAcls get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_PERSISTENT_ACLS) != 0; } } - + /// The specified volume is read-only. public bool ReadOnlyVolume { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_READ_ONLY_VOLUME) != 0; } } - + /// The specified volume supports a single sequential write. public bool SequentialWriteOnce { @@ -375,5 +322,77 @@ public bool VolumeQuotas { get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_VOLUME_QUOTAS) != 0; } } + + #endregion // Properties + + + #region Methods + + /// Refreshes the state of the object. + 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)) + { + 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) + break; + + + 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; + } + + } 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; + + DriveType = Volume.GetDriveType(FullPath); + } + + #endregion // Methods } } diff --git a/AlphaFS/Filesystem/File Class/File.Create.cs b/AlphaFS/Filesystem/File Class/File.Create.cs index 3ac06ebf4..4b5c65435 100644 --- a/AlphaFS/Filesystem/File Class/File.Create.cs +++ b/AlphaFS/Filesystem/File Class/File.Create.cs @@ -64,7 +64,7 @@ public static FileStream Create(string path, int bufferSize) [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); + return CreateFileStreamCore(null, path, (ExtendedFileAttributes)options, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } @@ -262,7 +262,7 @@ internal static FileStream CreateFileStreamCore(KernelTransaction transaction, s try { - safeHandle = CreateFileCore(transaction, path, attributes, fileSecurity, mode, (FileSystemRights) access, share, true, false, pathFormat); + safeHandle = CreateFileCore(transaction, path, attributes, fileSecurity, mode, (FileSystemRights)access, share, true, false, pathFormat); return new FileStream(safeHandle, access, bufferSize, (attributes & ExtendedFileAttributes.Overlapped) != 0); } @@ -326,10 +326,10 @@ internal static SafeFileHandle CreateFileCore(KernelTransaction transaction, str if (null != fileSecurity) - fileSystemRights |= (FileSystemRights) SecurityInformation.UnprotectedSacl; + fileSystemRights |= (FileSystemRights)SecurityInformation.UnprotectedSacl; - using ((fileSystemRights & (FileSystemRights) SecurityInformation.UnprotectedSacl) != 0 || (fileSystemRights & (FileSystemRights) SecurityInformation.UnprotectedDacl) != 0 ? new PrivilegeEnabler(Privilege.Security) : null) + using ((fileSystemRights & (FileSystemRights)SecurityInformation.UnprotectedSacl) != 0 || (fileSystemRights & (FileSystemRights)SecurityInformation.UnprotectedDacl) != 0 ? new PrivilegeEnabler(Privilege.Security) : null) using (var securityAttributes = new Security.NativeMethods.SecurityAttributes(fileSecurity)) { var safeHandle = transaction == null || !NativeMethods.IsAtLeastWindowsVista diff --git a/AlphaFS/Filesystem/File Class/File.OpenPhysicalDrive.cs b/AlphaFS/Filesystem/File Class/File.OpenPhysicalDrive.cs new file mode 100644 index 000000000..3d334ef60 --- /dev/null +++ b/AlphaFS/Filesystem/File Class/File.OpenPhysicalDrive.cs @@ -0,0 +1,49 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Win32.SafeHandles; +using System.IO; +using System.Security; +using System.Security.AccessControl; + +namespace Alphaleonis.Win32.Filesystem +{ + partial class File + { + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + [SecurityCritical] + public static SafeFileHandle OpenPhysicalDrive(string path, FileSystemRights fileSystemRights) + { + return CreateFileCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Open, fileSystemRights, FileShare.ReadWrite, false, false, PathFormat.LongFullPath); + } + } +} diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs index 4950ab325..3f2a27347 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs @@ -68,31 +68,6 @@ internal static partial class NativeMethods /// Invalid FileAttributes = -1 - internal const FileAttributes InvalidFileAttributes = (FileAttributes) (-1); - - - - - /// MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384 - internal const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384; - - /// REPARSE_DATA_BUFFER_HEADER_SIZE = 8 - internal const int REPARSE_DATA_BUFFER_HEADER_SIZE = 8; - - - private const int DeviceIoControlMethodBuffered = 0; - private const int DeviceIoControlFileDeviceFileSystem = 9; - - // Command to compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. - internal const int FSCTL_SET_COMPRESSION = (DeviceIoControlFileDeviceFileSystem << 16) | (16 << 2) | DeviceIoControlMethodBuffered | (int) (FileAccess.Read | FileAccess.Write) << 14; - - // Command to set the reparse point data block. - internal const int FSCTL_SET_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (41 << 2) | DeviceIoControlMethodBuffered | (0 << 14); - - /// Command to delete the reparse point data base. - internal const int FSCTL_DELETE_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (43 << 2) | DeviceIoControlMethodBuffered | (0 << 14); - - /// Command to get the reparse point data block. - internal const int FSCTL_GET_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (42 << 2) | DeviceIoControlMethodBuffered | (0 << 14); + internal const FileAttributes InvalidFileAttributes = (FileAttributes)(-1); } } diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs index fb54fb59e..1563f1db9 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs @@ -19,11 +19,12 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; +using System.Threading; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { @@ -114,6 +115,7 @@ internal static partial class NativeMethods #endregion // CM_Xxx + #region DeviceIoControl /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. @@ -139,60 +141,44 @@ internal static partial class NativeMethods [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 DeviceIoControl(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] uint dwIoControlCode, IntPtr lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); + internal static extern bool DeviceIoControl(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, IntPtr lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); + - /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. - /// - /// If the operation completes successfully, the return value is nonzero. - /// If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError. - /// - /// - /// To retrieve a handle to the device, you must call the function with either the name of a device or - /// the name of the driver associated with a device. - /// To specify a device name, use the following format: \\.\DeviceName - /// Minimum supported client: Windows XP - /// Minimum supported server: Windows Server 2003 - /// - /// The device. - /// The i/o control code. - /// Buffer for in data. - /// Size of the in buffer. - /// Buffer for out data. - /// Size of the out buffer. - /// [out] The bytes returned. - /// The overlapped. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl2(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] uint dwIoControlCode, SafeGlobalMemoryBufferHandle lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, IntPtr lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); + internal static extern bool DeviceIoControlAnyObject(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, [MarshalAs(UnmanagedType.AsAny)] object lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); - /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. - /// - /// If the operation completes successfully, the return value is nonzero. - /// If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError. - /// - /// - /// To retrieve a handle to the device, you must call the function with either the name of a device or - /// the name of the driver associated with a device. - /// To specify a device name, use the following format: \\.\DeviceName - /// Minimum supported client: Windows XP - /// Minimum supported server: Windows Server 2003 - /// - /// The device. - /// The i/o control code. - /// Buffer for in data. - /// Size of the in buffer. - /// Buffer for out data. - /// Size of the out buffer. - /// [out] The bytes returned. - /// The overlapped. + + [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool DeviceIoControl2(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, SafeGlobalMemoryBufferHandle lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, IntPtr lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); + + + [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool DeviceIoControl3(SafeFileHandle hDevice, IoControlCode dwIoControlCode, IntPtr lpInBuffer, + int nInBufferSize, + SafeGlobalMemoryBufferHandle lpOutBuffer, + int nOutBufferSize, + out int lpBytesReturned, + IntPtr lpOverlapped); + + //internal static extern bool DeviceIoControl3(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, IntPtr lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); + + + + // Get size of a specified disk. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControlUnknownSize(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] uint dwIoControlCode, [MarshalAs(UnmanagedType.AsAny)] object lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, [MarshalAs(UnmanagedType.AsAny)] [Out] object lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); + internal static extern bool DeviceIoControl5(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, IntPtr lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, out long lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); #endregion // DeviceIoControl + #region SetupDiXxx /// diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.EncryptedFileRaw.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.EncryptedFileRaw.cs index 55dcc5bf4..3663fbc00 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.EncryptedFileRaw.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.EncryptedFileRaw.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs index 85d482050..ebf7a0553 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs @@ -734,7 +734,7 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnmapViewOfFile(SafeLocalMemoryBufferHandle lpBaseAddress); - + /// Enumerates the first stream with a ::$DATA stream type in the specified file or directory. /// /// If the function succeeds, the return value is a search handle that can be used in subsequent calls to the function. @@ -872,7 +872,7 @@ internal struct RM_PROCESS_INFO [DllImport("rstrtmgr.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] internal static extern int RmStartSession([MarshalAs(UnmanagedType.U4)] out uint pSessionHandle, [MarshalAs(UnmanagedType.I4)] int dwSessionFlags, [MarshalAs(UnmanagedType.LPWStr)] string strSessionKey); - + #endregion // Restart Manager } } diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs index 16785fc08..978016776 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs @@ -32,34 +32,34 @@ internal static partial class NativeMethods { internal static uint GetHighOrderDword(long highPart) { - return (uint) ((highPart >> 32) & 0xFFFFFFFF); + return (uint)((highPart >> 32) & 0xFFFFFFFF); } internal static uint GetLowOrderDword(long lowPart) { - return (uint) (lowPart & 0xFFFFFFFF); + return (uint)(lowPart & 0xFFFFFFFF); } internal static long LuidToLong(Luid luid) { - var high = (ulong) luid.HighPart << 32; - var low = (ulong) luid.LowPart & 0x00000000FFFFFFFF; + var high = (ulong)luid.HighPart << 32; + var low = (ulong)luid.LowPart & 0x00000000FFFFFFFF; - return unchecked((long) (high | low)); + return unchecked((long)(high | low)); } internal static Luid LongToLuid(long lluid) { - return new Luid {HighPart = (uint) (lluid >> 32), LowPart = (uint) (lluid & 0xFFFFFFFF)}; + 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); + return ((long)highPart << 32) | ((long)lowPart & 0xFFFFFFFF); } @@ -72,7 +72,7 @@ internal static bool IsValidHandle(SafeHandle handle, bool throwException = true { if (null == handle || handle.IsClosed || handle.IsInvalid) { - if (null != handle) + if (null != handle && !handle.IsClosed) handle.Close(); if (throwException) @@ -95,11 +95,11 @@ internal static bool IsValidHandle(SafeHandle handle, int lastError, bool throwE { if (null == handle || handle.IsClosed || handle.IsInvalid) { - if (null != handle) + if (null != handle && !handle.IsClosed) handle.Close(); if (throwException) - throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Handle_Is_Invalid_Win32Error, lastError), "handle"); + throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Handle_Is_Invalid_Win32Error, lastError.ToString(CultureInfo.InvariantCulture)), "handle"); return false; } @@ -112,7 +112,7 @@ internal static bool IsValidHandle(SafeHandle handle, int lastError, bool throwE /// The current handle to check. /// The result of Marshal.GetLastWin32Error() /// The path on which the Exception occurred. - /// will throw an , will not raise this exception.. + /// will throw an Exception, will not raise this exception.. /// on success, otherwise. /// /// @@ -120,7 +120,7 @@ internal static bool IsValidHandle(SafeHandle handle, int lastError, string path { if (null == handle || handle.IsClosed || handle.IsInvalid) { - if (null != handle) + if (null != handle && !handle.IsClosed) handle.Close(); if (throwException) diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs index e5e4749b2..cc8664ca9 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs @@ -30,12 +30,13 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods - { + { /// Defines, redefines, or deletes MS-DOS device names. /// /// 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. /// + /// SMB does not support volume management functions. For CsvFs, a new name will not be replicated to the other nodes on the cluster. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] @@ -43,11 +44,13 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DefineDosDevice(DosDeviceAttributes dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, [MarshalAs(UnmanagedType.LPWStr)] string lpTargetPath); + /// Deletes a drive letter or mounted folder. /// /// 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. /// + /// SMB does not support volume management functions. For CsvFs, a new mount point will not be replicated to the other nodes on the cluster. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] @@ -55,33 +58,39 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeleteVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint); + /// Retrieves the name of a volume on a computer. FindFirstVolume is used to begin scanning the volumes of a computer. /// /// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolume and FindVolumeClose functions. /// If the function fails to find any volumes, the return value is the INVALID_HANDLE_VALUE error code. To get extended error information, call GetLastError. /// + /// SMB does not support volume management functions. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstVolumeW"), SuppressUnmanagedCodeSecurity] internal static extern SafeFindVolumeHandle FindFirstVolume(StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); + /// Retrieves the name of a mounted folder on the specified volume. FindFirstVolumeMountPoint is used to begin scanning the mounted folders on a volume. /// /// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolumeMountPoint and FindVolumeMountPointClose functions. /// If the function fails to find a mounted folder on the volume, the return value is the INVALID_HANDLE_VALUE error code. /// + /// SMB does not support volume management functions. CsvFS does not support adding mount point on a CSV volume. ReFS does not index mount points. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstVolumeMountPointW"), SuppressUnmanagedCodeSecurity] internal static extern SafeFindVolumeMountPointHandle FindFirstVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszRootPathName, StringBuilder lpszVolumeMountPoint, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); + /// Continues a volume search started by a call to the FindFirstVolume function. FindNextVolume finds one volume per call. /// /// 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. /// + /// SMB does not support volume management functions. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] @@ -89,68 +98,72 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FindNextVolume(SafeFindVolumeHandle hFindVolume, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); + /// Continues a mounted folder search started by a call to the FindFirstVolumeMountPoint function. FindNextVolumeMountPoint finds one mounted folder per call. /// /// 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. If no more mounted folders can be found, the GetLastError function returns the ERROR_NO_MORE_FILES error code. + /// If the function fails, the return value is zero. To get extended error information, call GetLastError. + /// If no more mounted folders can be found, the GetLastError function returns the ERROR_NO_MORE_FILES error code. /// In that case, close the search with the FindVolumeMountPointClose function. /// - /// Minimum supported client: Windows XP - /// Minimum supported server: Windows Server 2003 + /// SMB does not support volume management functions. CsvFS does not support adding mount point on a CSV volume. ReFS does not index mount points. + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindNextVolumeMountPointW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FindNextVolumeMountPoint(SafeFindVolumeMountPointHandle hFindVolume, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); - /// Closes the specified volume search handle. - /// - /// SetLastError is set to . - /// Minimum supported client: Windows XP [desktop apps only]. Minimum supported server: Windows Server 2003 [desktop apps only]. - /// + + /// Closes the specified volume search handle. The FindFirstVolume and FindNextVolume functions use this search handle to locate volumes. /// - /// 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. + /// 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. /// + /// SMB does not support volume management functions. + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] [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 FindVolumeClose(IntPtr hFindVolume); + /// Closes the specified mounted folder search handle. - /// - /// SetLastError is set to . - /// Minimum supported client: Windows XP - /// Minimum supported server: Windows Server 2003 - /// /// /// 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. /// + /// SMB does not support volume management functions. CsvFS does not support adding mount point on a CSV volume. + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] [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 FindVolumeMountPointClose(IntPtr hFindVolume); + /// /// Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive. /// To determine whether a drive is a USB-type drive, call and specify the /// SPDRP_REMOVAL_POLICY property. /// + /// + /// The return value specifies the type of drive, see . + /// If the function fails, the return value is zero. To get extended error information, call GetLastError. + /// /// /// SMB does not support volume management functions. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// /// Full pathname of the root file. - /// - /// The return value specifies the type of drive, see . - /// If the function fails, the return value is zero. To get extended error information, call GetLastError. - /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetDriveTypeW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.U4)] internal static extern DriveType GetDriveType([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName); + /// /// Retrieves a bitmask representing the currently available disk drives. /// @@ -169,6 +182,7 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetLogicalDrives(); + /// Retrieves information about the file system and volume associated with the specified root directory. /// /// If all the requested information is retrieved, the return value is nonzero. @@ -182,6 +196,7 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumeInformation([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, [MarshalAs(UnmanagedType.U4)] out VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); + /// Retrieves information about the file system and volume associated with the specified file. /// /// If all the requested information is retrieved, the return value is nonzero. @@ -196,6 +211,7 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumeInformationByHandle(SafeFileHandle hFile, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, out VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); + /// Retrieves a volume GUID path for the volume that is associated with the specified volume mount point (drive letter, volume GUID path, or mounted folder). /// /// If the function succeeds, the return value is nonzero. @@ -211,6 +227,7 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumeNameForVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); + /// Retrieves the volume mount point where the specified path is mounted. /// /// If a specified path is passed, GetVolumePathName returns the path to the volume mount point, which means that it returns the @@ -232,6 +249,7 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumePathName([MarshalAs(UnmanagedType.LPWStr)] string lpszFileName, StringBuilder lpszVolumePathName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); + /// Retrieves a list of drive letters and mounted folder paths for the specified volume. /// Minimum supported client: Windows XP. /// Minimum supported server: Windows Server 2003. @@ -242,7 +260,8 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumePathNamesForVolumeNameW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool GetVolumePathNamesForVolumeName([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName, char[] lpszVolumePathNames, [MarshalAs(UnmanagedType.U4)] uint cchBuferLength, [MarshalAs(UnmanagedType.U4)] out uint lpcchReturnLength); + internal static extern bool GetVolumePathNamesForVolumeName([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName, StringBuilder lpszVolumePathNames, [MarshalAs(UnmanagedType.U4)] uint cchBuferLength, [MarshalAs(UnmanagedType.U4)] out int lpcchReturnLength); + /// Sets the label of a file system volume. /// Minimum supported client: Windows XP [desktop apps only]. @@ -257,6 +276,7 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetVolumeLabel([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, [MarshalAs(UnmanagedType.LPWStr)] string lpVolumeName); + /// Associates a volume with a drive letter or a directory on another volume. /// Minimum supported client: Windows XP [desktop apps only]. /// Minimum supported server: Windows Server 2003 [desktop apps only]. @@ -269,6 +289,7 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint, [MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName); + /// Retrieves information about MS-DOS device names. /// Minimum supported client: Windows XP [desktop apps only]. /// Minimum supported server: Windows Server 2003 [desktop apps only]. @@ -282,4 +303,4 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.U4)] internal static extern uint QueryDosDevice([MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, char[] lpTargetPath, [MarshalAs(UnmanagedType.U4)] uint ucchMax); } -} \ No newline at end of file +} diff --git a/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs b/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs new file mode 100644 index 000000000..252e331e6 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs @@ -0,0 +1,43 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// Represents a disk extent. + /// MSDN: http://msdn.microsoft.com/en-us/library/aa363968(v=vs.85).aspx + [StructLayout(LayoutKind.Sequential)] + internal struct DISK_EXTENT + { + /// The number of the disk that contains this extent. This is the same number that is used to construct the name of the disk, for example, the X in "\\?\PhysicalDriveX" or "\\?\HarddiskX". + public int DiskNumber; + + /// The offset from the beginning of the disk to the extent, in bytes. + public long StartingOffset; + + /// The number of bytes in this extent. + public long ExtentLength; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/IoControlCode.cs b/AlphaFS/Filesystem/Native Other/IoControlCode.cs new file mode 100644 index 000000000..cf1252d5b --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/IoControlCode.cs @@ -0,0 +1,700 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + internal static partial class NativeMethods + { + /// Enumerable values that enter into DeviceIoControl function as dwIoControlCode parameter + /// Some of the code was taken from: http://blogs.msdn.com/b/codedebate/archive/2007/12/18/6797175.aspx + [Flags] + internal enum IoControlCode : uint + { + // VIDEO + //VideoQuerySupportedBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0125 << 2) | IoMethod.Buffered | (0 << 14), + //VideoQueryDisplayBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0126 << 2) | IoMethod.Buffered | (0 << 14), + //VideoSetDisplayBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0127 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Retrieves the physical location of a specified volume on one or more disks. + IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Return properties of a storage device or adapter. The request indicates the kind of information to retrieve, such as inquiry data for a device or capabilities and limitations of an adapter. + IOCTL_STORAGE_QUERY_PROPERTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x500 << 2) | IoMethod.Buffered | (0 << 14), + + + + + #region FILE_DEVICE_MASS_STORAGE + + /// Determines whether the media has changed on a removable-media device that the caller has opened for read or write access. If read or write access to the device is not necessary, the caller can improve performance by opening the device with FILE_READ_ATTRIBUTES and issuing anIOCTL_STORAGE_CHECK_VERIFY2 request instead. + IOCTL_STORAGE_CHECK_VERIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0200 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Determines whether the media has changed on a removable-media device - the caller has opened with FILE_READ_ATTRIBUTES. Because no file system is mounted when a device is opened in this way, this request can be processed much more quickly than an IOCTL_STORAGE_CHECK_VERIFY request. + IOCTL_STORAGE_CHECK_VERIFY2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0200 << 2) | IoMethod.Buffered | (0 << 14), // FileAccess.Any + + + /// Locks the device to prevent removal of the media. If the driver can prevent the media from being removed while the drive is in use, it disables or enables the mechanism that ejects media on a device - the caller has opened for read or write access. + IOCTL_STORAGE_MEDIA_REMOVAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0201 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Causes the device to eject the media if the device supports ejection capabilities. + IOCTL_STORAGE_EJECT_MEDIA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0202 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Causes media to be loaded in a device that the caller has opened for read or write access. If read or write access to the device is not necessary, the caller can improve performance by opening the device with FILE_READ_ATTRIBUTES and issuing an IOCTL_STORAGE_LOAD_MEDIA2 request instead. + IOCTL_STORAGE_LOAD_MEDIA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0203 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Causes media to be loaded in a device that the caller has opened with FILE_READ_ATTRIBUTES. Because no file system is mounted when a device is opened in this way, this request can be processed much more quickly than an IOCTL_STORAGE_LOAD_MEDIA request. + IOCTL_STORAGE_LOAD_MEDIA2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0203 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Claims a device for the exclusive use of the caller on a bus that supports multiple initiators and the concept of reserving a device, such as a SCSI bus. + IOCTL_STORAGE_RESERVE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0204 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Releases a device previously reserved for the exclusive use of the caller on a bus that supports multiple initiators and the concept of reserving a device, such as a SCSI bus. + IOCTL_STORAGE_RELEASE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0205 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// + /// Determines whether another device that the driver supports has been connected to the I/O bus, either since the system was booted or since + /// the driver last processed this request. + /// This IOCTL is obsolete in the Plug and Play environment. Plug and Play class drivers handle this request by calling IoInvalidateDeviceRelations + /// with the device relations type BusRelations. If a new device is found, the class driver's AddDevice routine will be called. + /// Legacy class drivers can continue to handle this IOCTL without modifications. If a new device is found, the driver sets up any necessary + /// system objects and resources to handle I/O requests for its new device. It also initializes the device on receipt of this request + /// dynamically, that is, without requiring the machine to be rebooted. Such a driver is assumed to support devices connected on a dynamically + /// configurable I/O bus. + /// + IOCTL_STORAGE_FIND_NEW_DEVICES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0206 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// + /// Locks the device to prevent removal of the media. If the driver can prevent the media from being removed while the drive is in use, + /// the driver disables or enables the mechanism that ejects media, thereby locking the drive. A caller must open the device with + /// FILE_READ_ATTRIBUTES to send this request. + /// Unlike IOCTL_STORAGE_MEDIA_REMOVAL, the driver tracks IOCTL_STORAGE_EJECTION_CONTROL requests by caller and ignores unlock requests for + /// which it has not received a lock request from the same caller, thereby preventing other callers from unlocking the drive. + /// + IOCTL_STORAGE_EJECTION_CONTROL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0250 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// Temporarily enables or disables delivery of the custom PnP events GUID_IO_MEDIA_ARRIVAL and GUID_IO_MEDIA_REMOVAL on a removable-media device. + /// This, in turn, enables or disables media change detection (AutoPlay) for the device if the caller has opened the device with + /// FILE_READ_ATTRIBUTES access and if the device has AutoPlay enabled in the registry. The caller must not open the device for read or write + /// access or the IOCTL operation will fail. This IOCTL has no effect on the AutoPlay setting in the registry. + /// + IOCTL_STORAGE_MCN_CONTROL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0251 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Returns information about the geometry of floppy drives. + IOCTL_STORAGE_GET_MEDIA_TYPES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0300 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Returns information about the types of media supported by a device. A storage class driver must handle this IOCTL to control devices to be accessed by the removable storage manager (RSM) either as stand-alone devices or as data transfer elements (drives) in a media library or changer device. + IOCTL_STORAGE_GET_MEDIA_TYPES_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0301 << 2) | IoMethod.Buffered | (0 << 14), + + + ///// Resets an I/O bus and, indirectly, each device on the bus. Resetting the bus clears all device reservations and transfer speed settings, which must then be renegotiated, making it a time-consuming operation that should be used very rarely. The caller requires only read access to issue a bus reset. + //[Obsolete] + //IOCTL_STORAGE_RESET_BUS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0400 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + ///// If possible, resets a non-SCSI storage device without affecting other devices on the bus. Device reset for SCSI devices is not supported. The caller requires only read access to issue a device reset and, to comply, the device must be capable of responding to I/O requests. If the device reset succeeds, pending I/O requests are canceled. + //[Obsolete] + //IOCTL_STORAGE_RESET_DEVICE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0401 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Returns a STORAGE_DEVICE_NUMBER structure that contains the FILE_DEVICE_XXX type, device number, and, for a partitionable device, the partition number assigned to a device by the driver when the device is started. This request is usually issued by a fault-tolerant disk driver. + IOCTL_STORAGE_GET_DEVICE_NUMBER = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0420 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// Polls for a prediction of device failure. This request works with the IDE disk drives that support self-monitoring analysis and reporting technology (SMART). If the drive is a SCSI drive, the class driver attempts to verify if the SCSI disk supports the equivalent IDE SMART technology by check the inquiry information on the Information Exception Control Page, X3T10/94-190 Rev 4. + /// If the device supports prediction failure, the disk class driver queries the device for failure prediction status and reports the results. If the disk class driver assigns a nonzero value to the PredictFailure member of STORAGE_PREDICT_FAILURE in the output buffer at Irp->AssociatedIrp.SystemBuffer, the disk has bad sectors and is predicting a failure. The storage stack returns 512 bytes of vendor-specific information about the failure prediction in the VendorSpecific member of STORAGE_PREDICT_FAILURE. + /// If the PredictFailure member contains a value of zero, the disk is not predicting a failure. + /// + IOCTL_STORAGE_PREDICT_FAILURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0440 << 2) | IoMethod.Buffered | (0 << 14), + + #endregion // FILE_DEVICE_MASS_STORAGE + + + #region FILE_DEVICE_DISK + + + /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). + IOCTL_DISK_GET_DRIVE_GEOMETRY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0000 << 2) | IoMethod.Buffered | (0 << 14), + + /// + /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). + /// The difference between IOCTL_DISK_GET_DRIVE_GEOMETRY_EX and the older IOCTL_DISK_GET_DRIVE_GEOMETRY request is that + /// IOCTL_DISK_GET_DRIVE_GEOMETRY_EX can retrieve information from both Master Boot Record (MBR) and GUID Partition Table (GPT)-type + /// partitioned media, whereas IOCTL_DISK_GET_DRIVE_GEOMETRY can only read MBR-style media. + /// + IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0028 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Returns information about the type, size, and nature of a disk partition. (Floppy drivers need not handle this request.) + IOCTL_DISK_GET_PARTITION_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0001 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Changes the partition type of the specified disk partition. (Floppy drivers need not handle this request.) + IOCTL_DISK_SET_PARTITION_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0002 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Returns information about the number of partitions, disk signature, and features of each partition on a disk. (Floppy drivers need not handle this request.) + IOCTL_DISK_GET_DRIVE_LAYOUT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0003 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Contains extended information about a drive's partitions. + IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0014 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Repartitions a disk as specified. (Floppy drivers need not handle this request.) + IOCTL_DISK_SET_DRIVE_LAYOUT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0004 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Performs a logical format of a specified extent on a disk. + IOCTL_DISK_VERIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0005 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Formats the specified set of contiguous tracks on the disk. + IOCTL_DISK_FORMAT_TRACKS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0006 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Maps defective blocks to new location on disk. This request instructs the device to reassign the bad block address to a good block from its spare-block pool. + IOCTL_DISK_REASSIGN_BLOCKS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0007 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Increments a reference counter that enables the collection of disk performance statistics, such as the numbers of bytes read and written since the driver last processed this request, for a corresponding disk monitoring application. In Microsoft Windows 2000 this IOCTL is handled by the filter driver diskperf. In Windows XP and later operating systems, the partition manager handles this request for disks and ftdisk.sys and dmio.sys handle this request for volumes. + IOCTL_DISK_PERFORMANCE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0008 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Determines whether a disk is writable. + IOCTL_DISK_IS_WRITABLE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0009 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + DiskLogging = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x000a << 2) | IoMethod.Buffered | (0 << 14), + + + /// Is similar to IOCTL_DISK_FORMAT_TRACKS, except that it allows the caller to specify several more parameters. The additional extended parameters are the format gap length, the number of sectors per track, and an array whose element size is equal to the number of sectors per track. This array represents the track layout. + IOCTL_DISK_FORMAT_TRACKS_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x000b << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + ///// Do not use + //[Obsolete] + //IOCTL_DISK_HISTOGRAM_STRUCTURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000c << 2) | IoMethod.Buffered | (0 << 14), + + + ///// Do not use + //[Obsolete] + //IOCTL_DISK_HISTOGRAM_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000d << 2) | IoMethod.Buffered | (0 << 14), + + + ///// Do not use + //[Obsolete] + //IOCTL_DISK_HISTOGRAM_RESET = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000e << 2) | IoMethod.Buffered | (0 << 14), + + + ///// Do not use + //[Obsolete] + //IOCTL_DISK_REQUEST_STRUCTURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000f << 2) | IoMethod.Buffered | (0 << 14), + + ///// Do not use + //[Obsolete] + //IOCTL_DISK_REQUEST_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x0010 << 2) | IoMethod.Buffered | (0 << 14), + + + ///// Do not use + //[Obsolete] + //IOCTL_DISK_CONTROLLER_NUMBER = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x0011 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Retrieves the length of the specified disk, volume, or partition. + IOCTL_DISK_GET_LENGTH_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0017 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Returns version information, a capabilities mask, and a bitmask for the device. This IOCTL must be handled by drivers that support Self-Monitoring Analysis and Reporting Technology (SMART). + SMART_GET_VERSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0020 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// + /// Sends one of the following Self-Monitoring Analysis and Reporting Technology (SMART) commands to the device: + /// * Enable or disable reporting on the device + /// * Enable or disable autosaving of attributes + /// * Save current attributes now + /// * Execute offline diagnostics + /// * Get current SMART status + /// * Write to SMART log + /// This IOCTL must be handled by drivers that support SMART. + /// + SMART_SEND_DRIVE_COMMAND = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0021 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Returns the ATA-2 identify data, the Self-Monitoring Analysis and Reporting Technology (SMART) thresholds, or the SMART attributes for the device. This IOCTL must be handled by drivers that support SMART. + SMART_RCV_DRIVE_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0022 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Updates device extension with drive size information for current media. + IOCTL_DISK_UPDATE_DRIVE_SIZE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0032 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Increases the size of an existing partition. It is used in conjunction with IOCTL_DISK_UPDATE_DRIVE_SIZE to extend a disk, so that it will contain a new free space area, and then to extend an existing partition on the disk into the newly attached free space. It takes a DISK_GROW_PARTITION structure as the only parameter. For this operation to work, the space after the specified partition must be free. A partition cannot be extended over another existing partition. + IOCTL_DISK_GROW_PARTITION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0034 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Returns disk cache configuration data. + IOCTL_DISK_GET_CACHE_INFORMATION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0035 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Sets disk cache configuration data. + IOCTL_DISK_SET_CACHE_INFORMATION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0036 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Removes partition information from the disk. If the partition style of the disk is Master Boot Record (MBR), sector 0 of the disk is wiped clean except for the bootstrap code. All signatures, such as the AA55 boot signature and the NTFT disk signature, will be removed. If the partition style of the disk is GUID Partition Table (GPT), the primary partition table header in sector 1 and the backup partition table in the last sector of the disk are wiped clean. This operation can be used to generate so-called "superfloppies" that contain a file system starting at the first sector of the disk rather than in a partition on the disk. + IOCTL_DISK_DELETE_DRIVE_LAYOUT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0040 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// + DiskSenseDevice = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x00f8 << 2) | IoMethod.Buffered | (0 << 14), + + + /// In Microsoft Windows 2000 and later operating systems, this IOCTL is replaced by IOCTL_STORAGE_CHECK_VERIFY. The only difference between the two IOCTLs is the base value. + IOCTL_DISK_CHECK_VERIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0200 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// In Microsoft Windows 2000 and later operating systems, this IOCTL is replaced by IOCTL_STORAGE_FIND_NEW_DEVICES. The only difference between the two IOCTLs is the base value. + IOCTL_DISK_FIND_NEW_DEVICES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0206 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// In Microsoft Windows 2000 and later operating systems, this IOCTL is replaced by IOCTL_STORAGE_GET_MEDIA_TYPES. The only difference between the two IOCTLs is the base value. + IOCTL_DISK_GET_MEDIA_TYPES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0300 << 2) | IoMethod.Buffered | (0 << 14), + + #endregion // FILE_DEVICE_DISK + + + #region FILE_DEVICE_CHANGER + + /// Retrieves the parameters of the specified device. + IOCTL_CHANGER_GET_PARAMETERS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0000 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Retrieves the current status of the specified device. + IOCTL_CHANGER_GET_STATUS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0001 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Retrieves the product data for the specified device. + IOCTL_CHANGER_GET_PRODUCT_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0002 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Sets the state of the device's insert/eject port, door, or keypad. + IOCTL_CHANGER_SET_ACCESS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0004 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Retrieves the status of all elements or a specified number of elements of a particular type. + IOCTL_CHANGER_GET_ELEMENT_STATUS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0005 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Initializes the status of all elements or the specified elements of a particular type. + IOCTL_CHANGER_INITIALIZE_ELEMENT_STATUS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0006 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Sets the changer's robotic transport mechanism to the specified element address. This optimizes moving or exchanging media by positioning the transport beforehand. + IOCTL_CHANGER_SET_POSITION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0007 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Moves a piece of media from a source element to one destination, and the piece of media originally in the first destination to a second destination. + IOCTL_CHANGER_EXCHANGE_MEDIUM = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0008 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Moves a piece of media to a destination. + IOCTL_CHANGER_MOVE_MEDIUM = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0009 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Physically recalibrates a transport element. Recalibration may involve returning the transport to its home position. + IOCTL_CHANGER_REINITIALIZE_TRANSPORT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x000A << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// Retrieves the volume tag information for the specified elements. + IOCTL_CHANGER_QUERY_VOLUME_TAGS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x000B << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + #endregion // FILE_DEVICE_CHANGER + + + #region FILE_DEVICE_FILE_SYSTEM + + /// Requests a level 1 opportunistic lock on a file. + FSCTL_REQUEST_OPLOCK_LEVEL_1 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Requests a level 2 opportunistic lock on a file. + FSCTL_REQUEST_OPLOCK_LEVEL_2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (1 << 2) | IoMethod.Buffered | (0 << 14), + + /// Requests a batch opportunistic lock on a file. + FSCTL_REQUEST_BATCH_OPLOCK = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (2 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Responds to notification that an exclusive opportunistic lock on a file is about to be broken. Use this operation to indicate that the file should receive a level 2 opportunistic lock. + FSCTL_OPLOCK_BREAK_ACKNOWLEDGE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (3 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Notifies a server that a client application is ready to close a file. Use this operation after notification that an opportunistic lock on a file is ready to be broken. + FSCTL_OPBATCH_ACK_CLOSE_PENDING = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (4 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// Enables the calling application to wait for completion of an opportunistic lock break. + /// This operation is not useful to application developers and is documented here only for completeness. CreateFile handles the problem that this operation was designed to handle. + /// + FSCTL_OPLOCK_BREAK_NOTIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (5 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Locks a volume if it is not in use. A locked volume can be accessed only through handles to the file object (*hDevice) that locks the volume. For more information, see the Remarks section. + FSCTL_LOCK_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (6 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Unlocks a volume. + FSCTL_UNLOCK_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (7 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Dismounts a volume regardless of whether or not the volume is currently in use. For more information, see the Remarks section. + FSCTL_DISMOUNT_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (8 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Determines whether the specified volume is mounted, or if the specified file or directory is on a mounted volume. + FSCTL_IS_VOLUME_MOUNTED = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (10 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// The FSCTL_IS_PATHNAME_VALID control code performs static analysis of the supplied pathname and returns a status value that indicates + /// whether the pathname is well formed (for example, no illegal characters, acceptable path length, and so on). Because this analysis does + /// not consider the content of the volume, it sometimes gives "false positives." In other words, the analysis might indicate that the + /// pathname is well formed, even when it is not. Negative results are more reliable, but are not guaranteed to be correct. + /// This control code is not supported with fast FAT file systems, and it is not a meaningful operation in NTFS or UDFS. NTFS and UDFS support + /// such a wide variety of codesets that any string is potentially a valid pathname. + /// + FSCTL_IS_PATHNAME_VALID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (11 << 2) | IoMethod.Buffered | (0 << 14), + + + /// The FSCTL_MARK_VOLUME_DIRTY control code marks a specified volume as dirty, which triggers Autochk.exe to run on the volume during the next system restart. + FSCTL_MARK_VOLUME_DIRTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (12 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// The FSCTL_QUERY_RETRIEVAL_POINTERS control code retrieves a mapping between virtual cluster numbers (VCN, offsets within the file/stream + /// space) and logical cluster numbers (LCN, offsets within the volume space), starting at the beginning of the file up to the map size + /// specified in InputBuffer. + /// FSCTL_QUERY_RETRIEVAL_POINTERS is similar to FSCTL_GET_RETRIEVAL_POINTERS. However, FSCTL_QUERY_RETRIEVAL_POINTERS only works in kernel + /// mode on local paging files or the system hives. The paging file is guaranteed to have a one-to-one mapping from the VCN in a volume to the + /// LCN that refer more directly to the underlying physical storage. You must not use FSCTL_QUERY_RETRIEVAL_POINTERS with files other than + /// the page file, because they might reside on volumes, such as mirrored volumes, that have one-to-many mappings of VCNs to LCNs. + /// + FSCTL_QUERY_RETRIEVAL_POINTERS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (14 << 2) | IoMethod.Neither | (0 << 14), + + + /// Retrieves the current compression state of a file or directory on a volume whose file system supports per-stream compression. + FSCTL_GET_COMPRESSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (15 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Sets the compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. You can use FSCTL_SET_COMPRESSION to compress or uncompress a file or directory on such a volume. + FSCTL_SET_COMPRESSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (16 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// + /// The FSCTL_MARK_AS_SYSTEM_HIVE control code informs the file system that the specified file contains the registry's system hive. The file + /// system must flush system hive data to disk at just the right moment to avoid deadlocks and to ensure data integrity. Do not use this file + /// system control code with any file other than the file that contains the registry's system hive. This control code does not work with a + /// directory or volume handle. File system redirectors that access files on remote machines treat this control code as a no-op. + /// Only kernel-level components can use this filesystem control code. + /// + FSCTL_MARK_AS_SYSTEM_HIVE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (19 << 2) | IoMethod.Neither | (0 << 14), + + + /// + /// The FSCTL_OPLOCK_BREAK_ACK_NO_2 control code responds to notification that an exclusive (level 1, batch, or filter) opportunistic lock + /// (oplock) on a file has been broken. + /// A client application sends this control code to indicate that it acknowledges the oplock break and that, if the oplock is a level 1 oplock + /// that was broken to level 2, it does not want the level 2 oplock. + /// To process this control code, a minifilter calls FltOplockFsctrl with the following parameters. A file system or legacy filter driver + /// calls FsRtlOplockFsctrl. + /// For more information about opportunistic locking and about the FSCTL_OPLOCK_BREAK_ACK_NO_2 control code, see the Microsoft Windows SDK + /// documentation. + /// + FSCTL_OPLOCK_BREAK_ACK_NO_2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (20 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// The FSCTL_INVALIDATE_VOLUMES control code finds and removes all the volumes mounted on the device represented by the specified file object + /// or handle. + /// To perform this operation, minifilter drivers call FltFsControlFile, and file systems, redirectors, and legacy file system filter drivers + /// call ZwFsControlFile, using the following parameters. + /// + FSCTL_INVALIDATE_VOLUMES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (21 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + FSCTL_QUERY_FAT_BPB = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (22 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// The FSCTL_REQUEST_FILTER_OPLOCK control code requests a filter opportunistic lock (oplock) on a file. + /// To process this control code, a minifilter calls FltOplockFsctrl with the following parameters. A file system or legacy filter driver + /// calls FsRtlOplockFsctrl. + /// For more information about opportunistic locking and about the FSCTL_REQUEST_FILTER_OPLOCK control code, see the Microsoft Windows SDK + /// documentation. + /// + FSCTL_REQUEST_FILTER_OPLOCK = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (23 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Retrieves the information from various file system performance counters. + FSCTL_FILESYSTEM_GET_STATISTICS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (24 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Retrieves information about the specified NTFS file system volume. + FSCTL_GET_NTFS_VOLUME_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (25 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Retrieves the first file record that is in use and is of a lesser than or equal ordinal value to the requested file reference number. + FSCTL_GET_NTFS_FILE_RECORD = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (26 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Retrieves a bitmap of occupied and available clusters on a volume. + FSCTL_GET_VOLUME_BITMAP = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (27 << 2) | IoMethod.Neither | (0 << 14), + + + /// Given a file handle, retrieves a data structure that describes the allocation and location on disk of a specific file, or, given a volume handle, the locations of bad clusters on a volume. + FSCTL_GET_RETRIEVAL_POINTERS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (28 << 2) | IoMethod.Neither | (0 << 14), + + + /// Relocates one or more virtual clusters of a file from one logical cluster to another within the same volume. This operation is used during defragmentation. + FSCTL_MOVE_FILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (29 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// The FSCTL_IS_VOLUME_DIRTY control code determines whether the specified volume is dirty. + /// If the volume information file is corrupted, NTFS will return STATUS_FILE_CORRUPT_ERROR. + /// To perform this operation, minifilter drivers call FltFsControlFile with the following parameters, and file systems, redirectors, and + /// legacy file system filter drivers call ZwFsControlFile with the following parameters. + /// + FSCTL_IS_VOLUME_DIRTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (30 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + FsctlGetHfsInformation = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (31 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Signals the file system driver not to perform any I/O boundary checks on partition read or write calls. Instead, boundary checks are performed by the device driver. + FSCTL_ALLOW_EXTENDED_DASD_IO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (32 << 2) | IoMethod.Neither | (0 << 14), + + + /// + FsctlReadPropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (33 << 2) | IoMethod.Neither | (0 << 14), + + + /// + FsctlWritePropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (34 << 2) | IoMethod.Neither | (0 << 14), + + + /// + FsctlDumpPropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (37 << 2) | IoMethod.Neither | (0 << 14), + + + /// Searches a directory for a file whose creator owner matches the specified SID. + FSCTL_FIND_FILES_BY_SID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (35 << 2) | IoMethod.Neither | (0 << 14), + + + /// Sets the object identifier for the specified file or directory. + FSCTL_SET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (38 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Retrieves the object identifier for the specified file or directory. + FSCTL_GET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (39 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Removes the object identifier from a specified file or directory. The underlying object is not deleted. + FSCTL_DELETE_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (40 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// The FSCTL_SET_REPARSE_POINT control code sets a reparse point on a file or directory. + /// To perform this operation, call ZwFsControlFile with the following parameters. + /// Minifilters should use FltTagFile instead of FSCTL_SET_REPARSE_POINT to set a reparse point. + /// For more information about reparse points and the FSCTL_SET_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. + /// + FSCTL_SET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (41 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// The FSCTL_GET_REPARSE_POINT control code retrieves the reparse point data associated with the specified file or directory. + /// To perform this operation, call FltFsControlFile or ZwFsControlFile with the following parameters. + /// For more information about reparse points and the FSCTL_GET_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. + /// + FSCTL_GET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (42 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// The FSCTL_DELETE_REPARSE_POINT control code deletes a reparse point from the specified file or directory. + /// Using FSCTL_DELETE_REPARSE_POINT does not delete the file or directory. + /// To perform this operation, call ZwFsControlFile with the following parameters. + /// Minifilters should use FltUntagFile instead of FSCTL_DELETE_REPARSE_POINT to delete a reparse point. + /// For more information about reparse points and the FSCTL_DELETE_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. + /// + FSCTL_DELETE_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (43 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// Enumerates the update sequence number (USN) data between two specified boundaries to obtain master file table (MFT) records. + /// + FSCTL_ENUM_USN_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (44 << 2) | IoMethod.Neither | (0 << 14), + + + /// The FSCTL_SECURITY_ID_CHECK control code performs a bulk security check of the security identifiers exposed through USN records. + FSCTL_SECURITY_ID_CHECK = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (45 << 2) | IoMethod.Neither | (FileAccess.Read << 14), + + + /// Retrieves the set of update sequence number (USN) change journal records between two specified USN values. + /// MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/aa364586(v=vs.85).aspx + FSCTL_READ_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (46 << 2) | IoMethod.Neither | (0 << 14), + + + /// Modifies user data associated with the object identifier for the specified file or directory. + FSCTL_SET_OBJECT_ID_EXTENDED = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (47 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Retrieves the object identifier for the specified file or directory. If no object identifier exists, using FSCTL_CREATE_OR_GET_OBJECT_ID creates one. + FSCTL_CREATE_OR_GET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (48 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Marks the indicated file as sparse or not sparse. In a sparse file, large ranges of zeros may not require disk allocation. Space for nonzero data will be allocated as needed as the file is written. + FSCTL_SET_SPARSE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (49 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Fills a specified range of a file with zeros (0). If the file is sparse or compressed, the NTFS file system may deallocate disk space in the file. This sets the range of bytes to zeros (0) without extending the file size. + FSCTL_SET_ZERO_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (50 << 2) | IoMethod.Buffered | (FileAccess.Write << 14), + + + /// Scans a file or alternate stream looking for ranges that may contain nonzero data. Only compressed or sparse files can have zeroed ranges known to the operating system. For other files, the output buffer will contain only a single entry that contains the starting point and the length requested. + FSCTL_QUERY_ALLOCATED_RANGES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (51 << 2) | IoMethod.Neither | (FileAccess.Read << 14), + + + /// + FsctlEnableUpgrade = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (52 << 2) | IoMethod.Buffered | (FileAccess.Write << 14), + + + /// + /// The FSCTL_SET_ENCRYPTION request sets the encryption for the file or directory associated with the given handle. + /// The message contains an ENCRYPTION_BUFFER structure that indicates whether to encrypt/decrypt a file or an individual stream. + /// + FSCTL_SET_ENCRYPTION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (53 << 2) | IoMethod.Neither | (0 << 14), + + + /// + FsctlEncryptionFsctlIo = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (54 << 2) | IoMethod.Neither | (0 << 14), + + + /// + FsctlWriteRawEncrypted = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (55 << 2) | IoMethod.Neither | (0 << 14), + + + /// + FsctlReadRawEncrypted = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (56 << 2) | IoMethod.Neither | (0 << 14), + + + /// Creates an update sequence number (USN) change journal stream on a target volume, or modifies an existing change journal stream. + FSCTL_CREATE_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (57 << 2) | IoMethod.Neither | (0 << 14), + + + /// Retrieves the update sequence number (USN) change-journal information for the specified file or directory. + FSCTL_READ_FILE_USN_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (58 << 2) | IoMethod.Neither | (0 << 14), + + + /// Generates a record in the update sequence number (USN) change journal stream for the input file. This record will have the USN_REASON_CLOSE flag. + FSCTL_WRITE_USN_CLOSE_RECORD = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (59 << 2) | IoMethod.Neither | (0 << 14), + + + /// Increases the size of a mounted volume. + FSCTL_EXTEND_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (60 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Queries for information on the current update sequence number (USN) change journal, its records, and its capacity. + FSCTL_QUERY_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (61 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Deletes the update sequence number (USN) change journal on a volume, or waits for notification of change journal deletion. + FSCTL_DELETE_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (62 << 2) | IoMethod.Buffered | (0 << 14), + + + /// Marks a specified file or directory and its change journal record with information about changes to that file or directory. + FSCTL_MARK_HANDLE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (63 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + /// The FSCTL_SIS_COPYFILE request message requests that the server use the single-instance storage (SIS)filter to copy a file. + /// The message contains an SI_COPYFILE data element. For more information about single-instance storage, see [SIS]. + /// If the SIS filter is installed on the server, it will attempt to copy the specified source file to the specified destination + /// file by creating an SIS link instead of actually copying the file data. If necessary and allowed, the source file is placed under + /// SIS control before the destination file is created. + /// This FSCTL can be issued against either a file or directory handle. The source and destination files MUST reside on the volume + /// associated with the given handle. + /// + FSCTL_SIS_COPYFILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (64 << 2) | IoMethod.Buffered | (0 << 14), + + + /// + FsctlSisLinkFiles = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (65 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// + FsctlHsmMsg = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (66 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// + FsctlNssControl = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (67 << 2) | IoMethod.Buffered | (FileAccess.Write << 14), + + + /// + FsctlNssRcontrol = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (70 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + + /// + FsctlHsmData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (68 << 2) | IoMethod.Neither | ((FileAccess.Read | FileAccess.Write) << 14), + + + /// Recalls a file from storage media that Remote Storage manages, which is the hierarchical storage management software. + FSCTL_RECALL_FILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (69 << 2) | IoMethod.Neither | (0 << 14), + + + /// The FSCTL_GET_BOOT_AREA_INFO control code retrieves the locations of boot sectors for a volume. + FSCTL_GET_BOOT_AREA_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (140 << 2) | IoMethod.Buffered | (0 << 14), + + #endregion // FILE_DEVICE_FILE_SYSTEM + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/IoMethod.cs b/AlphaFS/Filesystem/Native Other/IoMethod.cs new file mode 100644 index 000000000..a9e341d28 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/IoMethod.cs @@ -0,0 +1,45 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Define values for DeviceIoControl method (if buffered, direct, etc...) + [Flags] + internal enum IoMethod : uint + { + /// Buffered + Buffered = 0, + + /// InDirect + InDirect = 1, + + /// OutDirect + OutDirect = 2, + + /// Neither + Neither = 3 + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs new file mode 100644 index 000000000..603609d25 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs @@ -0,0 +1,91 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Provides a symbolic means of representing storage bus types. + internal enum STORAGE_BUS_TYPE + { + /// Indicates an unknown bus type. + BusTypeUnknown = 0, + + /// Indicates a SCSI bus type. + BusTypeScsi = 1, + + /// Indicates an ATAPI bus type. + BusTypeAtapi = 2, + + /// Indicates an ATA bus type. + BusTypeAta = 3, + + /// Indicates an IEEE 1394 bus type. + BusType1394 = 4, + + /// Indicates an SSA bus type. + BusTypeSsa = 5, + + /// Indicates a fiber channel bus type. + BusTypeFibre = 6, + + /// Indicates a USB bus type. + BusTypeUsb = 7, + + /// Indicates a RAID bus type. + BusTypeRAID = 8, + + /// Indicates an iSCSI bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + BusTypeiScsi = 9, + + /// Indicates a serial-attached SCSI (SAS) bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + BusTypeSas = 10, + + /// Indicates a SATA bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + BusTypeSata = 11, + + /// Indicates a secure digital (SD) bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + BusTypeSd = 12, + + /// Indicates a multimedia card (MMC) bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + BusTypeMmc = 13, + + /// Indicates a virtual bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + BusTypeVirtual = 14, + + /// Indicates a file-backed virtual bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + BusTypeFileBackedVirtual = 15, + + /// Indicates the maximum value for this value. + BusTypeMax = 16, + + /// The maximum value of the storage bus type range. + BusTypeMaxReserved = 127 + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs new file mode 100644 index 000000000..1f7c9a2c9 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs @@ -0,0 +1,72 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// Used in conjunction with the IOCTL_STORAGE_QUERY_PROPERTY control code to retrieve the storage device descriptor data for a device. + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct STORAGE_DEVICE_DESCRIPTOR + { + /// Contains the size of this structure, in bytes. The value of this member will change as members are added to the structure. + public readonly uint Version; + + /// Specifies the total size of the descriptor, in bytes, which may include vendor ID, product ID, product revision, device serial number strings and bus-specific data which are appended to the structure. + public readonly uint Size; + + /// Specifies the device type as defined by the Small Computer Systems Interface (SCSI) specification. + public readonly byte DeviceType; + + /// Specifies the device type modifier, if any, as defined by the SCSI specification. If no device type modifier exists, this member is zero. + public readonly byte DeviceTypeModifier; + + /// Indicates when TRUE that the device's media (if any) is removable. If the device has no media, this member should be ignored. When FALSE the device's media is not removable. + [MarshalAs(UnmanagedType.U1)] public readonly bool RemovableMedia; + + /// Indicates when TRUE that the device supports multiple outstanding commands (SCSI tagged queuing or equivalent). When FALSE, the device does not support SCSI-tagged queuing or the equivalent. + [MarshalAs(UnmanagedType.U1)] public readonly bool CommandQueueing; + + /// Specifies the byte offset from the beginning of the structure to a null-terminated ASCII string that contains the device's vendor ID. If the device has no vendor ID, this member is zero. + public readonly uint VendorIdOffset; + + /// Specifies the byte offset from the beginning of the structure to a null-terminated ASCII string that contains the device's product ID. If the device has no product ID, this member is zero. + public readonly uint ProductIdOffset; + + /// Specifies the byte offset from the beginning of the structure to a null-terminated ASCII string that contains the device's product revision string. If the device has no product revision string, this member is zero. + public readonly uint ProductRevisionOffset; + + /// Specifies the byte offset from the beginning of the structure to a null-terminated ASCII string that contains the device's serial number. If the device has no serial number, this member is zero. + public readonly uint SerialNumberOffset; + + /// Specifies an enumerator value of type STORAGE_BUS_TYPE that indicates the type of bus to which the device is connected. This should be used to interpret the raw device properties at the end of this structure (if any). + public readonly STORAGE_BUS_TYPE BusType; + + /// Indicates the number of bytes of bus-specific data that have been appended to this descriptor. + public readonly uint RawPropertiesLength; + + /// Contains an array of length one that serves as a place holder for the first byte of the bus specific property data. + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 22)] public readonly byte[] RawDeviceProperties; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs new file mode 100644 index 000000000..a7ddcc792 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs @@ -0,0 +1,48 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// + /// The STORAGE_DEVICE_NUMBER structure is used in conjunction with the IOCTL_STORAGE_GET_DEVICE_NUMBER request to retrieve the FILE_DEVICE_XXX device type, + /// the device number, and, for a device that can be partitioned, the partition number assigned to a device by the driver when the device is started. + /// + /// MSDN: http://msdn.microsoft.com/en-us/library/windows/hardware/ff566974(v=vs.85).aspx + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct STORAGE_DEVICE_NUMBER + { + /// Specifies one of the system-defined FILE_DEVICE_XXX constants indicating the type of device (such as FILE_DEVICE_DISK, FILE_DEVICE_KEYBOARD, + /// and so forth) or a vendor-defined value for a new type of device. + /// + internal readonly StorageDeviceType DeviceType; + + /// Indicates the number of this device. This value is set to 0xFFFFFFFF (-1) for the disks that represent the physical paths of an MPIO disk. + [MarshalAs(UnmanagedType.U4)] internal readonly int DeviceNumber; + + /// Indicates the partition number of the device is returned in this member, if the device can be partitioned. Otherwise, -1 is returned. + [MarshalAs(UnmanagedType.U4)] internal readonly int PartitionNumber; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs new file mode 100644 index 000000000..eea8cd3df --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs @@ -0,0 +1,267 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + // STORAGE_DEVICE_NUMBER structure. + // 2018-01-17: https://msdn.microsoft.com/en-us/library/bb968801(VS.85).aspx + + // The type of device. Values from 0 through 32,767 are reserved for use by Microsoft. + // Values from 32,768 through 65,535 are reserved for use by other vendors. The following values are defined by Microsoft. + + + /// The storage device type. + internal enum STORAGE_DEVICE_TYPE + { + /// FILE_DEVICE_BEEP parameter. + FILE_DEVICE_BEEP = 1, + + /// FILE_DEVICE_CD_ROM parameter. + FILE_DEVICE_CD_ROM = 2, + + /// FILE_DEVICE_CD_ROM_FILE_SYSTEM parameter. + FILE_DEVICE_CD_ROM_FILE_SYSTEM = 3, + + /// FILE_DEVICE_CONTROLLER parameter. + FILE_DEVICE_CONTROLLER = 4, + + /// FILE_DEVICE_DATALINK parameter. + FILE_DEVICE_DATALINK = 5, + + /// FILE_DEVICE_DFS parameter. + FILE_DEVICE_DFS = 6, + + /// FILE_DEVICE_DISK parameter. + FILE_DEVICE_DISK = 7, + + /// FILE_DEVICE_DISK_FILE_SYSTEM parameter. + FILE_DEVICE_DISK_FILE_SYSTEM = 8, + + /// FILE_DEVICE_FILE_SYSTEM parameter. + FILE_DEVICE_FILE_SYSTEM = 9, + + /// FILE_DEVICE_INPORT_PORT parameter. + FILE_DEVICE_INPORT_PORT = 10, + + /// FILE_DEVICE_KEYBOARD parameter. + FILE_DEVICE_KEYBOARD = 11, + + /// FILE_DEVICE_MAILSLOT parameter. + FILE_DEVICE_MAILSLOT = 12, + + /// FILE_DEVICE_MIDI_IN parameter. + FILE_DEVICE_MIDI_IN = 13, + + /// FILE_DEVICE_MIDI_OUT parameter. + FILE_DEVICE_MIDI_OUT = 14, + + /// FILE_DEVICE_MOUSE parameter. + FILE_DEVICE_MOUSE = 15, + + /// FILE_DEVICE_MULTI_UNC_PROVIDER parameter. + FILE_DEVICE_MULTI_UNC_PROVIDER = 16, + + /// FILE_DEVICE_NAMED_PIPE parameter. + FILE_DEVICE_NAMED_PIPE = 17, + + /// FILE_DEVICE_NETWORK parameter. + FILE_DEVICE_NETWORK = 18, + + /// FILE_DEVICE_NETWORK_BROWSER parameter. + FILE_DEVICE_NETWORK_BROWSER = 19, + + /// FILE_DEVICE_NETWORK_FILE_SYSTEM parameter. + FILE_DEVICE_NETWORK_FILE_SYSTEM = 20, + + /// FILE_DEVICE_NULL parameter. + FILE_DEVICE_NULL = 21, + + /// FILE_DEVICE_PARALLEL_PORT parameter. + FILE_DEVICE_PARALLEL_PORT = 22, + + /// FILE_DEVICE_PHYSICAL_NETCARD parameter. + FILE_DEVICE_PHYSICAL_NETCARD = 23, + + /// FILE_DEVICE_PRINTER parameter. + FILE_DEVICE_PRINTER = 24, + + /// FILE_DEVICE_SCANNER parameter. + FILE_DEVICE_SCANNER = 25, + + /// FILE_DEVICE_SERIAL_MOUSE_PORT parameter. + FILE_DEVICE_SERIAL_MOUSE_PORT = 26, + + /// FILE_DEVICE_SERIAL_PORT parameter. + FILE_DEVICE_SERIAL_PORT = 27, + + /// FILE_DEVICE_SCREEN parameter. + FILE_DEVICE_SCREEN = 28, + + /// FILE_DEVICE_SOUND parameter. + FILE_DEVICE_SOUND = 29, + + /// FILE_DEVICE_STREAMS parameter. + FILE_DEVICE_STREAMS = 30, + + /// FILE_DEVICE_TAPE parameter. + FILE_DEVICE_TAPE = 31, + + /// FILE_DEVICE_TAPE_FILE_SYSTEM parameter. + FILE_DEVICE_TAPE_FILE_SYSTEM = 32, + + /// FILE_DEVICE_TRANSPORT parameter. + FILE_DEVICE_TRANSPORT = 33, + + /// FILE_DEVICE_UNKNOWN parameter. + FILE_DEVICE_UNKNOWN = 34, + + /// FILE_DEVICE_VIDEO parameter. + FILE_DEVICE_VIDEO = 35, + + /// FILE_DEVICE_VIRTUAL_DISK parameter. + FILE_DEVICE_VIRTUAL_DISK = 36, + + /// FILE_DEVICE_WAVE_IN parameter. + FILE_DEVICE_WAVE_IN = 37, + + /// FILE_DEVICE_WAVE_OUT parameter. + FILE_DEVICE_WAVE_OUT = 38, + + /// FILE_DEVICE_8042_PORT parameter. + FILE_DEVICE_8042_PORT = 39, + + /// FILE_DEVICE_NETWORK_REDIRECTOR parameter. + FILE_DEVICE_NETWORK_REDIRECTOR = 40, + + /// FILE_DEVICE_BATTERY parameter. + FILE_DEVICE_BATTERY = 41, + + /// FILE_DEVICE_BUS_EXTENDER parameter. + FILE_DEVICE_BUS_EXTENDER = 42, + + /// FILE_DEVICE_MODEM parameter. + FILE_DEVICE_MODEM = 43, + + /// FILE_DEVICE_VDM parameter. + FILE_DEVICE_VDM = 44, + + /// FILE_DEVICE_MASS_STORAGE parameter. + FILE_DEVICE_MASS_STORAGE = 45, + + /// FILE_DEVICE_SMB parameter. + FILE_DEVICE_SMB = 46, + + /// FILE_DEVICE_KS parameter. + FILE_DEVICE_KS = 47, + + /// FILE_DEVICE_CHANGER parameter. + FILE_DEVICE_CHANGER = 48, + + /// FILE_DEVICE_SMARTCARD parameter. + FILE_DEVICE_SMARTCARD = 49, + + /// FILE_DEVICE_ACPI parameter. + FILE_DEVICE_ACPI = 50, + + /// FILE_DEVICE_DVD parameter. + FILE_DEVICE_DVD = 51, + + /// FILE_DEVICE_FULLSCREEN_VIDEO parameter. + FILE_DEVICE_FULLSCREEN_VIDEO = 52, + + /// FILE_DEVICE_DFS_FILE_SYSTEM parameter. + FILE_DEVICE_DFS_FILE_SYSTEM = 53, + + /// FILE_DEVICE_DFS_VOLUME parameter. + FILE_DEVICE_DFS_VOLUME = 54, + + /// FILE_DEVICE_SERENUM parameter. + FILE_DEVICE_SERENUM = 55, + + /// FILE_DEVICE_TERMSRV parameter. + FILE_DEVICE_TERMSRV = 56, + + /// FILE_DEVICE_KSEC parameter. + FILE_DEVICE_KSEC = 57, + + /// FILE_DEVICE_FIPS parameter. + FILE_DEVICE_FIPS = 58, + + /// FILE_DEVICE_INFINIBAND parameter. + FILE_DEVICE_INFINIBAND = 59, + + /// FILE_DEVICE_VMBUS parameter. + FILE_DEVICE_VMBUS = 62, + + /// FILE_DEVICE_CRYPT_PROVIDER parameter. + FILE_DEVICE_CRYPT_PROVIDER = 63, + + /// FILE_DEVICE_WPD parameter. + FILE_DEVICE_WPD = 64, + + /// FILE_DEVICE_BLUETOOTH parameter. + FILE_DEVICE_BLUETOOTH = 65, + + /// FILE_DEVICE_MT_COMPOSITE parameter. + FILE_DEVICE_MT_COMPOSITE = 66, + + /// FILE_DEVICE_MT_TRANSPORT parameter. + FILE_DEVICE_MT_TRANSPORT = 67, + + /// FILE_DEVICE_BIOMETRIC parameter. + FILE_DEVICE_BIOMETRIC = 68, + + /// FILE_DEVICE_PMI parameter. + FILE_DEVICE_PMI = 69, + + /// FILE_DEVICE_EHSTOR parameter. + FILE_DEVICE_EHSTOR = 70, + + /// FILE_DEVICE_DEVAPI parameter. + FILE_DEVICE_DEVAPI = 71, + + /// FILE_DEVICE_GPIO parameter. + FILE_DEVICE_GPIO = 72, + + /// FILE_DEVICE_USBEX parameter. + FILE_DEVICE_USBEX = 73, + + /// FILE_DEVICE_CONSOLE parameter. + FILE_DEVICE_CONSOLE = 80, + + /// FILE_DEVICE_NFP parameter. + FILE_DEVICE_NFP = 81, + + /// FILE_DEVICE_SYSENV parameter. + FILE_DEVICE_SYSENV = 82, + + + /// [AlphaFS] FILE_DEVICE_MASS_STORAGE parameter. + FILE_DEVICE_VOLUME = 86, + + + /// [AlphaFS] FILE_DEVICE_MASS_STORAGE parameter. + IOCTL_STORAGE_QUERY_PROPERTY = 86, + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs new file mode 100644 index 000000000..cadf7799d --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs @@ -0,0 +1,48 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// Indicates the properties of a storage device or adapter to retrieve as the input buffer passed to the IOCTL_STORAGE_QUERY_PROPERTY control code. + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct STORAGE_PROPERTY_QUERY + { + /// Indicates whether the caller is requesting a device descriptor, an adapter descriptor, a write cache property, a device unique ID (DUID), + /// or the device identifiers provided in the device's SCSI vital product data (VPD) page. For a list of the property IDs that can be assigned to this member, see STORAGE_PROPERTY_ID. + /// + public uint PropertyId; + + /// Contains flags indicating the type of query to be performed as enumerated by the STORAGE_QUERY_TYPE enumeration. + /// PropertyStandardQuery = 0: Instructs the port driver to report a device descriptor, an adapter descriptor or a unique hardware device ID(DUID). + /// PropertyExistsQuery = 1: Instructs the port driver to report whether the descriptor is supported. + /// + public uint QueryType; + + /// Contains an array of bytes that can be used to retrieve additional parameters for specific queries. + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] + public byte[] AdditionalParameters; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs b/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs new file mode 100644 index 000000000..a9e04d3c1 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs @@ -0,0 +1,39 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// Represents a physical location on a disk. It is the output buffer for the control code. + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct VOLUME_DISK_EXTENTS + { + /// The number of disks in the volume (a volume can span multiple disks). + public uint NumberOfDiskExtents; + + /// An array of structures. + [MarshalAs(UnmanagedType.ByValArray)] public DISK_EXTENT[] Extents; + } + } +} diff --git a/AlphaFS/Filesystem/Structures And Enumerations/CopyMoveProgressCallbackReason.cs b/AlphaFS/Filesystem/Structures, Enumerations/CopyMoveProgressCallbackReason.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/CopyMoveProgressCallbackReason.cs rename to AlphaFS/Filesystem/Structures, Enumerations/CopyMoveProgressCallbackReason.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/CopyMoveProgressResult.cs b/AlphaFS/Filesystem/Structures, Enumerations/CopyMoveProgressResult.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/CopyMoveProgressResult.cs rename to AlphaFS/Filesystem/Structures, Enumerations/CopyMoveProgressResult.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/CopyOptions.cs b/AlphaFS/Filesystem/Structures, Enumerations/CopyOptions.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/CopyOptions.cs rename to AlphaFS/Filesystem/Structures, Enumerations/CopyOptions.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/DeviceGuid.cs b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs similarity index 95% rename from AlphaFS/Filesystem/Structures And Enumerations/DeviceGuid.cs rename to AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs index 7710a3527..8d6c00ac8 100644 --- a/AlphaFS/Filesystem/Structures And Enumerations/DeviceGuid.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs @@ -132,7 +132,8 @@ public enum DeviceGuid /// The GUID_DEVINTERFACE_COMPORT device interface class is defined for COM ports. [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "ComPort")] - [Description("86E0D1E0-8089-11D0-9CE4-08003E301F73")] ComPort, + [Description("86E0D1E0-8089-11D0-9CE4-08003E301F73")] + ComPort, /// The GUID_DEVINTERFACE_PARALLEL device interface class is defined for parallel ports that support an IEEE 1284-compatible hardware interface. [Description("97F76EF0-F883-11D0-AF1F-0000F800845C")] Parallel, @@ -148,12 +149,12 @@ public enum DeviceGuid #region Storage Devices /// The GUID_DEVINTERFACE_CDCHANGER device interface class is defined for CD-ROM changer devices. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cdrom")] - [Description("53F56312-B6BF-11D0-94F2-00A0C91EFB8B")] CdromChanger, + [Description("53F56312-B6BF-11D0-94F2-00A0C91EFB8B")] CDChanger, /// The GUID_DEVINTERFACE_CDROM device interface class is defined for CD-ROM storage devices. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cdrom")] - [Description("53F56308-B6BF-11D0-94F2-00A0C91EFB8B")] Cdrom, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "rom")] + [Description("53F56308-B6BF-11D0-94F2-00A0C91EFB8B")] + CDRom, /// The GUID_DEVINTERFACE_DISK device interface class is defined for hard disk storage devices. [Description("53F56307-B6BF-11D0-94F2-00A0C91EFB8B")] Disk, @@ -185,16 +186,19 @@ public enum DeviceGuid /// The GUID_DEVINTERFACE_USB_DEVICE device interface class is defined for USB devices that are attached to a USB hub. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] - [Description("A5DCBF10-6530-11D2-901F-00C04FB951ED")] UsbDevice, + [Description("A5DCBF10-6530-11D2-901F-00C04FB951ED")] + UsbDevice, /// The GUID_DEVINTERFACE_USB_HOST_CONTROLLER device interface class is defined for USB host controller devices. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] - [Description("3ABF6F2D-71C4-462A-8A92-1E6861E6AF27")] UsbHostController, + [Description("3ABF6F2D-71C4-462A-8A92-1E6861E6AF27")] + UsbHostController, /// The GUID_DEVINTERFACE_USB_HUB device interface class is defined for USB hub devices. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] - [Description("F18A0E88-C30C-11D0-8815-00A0C906BED8")] UsbHub + [Description("F18A0E88-C30C-11D0-8815-00A0C906BED8")] + UsbHub #endregion // USB Devices } -} \ No newline at end of file +} diff --git a/AlphaFS/Filesystem/Structures And Enumerations/DiGetClassFlags.cs b/AlphaFS/Filesystem/Structures, Enumerations/DiGetClassFlags.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/DiGetClassFlags.cs rename to AlphaFS/Filesystem/Structures, Enumerations/DiGetClassFlags.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/DirectoryEnumerationFilters.cs b/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/DirectoryEnumerationFilters.cs rename to AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/DirectoryEnumerationOptions.cs b/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationOptions.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/DirectoryEnumerationOptions.cs rename to AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationOptions.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/DosDeviceAttributes.cs b/AlphaFS/Filesystem/Structures, Enumerations/DosDeviceAttributes.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/DosDeviceAttributes.cs rename to AlphaFS/Filesystem/Structures, Enumerations/DosDeviceAttributes.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/EncryptedFileRawMode.cs b/AlphaFS/Filesystem/Structures, Enumerations/EncryptedFileRawMode.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/EncryptedFileRawMode.cs rename to AlphaFS/Filesystem/Structures, Enumerations/EncryptedFileRawMode.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/ErrorMode.cs b/AlphaFS/Filesystem/Structures, Enumerations/ErrorMode.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/ErrorMode.cs rename to AlphaFS/Filesystem/Structures, Enumerations/ErrorMode.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/ExtendedFileAttributes.cs b/AlphaFS/Filesystem/Structures, Enumerations/ExtendedFileAttributes.cs similarity index 99% rename from AlphaFS/Filesystem/Structures And Enumerations/ExtendedFileAttributes.cs rename to AlphaFS/Filesystem/Structures, Enumerations/ExtendedFileAttributes.cs index 4cf77b7a2..2efa7caed 100644 --- a/AlphaFS/Filesystem/Structures And Enumerations/ExtendedFileAttributes.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/ExtendedFileAttributes.cs @@ -28,7 +28,7 @@ namespace Alphaleonis.Win32.Filesystem /// Specifies how the operating system should open a file. [SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags")] [Flags] - public enum ExtendedFileAttributes + public enum ExtendedFileAttributes { /// If you pass , the set of attributes is unspecified. explicitly sets no attributes. None = 0, diff --git a/AlphaFS/Filesystem/Structures And Enumerations/FileEncryptionStatus.cs b/AlphaFS/Filesystem/Structures, Enumerations/FileEncryptionStatus.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/FileEncryptionStatus.cs rename to AlphaFS/Filesystem/Structures, Enumerations/FileEncryptionStatus.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/FileIdInfo.cs b/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs similarity index 92% rename from AlphaFS/Filesystem/Structures And Enumerations/FileIdInfo.cs rename to AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs index 89e754d56..cf2728bf2 100644 --- a/AlphaFS/Filesystem/Structures And Enumerations/FileIdInfo.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs @@ -65,7 +65,7 @@ private static void ArrayToLong(byte[] fileId, int startIndex, int count, out lo value = 0; for (var i = 0; i < count; i++) - value |= (long) fileId[startIndex + i] << (8 * i); + value |= (long)fileId[startIndex + i] << (8 * i); } @@ -80,7 +80,7 @@ public int CompareTo(object obj) if (!(obj is FileIdInfo)) throw new ArgumentException("Object must be of type FileIdInfo"); - return CompareTo((FileIdInfo) obj); + return CompareTo((FileIdInfo)obj); } @@ -105,7 +105,7 @@ public int CompareTo(FileIdInfo other) /// true if the specified is equal to this instance; otherwise, false. public override bool Equals(object obj) { - return obj is FileIdInfo && Equals((FileIdInfo) obj); + return obj is FileIdInfo && Equals((FileIdInfo)obj); } @@ -170,7 +170,7 @@ public override int GetHashCode() { // _fileIdHighPart is 0 on NTFS and should be often 0 on ReFS, thus ignore it. - return (int) _fileIdLowPart ^ ((int) (_fileIdLowPart >> 32) | (int) _volumeSerialNumber); + return (int)_fileIdLowPart ^ ((int)(_fileIdLowPart >> 32) | (int)_volumeSerialNumber); } } @@ -185,13 +185,13 @@ public override string ToString() 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), + ((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)); + ((uint)(_fileIdLowPart >> 32)).ToString("X", CultureInfo.InvariantCulture), + ((uint)_fileIdLowPart).ToString("X", CultureInfo.InvariantCulture)); } } } diff --git a/AlphaFS/Filesystem/Structures And Enumerations/FinalPathFormats.cs b/AlphaFS/Filesystem/Structures, Enumerations/FinalPathFormats.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/FinalPathFormats.cs rename to AlphaFS/Filesystem/Structures, Enumerations/FinalPathFormats.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/GetFullPathOptions.cs b/AlphaFS/Filesystem/Structures, Enumerations/GetFullPathOptions.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/GetFullPathOptions.cs rename to AlphaFS/Filesystem/Structures, Enumerations/GetFullPathOptions.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/MoveOptions.cs b/AlphaFS/Filesystem/Structures, Enumerations/MoveOptions.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/MoveOptions.cs rename to AlphaFS/Filesystem/Structures, Enumerations/MoveOptions.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/PathFormat.cs b/AlphaFS/Filesystem/Structures, Enumerations/PathFormat.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/PathFormat.cs rename to AlphaFS/Filesystem/Structures, Enumerations/PathFormat.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/ReparsePointTag.cs b/AlphaFS/Filesystem/Structures, Enumerations/ReparsePointTag.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/ReparsePointTag.cs rename to AlphaFS/Filesystem/Structures, Enumerations/ReparsePointTag.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs b/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs rename to AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs new file mode 100644 index 000000000..bd81d5172 --- /dev/null +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs @@ -0,0 +1,97 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Provides a symbolic means of representing storage bus types. + public enum StorageBusType + { + /// Indicates an unknown bus type. + None = NativeMethods.STORAGE_BUS_TYPE.BusTypeUnknown, + + /// Indicates a SCSI bus type. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SCSI")] + SCSI = NativeMethods.STORAGE_BUS_TYPE.BusTypeScsi, + + /// Indicates an ATAPI bus type. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ATAPI")] + ATAPI = NativeMethods.STORAGE_BUS_TYPE.BusTypeAtapi, + + /// Indicates an ATA bus type. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ATA")] + ATA = NativeMethods.STORAGE_BUS_TYPE.BusTypeAta, + + /// Indicates an IEEE 1394 bus type. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "IEEE")] + IEEE1394 = NativeMethods.STORAGE_BUS_TYPE.BusType1394, + + /// Indicates an SSA bus type. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSA")] + SSA = NativeMethods.STORAGE_BUS_TYPE.BusTypeSsa, + + /// Indicates a fiber channel bus type. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fibre")] + Fibre = NativeMethods.STORAGE_BUS_TYPE.BusTypeFibre, + + /// Indicates a USB bus type. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "USB")] + USB = NativeMethods.STORAGE_BUS_TYPE.BusTypeUsb, + + /// Indicates a RAID bus type. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "RAID")] + RAID = NativeMethods.STORAGE_BUS_TYPE.BusTypeRAID, + + /// Indicates an iSCSI bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SCSI")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "i")] + iSCSI = NativeMethods.STORAGE_BUS_TYPE.BusTypeiScsi, + + /// Indicates a serial-attached SCSI (SAS) bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SAS")] + SAS = NativeMethods.STORAGE_BUS_TYPE.BusTypeSas, + + /// Indicates a SATA bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SATA")] + SATA = NativeMethods.STORAGE_BUS_TYPE.BusTypeSata, + + /// Indicates a secure digital (SD) bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + SD = NativeMethods.STORAGE_BUS_TYPE.BusTypeSd, + + /// Indicates a multimedia card (MMC) bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "MMC")] + MMC = NativeMethods.STORAGE_BUS_TYPE.BusTypeMmc, + + /// Indicates a virtual bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + Virtual = NativeMethods.STORAGE_BUS_TYPE.BusTypeVirtual, + + /// Indicates a file-backed virtual bus type. + /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + FileBackedVirtual = NativeMethods.STORAGE_BUS_TYPE.BusTypeFileBackedVirtual, + } +} diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs new file mode 100644 index 000000000..6ae488bf3 --- /dev/null +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs @@ -0,0 +1,282 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// The storage device type. + [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags", Justification = "Enum values should not be combinable.")] + public enum StorageDeviceType + { + /// Indicates an unknown storage device type. + None = 0, + + /// FILE_DEVICE_BEEP parameter. + Beep = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BEEP, + + /// FILE_DEVICE_CD_ROM parameter. + CDRom = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM, + + /// FILE_DEVICE_CD_ROM_FILE_SYSTEM parameter. + CDRomFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM_FILE_SYSTEM, + + /// FILE_DEVICE_CONTROLLER parameter. + Controller = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CONTROLLER, + + /// FILE_DEVICE_DATALINK parameter. + DataLink = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DATALINK, + + /// FILE_DEVICE_DFS parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "DFS")] + DFS = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS, + + /// FILE_DEVICE_DISK parameter. + Disk = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK, + + /// FILE_DEVICE_DISK_FILE_SYSTEM parameter. + DiskFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK_FILE_SYSTEM, + + /// FILE_DEVICE_FILE_SYSTEM parameter. + FileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM, + + /// FILE_DEVICE_INPORT_PORT parameter. + InPort = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_INPORT_PORT, + + /// FILE_DEVICE_KEYBOARD parameter. + Keyboard = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_KEYBOARD, + + /// FILE_DEVICE_MAILSLOT parameter. + MailSlot = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MAILSLOT, + + /// FILE_DEVICE_MIDI_IN parameter. + MidiIn = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MIDI_IN, + + /// FILE_DEVICE_MIDI_OUT parameter. + MidiOut = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MIDI_OUT, + + /// FILE_DEVICE_MOUSE parameter. + Mouse = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MOUSE, + + /// FILE_DEVICE_MULTI_UNC_PROVIDER parameter. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi")] + MultiUncProvider = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MULTI_UNC_PROVIDER, + + /// FILE_DEVICE_NAMED_PIPE parameter. + NamedPipe = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NAMED_PIPE, + + /// FILE_DEVICE_NETWORK parameter. + Network = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NETWORK, + + /// FILE_DEVICE_NETWORK_BROWSER parameter. + NetworkBrowser = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NETWORK_BROWSER, + + /// FILE_DEVICE_NETWORK_FILE_SYSTEM parameter. + NetworkFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NETWORK_FILE_SYSTEM, + + /// FILE_DEVICE_NULL parameter. + NullDevice = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NULL, + + /// FILE_DEVICE_PARALLEL_PORT parameter. + ParallelPort = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_PARALLEL_PORT, + + /// FILE_DEVICE_PHYSICAL_NETCARD parameter. + PhysicalNetCard = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_PHYSICAL_NETCARD, + + /// FILE_DEVICE_PRINTER parameter. + Printer = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_PRINTER, + + /// FILE_DEVICE_SCANNER parameter. + Scanner = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SCANNER, + + /// FILE_DEVICE_SERIAL_MOUSE_PORT parameter. + SerialMousePort = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SERIAL_MOUSE_PORT, + + /// FILE_DEVICE_SERIAL_PORT parameter. + SerialPort = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SERIAL_PORT, + + /// FILE_DEVICE_SCREEN parameter. + Screen = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SCREEN, + + /// FILE_DEVICE_SOUND parameter. + Sound = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SOUND, + + /// FILE_DEVICE_STREAMS parameter. + Streams = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_STREAMS, + + /// FILE_DEVICE_TAPE parameter. + Tape = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_TAPE, + + /// FILE_DEVICE_TAPE_FILE_SYSTEM parameter. + TapeFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_TAPE_FILE_SYSTEM, + + /// FILE_DEVICE_TRANSPORT parameter. + Transport = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_TRANSPORT, + + /// FILE_DEVICE_UNKNOWN parameter. + Unknown = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_UNKNOWN, + + /// FILE_DEVICE_VIDEO parameter. + Video = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO, + + /// FILE_DEVICE_VIRTUAL_DISK parameter. + VirtualDisk = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VIRTUAL_DISK, + + /// FILE_DEVICE_WAVE_IN parameter. + WaveIn = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_WAVE_IN, + + /// FILE_DEVICE_WAVE_OUT parameter. + WaveOut = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_WAVE_OUT, + + /// FILE_DEVICE_8042_PORT parameter. + Port8042 = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_8042_PORT, + + /// FILE_DEVICE_NETWORK_REDIRECTOR parameter. + NetworkRedirector = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NETWORK_REDIRECTOR, + + /// FILE_DEVICE_BATTERY parameter. + Battery = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BATTERY, + + /// FILE_DEVICE_BUS_EXTENDER parameter. + BusExtender = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BUS_EXTENDER, + + /// FILE_DEVICE_MODEM parameter. + Modem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MODEM, + + /// FILE_DEVICE_VDM parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "VDM")] + VDM = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VDM, + + /// FILE_DEVICE_MASS_STORAGE parameter. + MassStorage = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE, + + /// FILE_DEVICE_SMB parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SMB")] + SMB = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SMB, + + /// FILE_DEVICE_KS parameter. + KS = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_KS, + + /// FILE_DEVICE_CHANGER parameter. + Changer = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER, + + /// FILE_DEVICE_SMARTCARD parameter. + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SmartCard")] + SmartCard = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SMARTCARD, + + /// FILE_DEVICE_ACPI parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ACPI")] + ACPI = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_ACPI, + + /// FILE_DEVICE_DVD parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "DVD")] + DVD = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DVD, + + /// FILE_DEVICE_FULLSCREEN_VIDEO parameter. + FullScreenVideo = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_FULLSCREEN_VIDEO, + + /// FILE_DEVICE_DFS_FILE_SYSTEM parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "DEVICE")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "DFS")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "FILE")] + [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores")] + FILE_DEVICE_DFSFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS_FILE_SYSTEM, + + /// FILE_DEVICE_DFS_VOLUME parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "DFS")] + DFSVolume = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS_VOLUME, + + /// FILE_DEVICE_SERENUM parameter. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Serenum")] + Serenum = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SERENUM, + + /// FILE_DEVICE_TERMSRV parameter. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Srv")] + TermSrv = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_TERMSRV, + + /// FILE_DEVICE_KSEC parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "KSEC")] + KSEC = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_KSEC, + + /// FILE_DEVICE_FIPS parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "FIPS")] + FIPS = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_FIPS, + + /// FILE_DEVICE_INFINIBAND parameter. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infini")] + InfiniBand = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_INFINIBAND, + + /// FILE_DEVICE_VMBUS parameter. + VMBus = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VMBUS, + + /// FILE_DEVICE_CRYPT_PROVIDER parameter. + CryptProvider = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CRYPT_PROVIDER, + + /// FILE_DEVICE_WPD parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "WPD")] + WPD = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_WPD, + + /// FILE_DEVICE_BLUETOOTH parameter. + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "BlueTooth")] + BlueTooth = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BLUETOOTH, + + /// FILE_DEVICE_MT_COMPOSITE parameter. + MTComposite = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MT_COMPOSITE, + + /// FILE_DEVICE_MT_TRANSPORT parameter. + MTTransport = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MT_TRANSPORT, + + /// FILE_DEVICE_BIOMETRIC parameter. + Biometric = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BIOMETRIC, + + /// FILE_DEVICE_PMI parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "PMI")] + PMI = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_PMI, + + /// FILE_DEVICE_EHSTOR parameter. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Stor")] + EHStor = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_EHSTOR, + + /// FILE_DEVICE_DEVAPI parameter. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Api")] + DevApi = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DEVAPI, + + /// FILE_DEVICE_GPIO parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "GPIO")] + GPIO = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_GPIO, + + /// FILE_DEVICE_USBEX parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "USB")] + [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] + USBEx = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_USBEX, + + /// FILE_DEVICE_CONSOLE parameter. + Console = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CONSOLE, + + /// FILE_DEVICE_NFP parameter. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NFP")] + NFP = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NFP, + + /// FILE_DEVICE_SYSENV parameter. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Env")] + SysEnv = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SYSENV + } +} diff --git a/AlphaFS/Filesystem/Structures And Enumerations/SymbolicLinkTarget.cs b/AlphaFS/Filesystem/Structures, Enumerations/SymbolicLinkTarget.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/SymbolicLinkTarget.cs rename to AlphaFS/Filesystem/Structures, Enumerations/SymbolicLinkTarget.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/SymbolicLinkType.cs b/AlphaFS/Filesystem/Structures, Enumerations/SymbolicLinkType.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/SymbolicLinkType.cs rename to AlphaFS/Filesystem/Structures, Enumerations/SymbolicLinkType.cs diff --git a/AlphaFS/Resources.Designer.cs b/AlphaFS/Resources.Designer.cs index 708bf1a5e..8fb5fd6f7 100644 --- a/AlphaFS/Resources.Designer.cs +++ b/AlphaFS/Resources.Designer.cs @@ -60,6 +60,15 @@ internal Resources() { } } + /// + /// Looks up a localized string similar to Argument must be a drive letter from a-z.. + /// + internal static string Argument_must_be_a_drive_letter_from_a_z { + get { + return ResourceManager.GetString("Argument_must_be_a_drive_letter_from_a_z", resourceCulture); + } + } + /// /// Looks up a localized string similar to Buffer is not large enough for the requested operation.. /// diff --git a/AlphaFS/Resources.resx b/AlphaFS/Resources.resx index 3220908a3..65d119a98 100644 --- a/AlphaFS/Resources.resx +++ b/AlphaFS/Resources.resx @@ -112,10 +112,10 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Invalid transaction object. @@ -259,4 +259,7 @@ No drive letters available. + + Argument must be a drive letter from a-z. + \ No newline at end of file diff --git a/AlphaFS/Win32Errors.cs b/AlphaFS/Win32Errors.cs index bb525e86b..2be0b8e28 100644 --- a/AlphaFS/Win32Errors.cs +++ b/AlphaFS/Win32Errors.cs @@ -64,7 +64,7 @@ public static int GetHrFromWin32Error(uint errorCode) //public const uint ERROR_BAD_ENVIRONMENT = 10; //public const uint ERROR_BAD_FORMAT = 11; //public const uint ERROR_INVALID_ACCESS = 12; - //public const uint ERROR_INVALID_DATA = 13; + public const uint ERROR_INVALID_DATA = 13; //public const uint ERROR_OUTOFMEMORY = 14; /// (15) The system cannot find the drive specified. @@ -293,8 +293,8 @@ public static int GetHrFromWin32Error(uint errorCode) //public const uint ERROR_EA_LIST_INCONSISTENT = 255; //public const uint WAIT_TIMEOUT = 258; - ///// (259) No more data is available. - //public const uint ERROR_NO_MORE_ITEMS = 259; + /// (259) No more data is available. + public const uint ERROR_NO_MORE_ITEMS = 259; //public const uint ERROR_CANNOT_COPY = 266; From 9f90e0f817f80ff80f44b6e3508b27d7e2c80711 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 30 Jan 2018 13:14:13 +0100 Subject: [PATCH 002/133] Improved method Device.EnumerateDevicesCore. --- .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 1 + .../AlphaFS_DeviceInfo.InitializeInstance.cs | 4 +- .../AlphaFS.Volume.EnumerateVolumes.cs | 33 ++++-- .../DriveInfo Class/DriveInfo_GetDrives.cs | 14 ++- .../DriveInfo_InitializeInstance.cs | 11 +- AlphaFS/Device/Device.DeviceEnumeration.cs | 101 ++++++++---------- .../Device/Device.EnumeratePhysicalDrives.cs | 2 +- AlphaFS/Device/Device.GetPhysicalDriveInfo.cs | 37 ++++--- .../Device/Device.GetPhysicalDriveNumber.cs | 4 +- AlphaFS/Device/Device.cs | 19 ++-- AlphaFS/Device/DeviceInfo.cs | 2 +- .../Volume/Volume.EnumerateVolumePathNames.cs | 1 + .../File Class/File.OpenPhysicalDrive.cs | 10 +- CHANGELOG.md | 2 +- 14 files changed, 135 insertions(+), 106 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs index f9f8a6e76..31f40e68c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -46,6 +46,7 @@ public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() UnitTestConstants.Dump(drive, -23); + foreach (var volume in drive.Volumes) UnitTestConstants.Dump(volume, -26, true); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo.InitializeInstance.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo.InitializeInstance.cs index b16bea46c..0f07fcba9 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo.InitializeInstance.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo.InitializeInstance.cs @@ -34,9 +34,7 @@ public void AlphaFS_DeviceInfo_InitializeInstance_Local_Success() { DeviceInfo_InitializeInstance(false); } - - - + private void DeviceInfo_InitializeInstance(bool isNetwork) { diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumes.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumes.cs index cddedcb1f..e293be18e 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumes.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumes.cs @@ -21,6 +21,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; +using System.Linq; namespace AlphaFS.UnitTest { @@ -30,7 +31,7 @@ public partial class AlphaFS_VolumeTest [TestMethod] - public void AlphaFS_Volume_EnumerateVolumes_Local_Success() + public void AlphaFS_Volume_EnumerateVolumes_And_EnumerateVolumePathNames_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -39,25 +40,45 @@ public void AlphaFS_Volume_EnumerateVolumes_Local_Success() var volumeCount = 0; + var volumes = Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumes().ToList(); - foreach (var volume in Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumes()) + foreach (var volume in volumes) { Console.WriteLine("#{0:000}\tVolume: [{1}]", ++volumeCount, volume); Console.WriteLine(); - - foreach (var displayName in Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumePathNames(volume)) + + Assert.IsTrue(volumes.Any(vol => vol.StartsWith(Alphaleonis.Win32.Filesystem.Path.VolumePrefix + "{") && + + vol.EndsWith("}" + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator)), "Volume path name is not valid, but it is expected."); + + + + + var pathNames = Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumePathNames(volume).ToList(); + + foreach (var displayName in pathNames) { - Console.WriteLine("\t\tVolume points to logcal drive: [{0}]", displayName); + Console.WriteLine("\t\tEnumerateVolumePathNames: Volume points to logcal drive: [{0}]", displayName); Console.WriteLine(); + + + // Volumes don't always have drive letters. + + if (!string.IsNullOrWhiteSpace(displayName)) + Assert.IsTrue(char.IsLetter(displayName[0]) && displayName.EndsWith(Alphaleonis.Win32.Filesystem.Path.VolumeSeparator + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator)); } Console.WriteLine(); + + + if (pathNames.Count == 0) + Assert.Inconclusive("Nothing is enumerated, but it is expected."); } - if (volumeCount == 0) + if (volumes.Count == 0) Assert.Inconclusive("Nothing is enumerated, but it is expected."); } } diff --git a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs index 369d7ad56..44cda4a26 100644 --- a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs +++ b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs @@ -34,17 +34,23 @@ public partial class DriveInfoTest public void DriveInfo_GetDrives_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); - - + + + var driveCount = 0; var drives = Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives().ToList(); foreach (var drive in drives) { - Console.WriteLine("\nLogical Drive: [{0}]", drive.Name); - + Console.WriteLine(); + Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, drive.Name); + UnitTestConstants.Dump(drive, -21); + if (null != drive.PhysicalDriveInfo) + UnitTestConstants.Dump(drive.PhysicalDriveInfo, -23, true); + + if (null != drive.DiskSpaceInfo) UnitTestConstants.Dump(drive.DiskSpaceInfo, -26, true); diff --git a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs index 913e1957c..ab098c8f9 100644 --- a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs +++ b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs @@ -94,8 +94,15 @@ private void DriveInfo_InitializeInstance(bool isNetwork) UnitTestConstants.Dump(actual, -21); - UnitTestConstants.Dump(actual.DiskSpaceInfo, -26); - UnitTestConstants.Dump(actual.VolumeInfo, -26); + + if (null != actual.PhysicalDriveInfo) + UnitTestConstants.Dump(actual.PhysicalDriveInfo, -23, true); + + if (null != actual.DiskSpaceInfo) + UnitTestConstants.Dump(actual.DiskSpaceInfo, -26, true); + + if (null != actual.VolumeInfo) + UnitTestConstants.Dump(actual.VolumeInfo, -26, true); Console.WriteLine(); } diff --git a/AlphaFS/Device/Device.DeviceEnumeration.cs b/AlphaFS/Device/Device.DeviceEnumeration.cs index 30a7b3d51..6b775f26a 100644 --- a/AlphaFS/Device/Device.DeviceEnumeration.cs +++ b/AlphaFS/Device/Device.DeviceEnumeration.cs @@ -35,7 +35,7 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) { - return EnumerateDevicesCore(null, null, deviceGuid); + return EnumerateDevicesCore(null, deviceGuid); } @@ -46,98 +46,87 @@ public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) [SecurityCritical] public static IEnumerable EnumerateDevices(string hostName, DeviceGuid deviceGuid) { - return EnumerateDevicesCore(null, hostName, deviceGuid); + return EnumerateDevicesCore(hostName, deviceGuid); } + + /// [AlphaFS] Enumerates all available devices on the local or remote host. [SecurityCritical] - internal static IEnumerable EnumerateDevicesCore(SafeHandle safeHandle, string hostName, DeviceGuid interfaceGuid, bool getAllProperties = true) + internal static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid interfaceGuid, bool getAllProperties = true) { - SafeCmConnectMachineHandle safeMachineHandle; - var callerHandle = safeHandle != null; - var deviceGuid = new Guid(Utils.GetEnumDescription(interfaceGuid)); - - // 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 deviceGuid = new Guid(Utils.GetEnumDescription(interfaceGuid)); + + + // Start at the "Root" of the device tree of the specified machine. using (safeMachineHandle) + using (var safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref deviceGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.SetupDiGetClassDevsExFlags.Present | NativeMethods.SetupDiGetClassDevsExFlags.DeviceInterface, IntPtr.Zero, hostName, IntPtr.Zero)) { - // Start at the "Root" of the device tree of the specified machine. + 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)); - if (!callerHandle) - safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref deviceGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.SetupDiGetClassDevsExFlags.Present | NativeMethods.SetupDiGetClassDevsExFlags.DeviceInterface, IntPtr.Zero, hostName, IntPtr.Zero); + // Start enumerating device interfaces. - try + do { - uint memberInterfaceIndex = 0; - var interfaceStructSize = Marshal.SizeOf(typeof(NativeMethods.SP_DEVICE_INTERFACE_DATA)); - var dataStructSize = Marshal.SizeOf(typeof(NativeMethods.SP_DEVINFO_DATA)); + var interfaceData = new NativeMethods.SP_DEVICE_INTERFACE_DATA {cbSize = interfaceStructSize}; + var success = NativeMethods.SetupDiEnumDeviceInterfaces(safeHandle, IntPtr.Zero, ref deviceGuid, memberInterfaceIndex++, ref interfaceData); - // Start enumerating device interfaces. - - do + lastError = Marshal.GetLastWin32Error(); + if (!success) { - NativeMethods.IsValidHandle(safeHandle, Marshal.GetLastWin32Error()); - - - var interfaceData = new NativeMethods.SP_DEVICE_INTERFACE_DATA { cbSize = (uint)interfaceStructSize }; - - var success = NativeMethods.SetupDiEnumDeviceInterfaces(safeHandle, IntPtr.Zero, ref deviceGuid, memberInterfaceIndex++, ref interfaceData); + if (lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_NO_MORE_ITEMS) + NativeError.ThrowException(lastError, hostName); - lastError = Marshal.GetLastWin32Error(); - if (!success) - { - if (lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_NO_MORE_ITEMS) - NativeError.ThrowException(lastError, hostName); + break; + } - break; - } + // Create DeviceInfo instance. - // Create DeviceInfo instance. + var diData = new NativeMethods.SP_DEVINFO_DATA {cbSize = dataStructSize}; - var diData = new NativeMethods.SP_DEVINFO_DATA { cbSize = (uint)dataStructSize }; - - var deviceInfo = new DeviceInfo(hostName) - { - ClassGuid = deviceGuid, - DevicePath = GetInterfaceDetails(safeHandle, ref interfaceData, ref diData).DevicePath - }; + var deviceInfo = new DeviceInfo(hostName) + { + ClassGuid = deviceGuid, + DevicePath = GetInterfaceDetails(safeHandle, ref interfaceData, ref diData).DevicePath + }; - if (getAllProperties) - { - SetDeviceProperties(safeHandle, deviceInfo, diData); + if (getAllProperties) + { + SetDeviceProperties(safeHandle, deviceInfo, diData); - deviceInfo.InstanceID = GetDeviceInstanceID(safeMachineHandle, hostName, diData); - } + deviceInfo.InstanceID = GetDeviceInstanceID(safeMachineHandle, hostName, diData); + } - else - SetMinimalDeviceProperties(safeHandle, deviceInfo, diData); + else + SetMinimalDeviceProperties(safeHandle, deviceInfo, diData); - yield return deviceInfo; + yield return deviceInfo; - } while (true); - } - finally - { - // Handle is ours, dispose. - if (!callerHandle && null != safeHandle && !safeHandle.IsClosed) - safeHandle.Close(); - } + } while (true); } } @@ -167,7 +156,7 @@ private static string GetDeviceInstanceID(SafeCmConnectMachineHandle safeMachine // as this functionality has been removed. // http://msdn.microsoft.com/en-us/library/windows/hardware/ff538411%28v=vs.85%29.aspx - lastError = NativeMethods.CM_Get_Device_ID_Ex(diData.DevInst, safeBuffer, (uint)safeBuffer.Capacity, 0, safeMachineHandle); + lastError = NativeMethods.CM_Get_Device_ID_Ex(diData.DevInst, safeBuffer, (uint) safeBuffer.Capacity, 0, safeMachineHandle); if (lastError != Win32Errors.CR_SUCCESS) NativeError.ThrowException(lastError, hostName); diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs index 521665ff3..4457e70e5 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs @@ -31,7 +31,7 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrives() { - foreach (var deviceInfo in EnumerateDevicesCore(null, null, DeviceGuid.Disk, false)) + foreach (var deviceInfo in EnumerateDevicesCore(null, DeviceGuid.Disk, false)) { yield return GetPhysicalDriveInfoCore(null, deviceInfo); } diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs index 4ac53dced..e5bcab4f0 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs @@ -37,7 +37,7 @@ public static partial class Device /// /// /// - /// The drive letter, such as C, D. + /// The drive letter, such as 'C', 'D'. [SecurityCritical] public static PhysicalDriveInfo GetPhysicalDriveInfo(char driveLetter) { @@ -45,14 +45,16 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(char driveLetter) } + + /// Gets the hardware information such as the serial number, Vendor ID, Product ID. /// A instance that represents the physical drive on the Computer. /// /// /// /// - /// - /// + /// The drive letter, such as 'C', 'D'. + /// a instance. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, DeviceInfo deviceInfo) @@ -73,7 +75,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De if (driveLetter.HasValue) - driveNumber = GetPhysicalDriveNumberCore((char)driveLetter); + driveNumber = GetPhysicalDriveNumberCore((char) driveLetter); else if (null != deviceInfo) { @@ -84,12 +86,17 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De if (!driveNumber.HasValue) + { + if (null != safeHandle) + safeHandle.Dispose(); + return null; + } var deviceNumber = driveNumber.Value; - var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, deviceNumber.DeviceNumber.ToString(CultureInfo.InvariantCulture)); - var exceptionPath = string.Format(CultureInfo.InvariantCulture, "Device number: {0}. Drive: {1}", deviceNumber.DeviceNumber.ToString(CultureInfo.InvariantCulture), physicalDrive); + var diskNumber = deviceNumber.DeviceNumber.ToString(CultureInfo.InvariantCulture); + var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, diskNumber); var info = new PhysicalDriveInfo { @@ -120,7 +127,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { PropertyId = 0, // StorageDeviceProperty, from STORAGE_PROPERTY_ID enum. - QueryType = 0, // PropertyStandardQuery, from STORAGE_QUERY_TYPE enum + QueryType = 0 // PropertyStandardQuery, from STORAGE_QUERY_TYPE enum }; @@ -129,23 +136,23 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De var storageDescriptor = safeBuffer.PtrToStructure(0); - info.BusType = (StorageBusType)storageDescriptor.BusType; + info.BusType = (StorageBusType) storageDescriptor.BusType; info.IsRemovable = storageDescriptor.RemovableMedia; info.SupportsCommandQueueing = storageDescriptor.CommandQueueing; - info.VendorID = safeBuffer.PtrToStringAnsi((int)storageDescriptor.VendorIdOffset).Trim(); + info.VendorID = safeBuffer.PtrToStringAnsi((int) storageDescriptor.VendorIdOffset).Trim(); - info.ProductRevision = safeBuffer.PtrToStringAnsi((int)storageDescriptor.ProductRevisionOffset).Trim(); + info.ProductRevision = safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductRevisionOffset).Trim(); // "FriendlyName" usually contains the name as shown in Windows Explorer, so let's use that. info.Name = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.FriendlyName) ? deviceInfo.FriendlyName - : safeBuffer.PtrToStringAnsi((int)storageDescriptor.ProductIdOffset).Trim(); + : safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductIdOffset).Trim(); //info.InstanceID = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.InstanceID) @@ -155,7 +162,8 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De long serial; - if (long.TryParse(safeBuffer.PtrToStringAnsi((int)storageDescriptor.SerialNumberOffset).Trim(), out serial)) + if (long.TryParse(safeBuffer.PtrToStringAnsi((int) storageDescriptor.SerialNumberOffset).Trim(), out serial)) + info.SerialNumber = serial; } @@ -164,11 +172,12 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De { long diskSize; - var success = NativeMethods.DeviceIoControl5(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, IntPtr.Zero, 0, out diskSize, (uint)Marshal.SizeOf(typeof(long)), out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl5(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, IntPtr.Zero, 0, out diskSize, (uint) Marshal.SizeOf(typeof(long)), out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); if (!success) - NativeError.ThrowException(lastError, exceptionPath); + NativeError.ThrowException(lastError, string.Format(CultureInfo.InvariantCulture, "Drive: {0}", physicalDrive)); + info.TotalSize = diskSize; } diff --git a/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs b/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs index def8a766e..250af8fe4 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs @@ -33,7 +33,7 @@ public static partial class Device /// /// /// - /// The logical drive letter, such as C, D. + /// The logical drive letter, such as 'C', 'D'. [SecurityCritical] public static int GetPhysicalDriveNumber(char driveLetter) { @@ -51,7 +51,7 @@ public static int GetPhysicalDriveNumber(char driveLetter) /// /// /// - /// The logical drive letter, such as C, D. + /// The logical drive letter, such as 'C', 'D'. [SecurityCritical] internal static NativeMethods.STORAGE_DEVICE_NUMBER? GetPhysicalDriveNumberCore(char driveLetter) { diff --git a/AlphaFS/Device/Device.cs b/AlphaFS/Device/Device.cs index e6e9a7eb2..3212060a5 100644 --- a/AlphaFS/Device/Device.cs +++ b/AlphaFS/Device/Device.cs @@ -24,7 +24,6 @@ using System.Globalization; using System.Runtime.InteropServices; using System.Security; -using System.Threading; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem @@ -33,10 +32,10 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Device { /// MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384 - internal const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384; + private const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384; /// REPARSE_DATA_BUFFER_HEADER_SIZE = 8 - internal const int REPARSE_DATA_BUFFER_HEADER_SIZE = 8; + private const int REPARSE_DATA_BUFFER_HEADER_SIZE = 8; /// Builds a Device Interface Detail Data structure. @@ -46,11 +45,11 @@ private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetInterfaceDetails { var didd = new NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA { - cbSize = (uint)(IntPtr.Size == 4 ? 6 : 8) + 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 success = NativeMethods.SetupDiGetDeviceInterfaceDetail(safeHandle, ref interfaceData, ref didd, (uint) Marshal.SizeOf(didd), IntPtr.Zero, ref infoData); var lastError = Marshal.GetLastWin32Error(); if (!success) @@ -77,7 +76,7 @@ private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMet { uint regDataType; - var success = NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref infoData, property, out regDataType, safeBuffer, (uint)safeBuffer.Capacity, IntPtr.Zero); + var success = NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref infoData, property, out regDataType, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); @@ -114,7 +113,7 @@ internal static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle s var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); @@ -142,7 +141,7 @@ internal static SafeGlobalMemoryBufferHandle GetDeviceIoData3(SafeFileHandle var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); @@ -162,7 +161,7 @@ private static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandl safeBuffer.Close(); - switch ((uint)lastError) + switch ((uint) lastError) { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: @@ -196,7 +195,7 @@ internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandl var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - var success = NativeMethods.DeviceIoControlAnyObject(safeHandle, controlCode, anyObject, (uint)bufferSize, safeBuffer, (uint)safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoControlAnyObject(safeHandle, controlCode, anyObject, (uint) bufferSize, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/DeviceInfo.cs b/AlphaFS/Device/DeviceInfo.cs index 1697f3056..c466dcee4 100644 --- a/AlphaFS/Device/DeviceInfo.cs +++ b/AlphaFS/Device/DeviceInfo.cs @@ -60,7 +60,7 @@ public DeviceInfo(string host) [SecurityCritical] public IEnumerable EnumerateDevices(DeviceGuid deviceGuid) { - return Device.EnumerateDevicesCore(null, HostName, deviceGuid); + return Device.EnumerateDevicesCore(HostName, deviceGuid); } #endregion // Methods diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs index be595a13c..1bce0faa0 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs @@ -60,6 +60,7 @@ public static IEnumerable EnumerateVolumePathNames(string volumeGuid) { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: + requiredLength *= 2; buffer = new StringBuilder(requiredLength); break; diff --git a/AlphaFS/Filesystem/File Class/File.OpenPhysicalDrive.cs b/AlphaFS/Filesystem/File Class/File.OpenPhysicalDrive.cs index 3d334ef60..cb592cd06 100644 --- a/AlphaFS/Filesystem/File Class/File.OpenPhysicalDrive.cs +++ b/AlphaFS/Filesystem/File Class/File.OpenPhysicalDrive.cs @@ -30,16 +30,14 @@ namespace Alphaleonis.Win32.Filesystem partial class File { - /// - /// - /// - /// + /// Opens a physical device, such as: "\\.\PhysicalDrive0" for access. + /// A instance. /// /// /// /// - /// - /// + /// The path to the physical device, such as: "\\.\PhysicalDrive0". + /// If no elevated access is needed to access the physical device, specify 0 for this parameter. [SecurityCritical] public static SafeFileHandle OpenPhysicalDrive(string path, FileSystemRights fileSystemRights) { diff --git a/CHANGELOG.md b/CHANGELOG.md index 742e24baf..e0ca698d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,7 +45,7 @@ Version vNext (xxxx-xx-xx) - Issue #351: Enable copying of Directory symbolic links. - Issue #353: Modify method `Directory.GetFileSystemEntryInfo` to return `FileSystemEntryInfo` structure for directories supporting also root directories, e.g., `C:\` (Thx besoft) - Issue #354: Add methods `File.GetFileId` and `Directory.GetFileId` to return a unique file identifier. (Thx besoft) -- Issue #357: Added new Windows 10 property: `FILE_DAX_VOLUME` to `VolumeInfo` class. +- Issue #357: Added new Windows 10 property: `DirectAccess` (Win32 `FILE_DAX_VOLUME`) to `VolumeInfo` class. - Issue #360: Add overloaded `Directory.EnumerateDirectories` methods that support `DirectoryEnumerationFilters`. (Thx SignFinder) - Issue #370: Relative path from a full path (Thx QbProg) - Issue #373: Improve method `Directory.CreateDirectory` to allow creating a folder consisting only of spaces. From a46d59ee9f89d37d3527754c51d6425892cfd886 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 30 Jan 2018 13:16:27 +0100 Subject: [PATCH 003/133] Corrected Issue #357 description. (#409) From 358a9a246450d5c9d41e6f020b001573d0d9d5bb Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 30 Jan 2018 14:01:58 +0100 Subject: [PATCH 004/133] Corrected Issue #357 description. (#410) From d46f075b58bab22a589e48eff0e44dd3a6193a4b Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 30 Jan 2018 17:17:23 +0100 Subject: [PATCH 005/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 4 +- .../DriveInfo Class/DriveInfo_GetDrives.cs | 10 ++-- .../DriveInfo_InitializeInstance.cs | 7 +-- .../Device/Device.EnumeratePhysicalDrives.cs | 6 +-- AlphaFS/Device/Device.GetPhysicalDriveInfo.cs | 47 ++++++++----------- .../Device/Device.GetPhysicalDriveNumber.cs | 17 ++++--- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 2 +- AlphaFS/Device/Device.cs | 38 +++++++-------- .../DriveInfo/DriveInfo.GetDeviceInfo.cs | 4 +- AlphaFS/Device/PhysicalDriveInfo.cs | 23 ++++----- .../Volume/Volume.GetVolumeDeviceName.cs | 7 +-- .../Filesystem/Native Other/DISK_EXTENT.cs | 6 +-- .../Native Other/VOLUME_DISK_EXTENTS.cs | 4 +- 13 files changed, 83 insertions(+), 92 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs index 31f40e68c..542e89ab1 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -47,8 +47,8 @@ public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() UnitTestConstants.Dump(drive, -23); - foreach (var volume in drive.Volumes) - UnitTestConstants.Dump(volume, -26, true); + //foreach (var volume in drive.Volumes) + // UnitTestConstants.Dump(volume, -26, true); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs index 44cda4a26..2636bea67 100644 --- a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs +++ b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs @@ -47,12 +47,16 @@ public void DriveInfo_GetDrives_Local_Success() UnitTestConstants.Dump(drive, -21); + if (null != drive.DiskSpaceInfo) + UnitTestConstants.Dump(drive.DiskSpaceInfo, -26, true); + + if (null != drive.PhysicalDriveInfo) UnitTestConstants.Dump(drive.PhysicalDriveInfo, -23, true); + - - if (null != drive.DiskSpaceInfo) - UnitTestConstants.Dump(drive.DiskSpaceInfo, -26, true); + if (null != drive.VolumeInfo) + UnitTestConstants.Dump(drive.VolumeInfo, -26, true); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs index ab098c8f9..25ccdefed 100644 --- a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs +++ b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs @@ -95,15 +95,16 @@ private void DriveInfo_InitializeInstance(bool isNetwork) UnitTestConstants.Dump(actual, -21); - if (null != actual.PhysicalDriveInfo) - UnitTestConstants.Dump(actual.PhysicalDriveInfo, -23, true); - if (null != actual.DiskSpaceInfo) UnitTestConstants.Dump(actual.DiskSpaceInfo, -26, true); + if (null != actual.PhysicalDriveInfo) + UnitTestConstants.Dump(actual.PhysicalDriveInfo, -23, true); + if (null != actual.VolumeInfo) UnitTestConstants.Dump(actual.VolumeInfo, -26, true); + Console.WriteLine(); } } diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs index 4457e70e5..3b285a0d3 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs @@ -20,6 +20,7 @@ */ using System.Collections.Generic; +using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -31,10 +32,7 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrives() { - foreach (var deviceInfo in EnumerateDevicesCore(null, DeviceGuid.Disk, false)) - { - yield return GetPhysicalDriveInfoCore(null, deviceInfo); - } + return EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).OrderBy(disk => disk.DeviceNumber).ThenBy(disk => disk.PartitionNumber); } } } diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs index e5bcab4f0..6ebcb5b58 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs @@ -47,7 +47,7 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(char driveLetter) - /// Gets the hardware information such as the serial number, Vendor ID, Product ID. + /// [AlphaFS] Gets the hardware information such as the serial number, Vendor ID, Product ID. /// A instance that represents the physical drive on the Computer. /// /// @@ -70,37 +70,31 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - SafeFileHandle safeHandle = null; - NativeMethods.STORAGE_DEVICE_NUMBER? driveNumber = null; + var device = driveLetter.HasValue + ? string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", Path.LogicalDrivePrefix, driveLetter.ToString(), Path.VolumeSeparator) - if (driveLetter.HasValue) - driveNumber = GetPhysicalDriveNumberCore((char) driveLetter); + : null != deviceInfo ? deviceInfo.DevicePath : null; - else if (null != deviceInfo) - { - safeHandle = File.OpenPhysicalDrive(deviceInfo.DevicePath, desiredAccess); - driveNumber = GetStorageDeviceDriveNumber(safeHandle, deviceInfo.DevicePath); - } + if (null == device) + return null; - if (!driveNumber.HasValue) - { - if (null != safeHandle) - safeHandle.Dispose(); + SafeFileHandle safeHandle; + NativeMethods.STORAGE_DEVICE_NUMBER? driveNumber; - return null; - } + using (safeHandle = File.OpenPhysicalDrive(device, desiredAccess)) + driveNumber = GetStorageDeviceDriveNumber(safeHandle, device); var deviceNumber = driveNumber.Value; - var diskNumber = deviceNumber.DeviceNumber.ToString(CultureInfo.InvariantCulture); - var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, diskNumber); + var diskNumber = deviceNumber.DeviceNumber; + var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, diskNumber.ToString(CultureInfo.InvariantCulture)); var info = new PhysicalDriveInfo { - DeviceNumber = deviceNumber.DeviceNumber, + DeviceNumber = diskNumber, PartitionNumber = deviceNumber.PartitionNumber }; @@ -114,13 +108,9 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De { Console.WriteLine(ex.Message); } + - - if (null == safeHandle) - safeHandle = File.OpenPhysicalDrive(physicalDrive, desiredAccess); - - - using (safeHandle) + using (safeHandle = File.OpenPhysicalDrive(physicalDrive, desiredAccess)) { uint bytesReturned; @@ -143,12 +133,12 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De info.SupportsCommandQueueing = storageDescriptor.CommandQueueing; - info.VendorID = safeBuffer.PtrToStringAnsi((int) storageDescriptor.VendorIdOffset).Trim(); + //info.VendorID = safeBuffer.PtrToStringAnsi((int) storageDescriptor.VendorIdOffset).Trim(); info.ProductRevision = safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductRevisionOffset).Trim(); - // "FriendlyName" usually contains the name as shown in Windows Explorer, so let's use that. + // "FriendlyName" usually contains a more complete name, as shown in Windows Explorer. info.Name = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.FriendlyName) ? deviceInfo.FriendlyName @@ -160,6 +150,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De // : string.Empty; + // Retrieve the device's hardware serial number. long serial; if (long.TryParse(safeBuffer.PtrToStringAnsi((int) storageDescriptor.SerialNumberOffset).Trim(), out serial)) @@ -184,7 +175,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De } - // "FriendlyName" usually contains the name as shown in Windows Explorer, so let's use that. + // "FriendlyName" usually contains a more complete name, as shown in Windows Explorer. if (null == deviceInfo) SetDeviceFriendlyName(info); diff --git a/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs b/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs index 250af8fe4..e6ff62fca 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs @@ -22,6 +22,7 @@ using System; using System.Globalization; using System.Security; +using System.Security.AccessControl; namespace Alphaleonis.Win32.Filesystem { @@ -55,27 +56,29 @@ public static int GetPhysicalDriveNumber(char driveLetter) [SecurityCritical] internal static NativeMethods.STORAGE_DEVICE_NUMBER? GetPhysicalDriveNumberCore(char driveLetter) { - if (!char.IsLetter(driveLetter)) + var drive = driveLetter.ToString(CultureInfo.InvariantCulture) + Path.VolumeSeparator; + + if (!Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath)) throw new ArgumentException(Resources.Argument_must_be_a_drive_letter_from_a_z, "driveLetter"); // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. - const int dwDesiredAccess = 0; + const int desiredAccess = 0; // Requires elevation. - //const FileSystemRights dwDesiredAccess = FileSystemRights.Read | FileSystemRights.Write; + //const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; - //const bool elevatedAccess = (dwDesiredAccess & FileSystemRights.Read) != 0 && (dwDesiredAccess & FileSystemRights.Write) != 0; + //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (dwDesiredAccess & FileSystemRights.Write) != 0; - var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", Path.LogicalDrivePrefix, driveLetter.ToString(), Path.VolumeSeparator); + var logicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.LogicalDrivePrefix, drive); - using (var safeHandle = File.OpenPhysicalDrive(physicalDrive, dwDesiredAccess)) + using (var safeHandle = File.OpenPhysicalDrive(logicalDrive, desiredAccess)) - return GetStorageDeviceDriveNumber(safeHandle, physicalDrive); + return GetStorageDeviceDriveNumber(safeHandle, logicalDrive); } } } diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index 372d2d1d5..25adf6651 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -39,7 +39,7 @@ public static void GetVolumeDiskExtents(string physicalDrive, FileSystemRights d { var structure = GetVolumeDiskExtentsCore(physicalDrive, desiredAccess); - Console.WriteLine("{0}: DiskNumber {1} ExtentLength {2} StartingOffset {3}", physicalDrive, structure.Extents[0].DiskNumber, structure.Extents[0].ExtentLength, structure.Extents[0].StartingOffset); + //Console.WriteLine("{0}: NumberOfDiskExtents: {1}", physicalDrive, structure.NumberOfDiskExtents); } diff --git a/AlphaFS/Device/Device.cs b/AlphaFS/Device/Device.cs index 3212060a5..bb454ebea 100644 --- a/AlphaFS/Device/Device.cs +++ b/AlphaFS/Device/Device.cs @@ -58,16 +58,7 @@ private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetInterfaceDetails return didd; } - - - [SecurityCritical] - private static NativeMethods.STORAGE_DEVICE_NUMBER GetStorageDeviceDriveNumber(SafeFileHandle safeHandle, string path) - { - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, path)) - - return safeBuffer.PtrToStructure(0); - } - + [SecurityCritical] private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum property) @@ -100,7 +91,7 @@ private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMet [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] - internal static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string path, int size = -1) + private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) { NativeMethods.IsValidHandle(safeHandle); @@ -121,14 +112,14 @@ internal static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle s return safeBuffer; - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, path); + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); } } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] - internal static SafeGlobalMemoryBufferHandle GetDeviceIoData3(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string path, int size = -1) + private static SafeGlobalMemoryBufferHandle GetDeviceIoData3(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) { NativeMethods.IsValidHandle(safeHandle); @@ -149,13 +140,13 @@ internal static SafeGlobalMemoryBufferHandle GetDeviceIoData3(SafeFileHandle return safeBuffer; - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, path); + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); } } [SecurityCritical] - private static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandle safeBuffer, int bufferSize, string path) + private static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandle safeBuffer, int bufferSize, string pathForException) { if (null != safeBuffer && !safeBuffer.IsClosed) safeBuffer.Close(); @@ -165,12 +156,12 @@ private static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandl { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: - bufferSize = 2 * bufferSize; + bufferSize *= 2; break; default: - NativeMethods.IsValidHandle(safeBuffer, lastError, string.Format(CultureInfo.InvariantCulture, "Buffer size: {0}. Path: {1}", bufferSize.ToString(CultureInfo.InvariantCulture), path)); + NativeMethods.IsValidHandle(safeBuffer, lastError, string.Format(CultureInfo.InvariantCulture, "Buffer size: {0}. Path: {1}", bufferSize.ToString(CultureInfo.InvariantCulture), pathForException)); break; } @@ -179,10 +170,19 @@ private static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandl } + [SecurityCritical] + private static NativeMethods.STORAGE_DEVICE_NUMBER GetStorageDeviceDriveNumber(SafeFileHandle safeHandle, string pathForException) + { + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, pathForException)) + + return safeBuffer.PtrToStructure(0); + } + + /// Invokes InvokeIoControl with the specified input and specified size. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] - internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string path, int size = -1) + private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string pathForException, int size = -1) { NativeMethods.IsValidHandle(safeHandle); @@ -204,7 +204,7 @@ internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandl return safeBuffer; - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, path); + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); } } diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs index 019127990..1225ba935 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs @@ -119,9 +119,7 @@ private object GetDeviceInfo(int type, int mode) case 4: if (mode == 0) { - return IsUnc - ? null - : (_physicalDriveInfo ?? (_physicalDriveInfo = Device.GetPhysicalDriveInfoCore(_name[0], null))); + return IsUnc ? null : (_physicalDriveInfo ?? (_physicalDriveInfo = Device.GetPhysicalDriveInfoCore(_name[0], null))); } return null; diff --git a/AlphaFS/Device/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo.cs index e4fb0875b..c52a6a756 100644 --- a/AlphaFS/Device/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo.cs @@ -41,6 +41,7 @@ public sealed class PhysicalDriveInfo /// Initializes a PhysicalDriveInfo instance. public PhysicalDriveInfo() { + PartitionNumber = -1; SerialNumber = -1; TotalSize = -1; } @@ -96,19 +97,19 @@ public string Name public long TotalSize { get; internal set; } - /// The Vendor ID of the physical drive. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] - public string VendorID - { - get { return !Utils.IsNullOrWhiteSpace(_vendorID) ? _vendorID : string.Empty; } + ///// The Vendor ID of the physical drive. + //[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] + //public string VendorID + //{ + // get { return !Utils.IsNullOrWhiteSpace(_vendorID) ? _vendorID : string.Empty; } - internal set - { - // SanDisk X400 M.2 2280 256GB reports VendorID as: "(" + // internal set + // { + // // SanDisk X400 M.2 2280 256GB reports VendorID as: "(" - _vendorID = null != value && value.Length > 1 ? value : string.Empty; - } - } + // _vendorID = null != value && value.Length > 1 ? value : string.Empty; + // } + //} /// The Volumes located on the physical drive. diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs index 3168b432c..f71cc697a 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs @@ -70,12 +70,7 @@ public static string GetVolumeDeviceName(string volumeName) // Check for Logical Drives: C:, D:, ... else - { - // Don't use char.IsLetter() here as that can be misleading. - // The only valid drive letters are: a-z and A-Z. - var c = volumeName[0]; - doQueryDos = volumeName[1] == Path.VolumeSeparatorChar && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'); - } + doQueryDos = Path.IsLogicalDriveCore(volumeName, PathFormat.LongFullPath); if (doQueryDos) diff --git a/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs b/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs index 252e331e6..b3a977183 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs @@ -26,11 +26,11 @@ namespace Alphaleonis.Win32.Filesystem internal static partial class NativeMethods { /// Represents a disk extent. - /// MSDN: http://msdn.microsoft.com/en-us/library/aa363968(v=vs.85).aspx - [StructLayout(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct DISK_EXTENT { - /// The number of the disk that contains this extent. This is the same number that is used to construct the name of the disk, for example, the X in "\\?\PhysicalDriveX" or "\\?\HarddiskX". + /// The number of the disk that contains this extent. This is the same number that is used to construct the name of the disk, + /// for example, the X in "\\.\PhysicalDriveX" or "\\?\HarddiskX". public int DiskNumber; /// The offset from the beginning of the disk to the extent, in bytes. diff --git a/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs b/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs index a9e04d3c1..a38259ed4 100644 --- a/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs +++ b/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs @@ -30,10 +30,10 @@ internal static partial class NativeMethods internal struct VOLUME_DISK_EXTENTS { /// The number of disks in the volume (a volume can span multiple disks). - public uint NumberOfDiskExtents; + public readonly uint NumberOfDiskExtents; /// An array of structures. - [MarshalAs(UnmanagedType.ByValArray)] public DISK_EXTENT[] Extents; + [MarshalAs(UnmanagedType.ByValArray)] public readonly DISK_EXTENT[] Extents; } } } From bae13a256edb125f2fe09a8dfe95f00c1e33f520 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 30 Jan 2018 17:21:54 +0100 Subject: [PATCH 006/133] Corrected Issue #357 description. (#411) From cd224aecd01e3e0ffb9c6d3d44fbc6d5a5c2c289 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 30 Jan 2018 19:17:02 +0100 Subject: [PATCH 007/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 6 +- ...numeratePhysicalDrivesFromLogicalDrives.cs | 57 +++++++++++++ ...vice.EnumeratePhysicalDrivesFromVolumes.cs | 57 +++++++++++++ .../AlphaFS.VolumeTest.cs | 4 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 2 + AlphaFS/AlphaFS.csproj | 5 +- .../Device/Device.EnumeratePhysicalDrives.cs | 2 +- ...numeratePhysicalDrivesFromLogicalDrives.cs | 38 +++++++++ ...vice.EnumeratePhysicalDrivesFromVolumes.cs | 38 +++++++++ AlphaFS/Device/Device.GetPhysicalDriveInfo.cs | 67 +++++++++------ .../Device/Device.GetPhysicalDriveNumber.cs | 84 ------------------- AlphaFS/Device/Device.cs | 2 + .../DriveInfo.EnumerateLogicalDrives.cs | 2 +- .../DriveInfo/DriveInfo.GetDeviceInfo.cs | 2 +- AlphaFS/Device/DriveInfo/DriveInfo.cs | 18 ++-- 15 files changed, 253 insertions(+), 131 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs create mode 100644 AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs create mode 100644 AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs delete mode 100644 AlphaFS/Device/Device.GetPhysicalDriveNumber.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs index 542e89ab1..2adcdf1af 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -42,15 +42,11 @@ public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() foreach (var drive in drives) { Console.WriteLine(); - Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]", ++driveCount, drive); + Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]", ++driveCount, drive.Name); UnitTestConstants.Dump(drive, -23); - //foreach (var volume in drive.Volumes) - // UnitTestConstants.Dump(volume, -26, true); - - Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs new file mode 100644 index 000000000..0ca92416e --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs @@ -0,0 +1,57 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_DeviceTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_EnumeratePhysicalDrivesFromLogicalDrives_Local_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + + var driveCount = 0; + var drives = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDrivesFromLogicalDrives().ToList(); + + foreach (var drive in drives) + { + Console.WriteLine(); + Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, drive.Name); + + UnitTestConstants.Dump(drive, -23); + + + Console.WriteLine(); + } + + + Assert.IsTrue(drives.Count > 0); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs new file mode 100644 index 000000000..f2162ce8a --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs @@ -0,0 +1,57 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_DeviceTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_EnumeratePhysicalDrivesFromVolumes_Local_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + + var volumeCount = 0; + var volumes = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDrivesFromVolumes().ToList(); + + foreach (var drive in volumes) + { + Console.WriteLine(); + Console.WriteLine("#{0:000}\tVolume: [{1}]", ++volumeCount, drive.Name); + + UnitTestConstants.Dump(drive, -23); + + + Console.WriteLine(); + } + + + Assert.IsTrue(volumes.Count > 0); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.VolumeTest.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.VolumeTest.cs index dcee2718d..365f1deee 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.VolumeTest.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.VolumeTest.cs @@ -111,7 +111,7 @@ private void DumpGetDriveNameForNtDeviceName(bool isLocal) foreach (var dosDev in Volume.QueryDosDevice(tempPath)) { - Console.WriteLine("#{0:000}\tInput Path : [{1}]", ++cnt, dosDev); + Console.WriteLine("#{0:000}\tInput Path : [{1}]", ++cnt, dosDev); var result = Volume.GetDriveNameForNtDeviceName(dosDev); Console.WriteLine("\tGetDriveNameForNtDeviceName() : [{0}]", result ?? "null"); @@ -140,7 +140,7 @@ private void DumpGetUniqueVolumeNameForPath(bool isLocal) { var tempPath = isLocal ? drive : Path.LocalToUnc(drive); - Console.WriteLine("#{0:000}\tInput Path : [{1}]", ++cnt, tempPath); + Console.WriteLine("#{0:000}\tInput Path : [{1}]", ++cnt, tempPath); var result = Volume.GetUniqueVolumeNameForPath(tempPath); Console.WriteLine("\tGetUniqueVolumeNameForPath(): [{0}]", result ?? "null"); diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 7cc3fc03d..94d017b0c 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -148,6 +148,8 @@ + + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index e7b8b541d..dd455feb9 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -196,8 +196,9 @@ True + + - @@ -612,7 +613,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs index 3b285a0d3..f37864d2d 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs @@ -32,7 +32,7 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrives() { - return EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).OrderBy(disk => disk.DeviceNumber).ThenBy(disk => disk.PartitionNumber); + return EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).OrderBy(disk => disk.DeviceNumber); } } } diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs new file mode 100644 index 000000000..673ffd322 --- /dev/null +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs @@ -0,0 +1,38 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Linq; +using System.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + /// [AlphaFS] Enumerates the drive names of all physical drives on the Computer. + /// An IEnumerable of type that represents the physical drives on the Computer. + [SecurityCritical] + public static IEnumerable EnumeratePhysicalDrivesFromLogicalDrives() + { + return DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(drive => GetPhysicalDriveInfoCore(drive.Name, null)); + } + } +} diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs new file mode 100644 index 000000000..fe254a7e3 --- /dev/null +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs @@ -0,0 +1,38 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Linq; +using System.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + /// [AlphaFS] Enumerates the drive names of all physical drives on the Computer. + /// An IEnumerable of type that represents the physical drives on the Computer. + [SecurityCritical] + public static IEnumerable EnumeratePhysicalDrivesFromVolumes() + { + return EnumerateDevicesCore(null, DeviceGuid.Volume, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).OrderBy(disk => disk.DeviceNumber).ThenBy(disk => disk.PartitionNumber); + } + } +} diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs index 6ebcb5b58..39f9af6eb 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs @@ -37,11 +37,11 @@ public static partial class Device /// /// /// - /// The drive letter, such as 'C', 'D'. + /// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z'. A null value is not valid. [SecurityCritical] - public static PhysicalDriveInfo GetPhysicalDriveInfo(char driveLetter) + public static PhysicalDriveInfo GetPhysicalDriveInfo(string driveName) { - return GetPhysicalDriveInfoCore(driveLetter, null); + return GetPhysicalDriveInfoCore(driveName, null); } @@ -53,16 +53,16 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(char driveLetter) /// /// /// - /// The drive letter, such as 'C', 'D'. + /// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z'. A null value is not valid. /// a instance. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, DeviceInfo deviceInfo) + internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, DeviceInfo deviceInfo) { // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. - //const int dwDesiredAccess = 0; + //const int desiredAccess = 0; // Requires elevation for: TotalNumberOfBytes const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; @@ -70,45 +70,60 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(char? driveLetter, De const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - var device = driveLetter.HasValue + var hasDeviceInfo = null != deviceInfo; + if (!hasDeviceInfo) + { + if (Utils.IsNullOrWhiteSpace(driveName)) + throw new ArgumentNullException("driveName"); + + driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); - ? string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", Path.LogicalDrivePrefix, driveLetter.ToString(), Path.VolumeSeparator) + if (!Path.IsLogicalDriveCore(driveName, PathFormat.LongFullPath)) + throw new ArgumentException(Resources.Argument_must_be_a_drive_letter_from_a_z, "driveName"); - : null != deviceInfo ? deviceInfo.DevicePath : null; + driveName = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.LogicalDrivePrefix, driveName); + } - if (null == device) + var pathToDevice = Path.RemoveTrailingDirectorySeparator(hasDeviceInfo ? deviceInfo.DevicePath : driveName); + + if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; SafeFileHandle safeHandle; - NativeMethods.STORAGE_DEVICE_NUMBER? driveNumber; + NativeMethods.STORAGE_DEVICE_NUMBER? storageDevice; - using (safeHandle = File.OpenPhysicalDrive(device, desiredAccess)) - driveNumber = GetStorageDeviceDriveNumber(safeHandle, device); + // No elevation needed. - var deviceNumber = driveNumber.Value; - var diskNumber = deviceNumber.DeviceNumber; - var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, diskNumber.ToString(CultureInfo.InvariantCulture)); + using (safeHandle = File.OpenPhysicalDrive(pathToDevice, 0)) + storageDevice = GetStorageDeviceDriveNumber(safeHandle, pathToDevice); + + + var device = storageDevice.Value; + var diskNumber = device.DeviceNumber; + + var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, diskNumber.ToString(CultureInfo.InvariantCulture)); + var info = new PhysicalDriveInfo { DeviceNumber = diskNumber, - PartitionNumber = deviceNumber.PartitionNumber + PartitionNumber = device.PartitionNumber }; - try - { - GetVolumeDiskExtents(physicalDrive, desiredAccess); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - + //try + //{ + // GetVolumeDiskExtents(physicalDrive, desiredAccess); + //} + //catch (Exception ex) + //{ + // Console.WriteLine(ex.Message); + //} + using (safeHandle = File.OpenPhysicalDrive(physicalDrive, desiredAccess)) { diff --git a/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs b/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs deleted file mode 100644 index e6ff62fca..000000000 --- a/AlphaFS/Device/Device.GetPhysicalDriveNumber.cs +++ /dev/null @@ -1,84 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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.Security; -using System.Security.AccessControl; - -namespace Alphaleonis.Win32.Filesystem -{ - public static partial class Device - { - /// [AlphaFS] Gets the physical drive number that is related to the logical drive. - /// The physical drive number that is related to the logical drive, or -1 when the logical drive is a mapped network drive or CDRom. - /// - /// - /// - /// - /// The logical drive letter, such as 'C', 'D'. - [SecurityCritical] - public static int GetPhysicalDriveNumber(char driveLetter) - { - var info = GetPhysicalDriveInfoCore(driveLetter, null); - - return null != info ? info.DeviceNumber : -1; - } - - - - - /// Gets the physical drive number that is related to the logical drive. - /// The physical drive number that is related to the logical drive, or -1 when the logical drive is a mapped network drive or CDRom. - /// - /// - /// - /// - /// The logical drive letter, such as 'C', 'D'. - [SecurityCritical] - internal static NativeMethods.STORAGE_DEVICE_NUMBER? GetPhysicalDriveNumberCore(char driveLetter) - { - var drive = driveLetter.ToString(CultureInfo.InvariantCulture) + Path.VolumeSeparator; - - if (!Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath)) - throw new ArgumentException(Resources.Argument_must_be_a_drive_letter_from_a_z, "driveLetter"); - - - // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes - // without accessing that file or device, even if GENERIC_READ access would have been denied. - // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. - const int desiredAccess = 0; - - // Requires elevation. - //const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; - - //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (dwDesiredAccess & FileSystemRights.Write) != 0; - - - var logicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.LogicalDrivePrefix, drive); - - - using (var safeHandle = File.OpenPhysicalDrive(logicalDrive, desiredAccess)) - - return GetStorageDeviceDriveNumber(safeHandle, logicalDrive); - } - } -} diff --git a/AlphaFS/Device/Device.cs b/AlphaFS/Device/Device.cs index bb454ebea..78851be49 100644 --- a/AlphaFS/Device/Device.cs +++ b/AlphaFS/Device/Device.cs @@ -250,6 +250,8 @@ private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo //deviceInfo.DeviceType = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceType); deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); + + //deviceInfo.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.PhysicalDeviceObjectName); } diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs index 88887f724..846f12f4e 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs @@ -80,7 +80,7 @@ internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvir } var result = new string[count]; - char[] root = { 'A', Path.VolumeSeparatorChar }; + char[] root = {'A', Path.VolumeSeparatorChar}; drives = lastError; count = 0; diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs index 1225ba935..c3d7b9c05 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs @@ -119,7 +119,7 @@ private object GetDeviceInfo(int type, int mode) case 4: if (mode == 0) { - return IsUnc ? null : (_physicalDriveInfo ?? (_physicalDriveInfo = Device.GetPhysicalDriveInfoCore(_name[0], null))); + return IsUnc ? null : (_physicalDriveInfo ?? (_physicalDriveInfo = Device.GetPhysicalDriveInfoCore(_name, null))); } return null; diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.cs index c9176a258..fb11cded0 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.cs @@ -118,7 +118,7 @@ public long AvailableFreeSpace /// Use DriveFormat to determine what formatting a drive uses. public string DriveFormat { - get { return (string)GetDeviceInfo(0, 1); } + get { return (string) GetDeviceInfo(0, 1); } } @@ -130,7 +130,7 @@ public string DriveFormat /// public DriveType DriveType { - get { return (DriveType)GetDeviceInfo(0, 3); } + get { return (DriveType) GetDeviceInfo(0, 3); } } @@ -164,7 +164,7 @@ public string Name /// A DirectoryInfo object that contains the root directory of the drive. public DirectoryInfo RootDirectory { - get { return (DirectoryInfo)GetDeviceInfo(2, 0); } + get { return (DirectoryInfo) GetDeviceInfo(2, 0); } } @@ -204,7 +204,7 @@ public long TotalSize /// public string VolumeLabel { - get { return (string)GetDeviceInfo(0, 2); } + get { return (string) GetDeviceInfo(0, 2); } set { Volume.SetVolumeLabel(_name, value); } } @@ -227,7 +227,7 @@ public DiskSpaceInfo DiskSpaceInfo /// [AlphaFS] The MS-DOS device name. public string DosDeviceName { - get { return (string)GetDeviceInfo(1, 0); } + get { return (string) GetDeviceInfo(1, 0); } } @@ -265,7 +265,7 @@ public bool IsVolume /// A object that contains information of the physical drive. public PhysicalDriveInfo PhysicalDriveInfo { - get { return (PhysicalDriveInfo)GetDeviceInfo(4, 0); } + get { return (PhysicalDriveInfo) GetDeviceInfo(4, 0); } } @@ -273,7 +273,7 @@ public PhysicalDriveInfo PhysicalDriveInfo /// A object that contains file system volume information of the drive. public VolumeInfo VolumeInfo { - get { return (VolumeInfo)GetDeviceInfo(0, 0); } + get { return (VolumeInfo) GetDeviceInfo(0, 0); } } #endregion // Properties @@ -284,11 +284,11 @@ public VolumeInfo VolumeInfo #region .NET /// Retrieves the drive names of all logical drives on the Computer. - /// An array of type that represents the logical drives on the Computer. + /// An array of type that represents the logical drives on the Computer. [SecurityCritical] public static DriveInfo[] GetDrives() { - return EnumerateLogicalDrivesCore(false, false).ToArray(); + return EnumerateLogicalDrivesCore(false, false).OrderBy(drive => drive.Name).ToArray(); } From 0a868410e685ae10258d1fc8e79a27a554224603 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 30 Jan 2018 23:15:00 +0100 Subject: [PATCH 008/133] Code improvement, work in progress. --- .../DriveInfo Class/DriveInfo_GetDrives.cs | 4 +- .../DriveInfo_InitializeInstance.cs | 4 +- AlphaFS/AlphaFS.csproj | 4 +- .../Device/Device.EnumeratePhysicalDrives.cs | 8 +- ...numeratePhysicalDrivesFromLogicalDrives.cs | 8 +- ...vice.EnumeratePhysicalDrivesFromVolumes.cs | 8 +- AlphaFS/Device/Device.GetPhysicalDriveInfo.cs | 81 +++++++++++-------- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 3 +- .../Device.OpenPhysicalDrive.cs} | 4 +- AlphaFS/Device/Device.cs | 18 ++++- .../DriveInfo.EnumerateLogicalDrives.cs | 14 ++-- .../DriveInfo/DriveInfo.GetDeviceInfo.cs | 16 ++-- .../DriveInfo/DriveInfo.GetFreeDriveLetter.cs | 2 +- AlphaFS/Device/DriveInfo/DriveInfo.cs | 20 ++--- 14 files changed, 117 insertions(+), 77 deletions(-) rename AlphaFS/{Filesystem/File Class/File.OpenPhysicalDrive.cs => Device/Device.OpenPhysicalDrive.cs} (90%) diff --git a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs index 2636bea67..1a0474450 100644 --- a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs +++ b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs @@ -51,8 +51,8 @@ public void DriveInfo_GetDrives_Local_Success() UnitTestConstants.Dump(drive.DiskSpaceInfo, -26, true); - if (null != drive.PhysicalDriveInfo) - UnitTestConstants.Dump(drive.PhysicalDriveInfo, -23, true); + //if (null != drive.PhysicalDriveInfo) + // UnitTestConstants.Dump(drive.PhysicalDriveInfo, -23, true); if (null != drive.VolumeInfo) diff --git a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs index 25ccdefed..57eca578a 100644 --- a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs +++ b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs @@ -98,8 +98,8 @@ private void DriveInfo_InitializeInstance(bool isNetwork) if (null != actual.DiskSpaceInfo) UnitTestConstants.Dump(actual.DiskSpaceInfo, -26, true); - if (null != actual.PhysicalDriveInfo) - UnitTestConstants.Dump(actual.PhysicalDriveInfo, -23, true); + //if (null != actual.PhysicalDriveInfo) + // UnitTestConstants.Dump(actual.PhysicalDriveInfo, -23, true); if (null != actual.VolumeInfo) UnitTestConstants.Dump(actual.VolumeInfo, -26, true); diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index dd455feb9..8b16e38e0 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -237,7 +237,7 @@ - + @@ -613,7 +613,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs index f37864d2d..ca03d65eb 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs @@ -32,7 +32,13 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrives() { - return EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).OrderBy(disk => disk.DeviceNumber); + return EnumerateDevicesCore(null, DeviceGuid.Disk, false) + + .Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)) + + .Where(physicalDrive => null != physicalDrive) + + .OrderBy(disk => disk.DeviceNumber).ThenBy(disk => disk.PartitionNumber); } } } diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs index 673ffd322..1adcca4dd 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs @@ -32,7 +32,13 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrivesFromLogicalDrives() { - return DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(drive => GetPhysicalDriveInfoCore(drive.Name, null)); + return DriveInfo.EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName) + + .Select(driveName => GetPhysicalDriveInfoCore(driveName, null)) + + .Where(physicalDrive => null != physicalDrive) + + .OrderBy(disk => disk.DeviceNumber).ThenBy(disk => disk.PartitionNumber); } } } diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs index fe254a7e3..82b741d99 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs @@ -32,7 +32,13 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrivesFromVolumes() { - return EnumerateDevicesCore(null, DeviceGuid.Volume, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).OrderBy(disk => disk.DeviceNumber).ThenBy(disk => disk.PartitionNumber); + return EnumerateDevicesCore(null, DeviceGuid.Volume, false) + + .Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)) + + .Where(physicalDrive => null != physicalDrive) + + .OrderBy(disk => disk.DeviceNumber).ThenBy(disk => disk.PartitionNumber); } } } diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs index 39f9af6eb..34968bb60 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs @@ -31,13 +31,16 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// [AlphaFS] Gets the hardware information such as the serial number, Vendor ID, Product ID. - /// A instance that represents the physical drive on the Computer. + /// [AlphaFS] Gets the hardware information such as the serial number and Product ID. + /// A instance that represents the physical drive on the Computer or null on error. /// /// /// /// - /// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z'. A null value is not valid. + /// + /// A valid drive path or drive letter suc as: "C:", "D:\". + /// A string is also valid when is set to . + /// [SecurityCritical] public static PhysicalDriveInfo GetPhysicalDriveInfo(string driveName) { @@ -45,16 +48,18 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string driveName) } - - - /// [AlphaFS] Gets the hardware information such as the serial number, Vendor ID, Product ID. - /// A instance that represents the physical drive on the Computer. + /// [AlphaFS] Gets the hardware information such as the serial number and Product ID. + /// A instance that represents the physical drive on the Computer or null on error. /// /// /// /// - /// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z'. A null value is not valid. + /// + /// A valid drive path or drive letter suc as: "C:", "D:\". + /// A string is also valid when is set to . + /// /// a instance. + ///Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, DeviceInfo deviceInfo) @@ -70,22 +75,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - var hasDeviceInfo = null != deviceInfo; - if (!hasDeviceInfo) - { - if (Utils.IsNullOrWhiteSpace(driveName)) - throw new ArgumentNullException("driveName"); - - driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); - - if (!Path.IsLogicalDriveCore(driveName, PathFormat.LongFullPath)) - throw new ArgumentException(Resources.Argument_must_be_a_drive_letter_from_a_z, "driveName"); - - driveName = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.LogicalDrivePrefix, driveName); - } - - - var pathToDevice = Path.RemoveTrailingDirectorySeparator(hasDeviceInfo ? deviceInfo.DevicePath : driveName); + var pathToDevice = ValidateAndGetPathToDevice(driveName, deviceInfo); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; @@ -97,10 +87,14 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev // No elevation needed. - using (safeHandle = File.OpenPhysicalDrive(pathToDevice, 0)) - + using (safeHandle = OpenPhysicalDrive(pathToDevice, 0)) + { storageDevice = GetStorageDeviceDriveNumber(safeHandle, pathToDevice); + if (null == storageDevice) + return null; + } + var device = storageDevice.Value; var diskNumber = device.DeviceNumber; @@ -125,7 +119,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev //} - using (safeHandle = File.OpenPhysicalDrive(physicalDrive, desiredAccess)) + using (safeHandle = OpenPhysicalDrive(physicalDrive, desiredAccess)) { uint bytesReturned; @@ -146,14 +140,11 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev info.IsRemovable = storageDescriptor.RemovableMedia; info.SupportsCommandQueueing = storageDescriptor.CommandQueueing; - - - //info.VendorID = safeBuffer.PtrToStringAnsi((int) storageDescriptor.VendorIdOffset).Trim(); - + info.ProductRevision = safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductRevisionOffset).Trim(); - // "FriendlyName" usually contains a more complete name, as shown in Windows Explorer. + // "FriendlyName" usually contains a more complete name, as seen in Windows Explorer. info.Name = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.FriendlyName) ? deviceInfo.FriendlyName @@ -166,10 +157,9 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev // Retrieve the device's hardware serial number. - long serial; + long serial; if (long.TryParse(safeBuffer.PtrToStringAnsi((int) storageDescriptor.SerialNumberOffset).Trim(), out serial)) - info.SerialNumber = serial; } @@ -190,7 +180,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev } - // "FriendlyName" usually contains a more complete name, as shown in Windows Explorer. + // "FriendlyName" usually contains a more complete name, as seen in Windows Explorer. if (null == deviceInfo) SetDeviceFriendlyName(info); @@ -200,6 +190,27 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev } + private static string ValidateAndGetPathToDevice(string driveName, DeviceInfo deviceInfo) + { + var hasDeviceInfo = null != deviceInfo; + if (!hasDeviceInfo) + { + if (Utils.IsNullOrWhiteSpace(driveName)) + throw new ArgumentNullException("driveName"); + + driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); + + if (!Path.IsLogicalDriveCore(driveName, PathFormat.LongFullPath)) + throw new ArgumentException(Resources.Argument_must_be_a_drive_letter_from_a_z, "driveName"); + + driveName = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.LogicalDrivePrefix, driveName); + } + + + return Path.RemoveTrailingDirectorySeparator(hasDeviceInfo ? deviceInfo.DevicePath : driveName); + } + + [SecurityCritical] private static void SetDeviceFriendlyName(PhysicalDriveInfo info) { diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index 25adf6651..c44016865 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System; using System.Security; using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; @@ -66,7 +65,7 @@ public static void GetVolumeDiskExtents(SafeFileHandle safeHandle, string physic [SecurityCritical] private static NativeMethods.VOLUME_DISK_EXTENTS GetVolumeDiskExtentsCore(string physicalDrive, FileSystemRights desiredAccess) { - using (var safeHandle = File.OpenPhysicalDrive(physicalDrive, desiredAccess)) + using (var safeHandle = OpenPhysicalDrive(physicalDrive, desiredAccess)) using (var safeBuffer = GetDeviceIoData3(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, physicalDrive, 32)) { diff --git a/AlphaFS/Filesystem/File Class/File.OpenPhysicalDrive.cs b/AlphaFS/Device/Device.OpenPhysicalDrive.cs similarity index 90% rename from AlphaFS/Filesystem/File Class/File.OpenPhysicalDrive.cs rename to AlphaFS/Device/Device.OpenPhysicalDrive.cs index cb592cd06..14f450415 100644 --- a/AlphaFS/Filesystem/File Class/File.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/Device.OpenPhysicalDrive.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Filesystem { - partial class File + public static partial class Device { /// Opens a physical device, such as: "\\.\PhysicalDrive0" for access. @@ -41,7 +41,7 @@ partial class File [SecurityCritical] public static SafeFileHandle OpenPhysicalDrive(string path, FileSystemRights fileSystemRights) { - return CreateFileCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Open, fileSystemRights, FileShare.ReadWrite, false, false, PathFormat.LongFullPath); + return File.CreateFileCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Open, fileSystemRights, FileShare.ReadWrite, false, false, PathFormat.LongFullPath); } } } diff --git a/AlphaFS/Device/Device.cs b/AlphaFS/Device/Device.cs index 78851be49..c001d5a10 100644 --- a/AlphaFS/Device/Device.cs +++ b/AlphaFS/Device/Device.cs @@ -108,9 +108,15 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa var lastError = Marshal.GetLastWin32Error(); + if (success) return safeBuffer; + + // Dynamic disk. + if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) + return null; + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); } @@ -136,10 +142,16 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData3(SafeFileHandle s var lastError = Marshal.GetLastWin32Error(); + if (success) return safeBuffer; + // Dynamic disk. + if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) + return null; + + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); } } @@ -171,11 +183,11 @@ private static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandl [SecurityCritical] - private static NativeMethods.STORAGE_DEVICE_NUMBER GetStorageDeviceDriveNumber(SafeFileHandle safeHandle, string pathForException) + private static NativeMethods.STORAGE_DEVICE_NUMBER? GetStorageDeviceDriveNumber(SafeFileHandle safeHandle, string pathForException) { using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, pathForException)) - return safeBuffer.PtrToStructure(0); + return null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?) null; } @@ -198,7 +210,7 @@ private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle var success = NativeMethods.DeviceIoControlAnyObject(safeHandle, controlCode, anyObject, (uint) bufferSize, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); - + if (success) return safeBuffer; diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs index 846f12f4e..ea90e3664 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs @@ -29,11 +29,11 @@ namespace Alphaleonis.Win32.Filesystem public sealed partial class DriveInfo { /// Enumerates the drive names of all logical drives on the Computer. - /// An IEnumerable of type that represents the logical drives on the Computer. + /// An IEnumerable of type that represents the logical drives on the Computer. /// Retrieve logical drives as known by the Environment. /// Retrieve only when accessible (IsReady) logical drives. [SecurityCritical] - internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvironment, bool isReady) + internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvironment, bool isReady) { // Get from Environment. @@ -49,11 +49,11 @@ internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvir if (isReady) { if (File.ExistsCore(null, true, drive, PathFormat.FullPath)) - yield return new DriveInfo(drive); + yield return drive; } else - yield return new DriveInfo(drive); + yield return drive; } yield break; @@ -80,7 +80,7 @@ internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvir } var result = new string[count]; - char[] root = {'A', Path.VolumeSeparatorChar}; + char[] root = { 'A', Path.VolumeSeparatorChar }; drives = lastError; count = 0; @@ -95,12 +95,12 @@ internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvir { // Optionally check Drive .IsReady property. if (File.ExistsCore(null, true, drive, PathFormat.FullPath)) - yield return new DriveInfo(drive); + yield return drive; } else { // Ready or not. - yield return new DriveInfo(drive); + yield return drive; } result[count++] = drive; diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs index c3d7b9c05..383246ef8 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs @@ -115,16 +115,16 @@ private object GetDeviceInfo(int type, int mode) #region Physical Drive - // Physical Drive related. - case 4: - if (mode == 0) - { - return IsUnc ? null : (_physicalDriveInfo ?? (_physicalDriveInfo = Device.GetPhysicalDriveInfoCore(_name, null))); - } + //// Physical Drive related. + //case 4: + // if (mode == 0) + // { + // return IsUnc ? null : (_physicalDriveInfo ?? (_physicalDriveInfo = Device.GetPhysicalDriveInfoCore(_name, null))); + // } - return null; + // return null; - #endregion // Physical Drive + #endregion // Physical Drive } //} //catch diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs index eb992855e..e3c2298ce 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs @@ -44,7 +44,7 @@ public static char GetFreeDriveLetter() [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public static char GetFreeDriveLetter(bool getLastAvailable) { - var freeDriveLetters = "CDEFGHIJKLMNOPQRSTUVWXYZ".Except(EnumerateLogicalDrivesCore(false, false).Select(d => d.Name[0])); + var freeDriveLetters = "CDEFGHIJKLMNOPQRSTUVWXYZ".Except(EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName).Select(driveName => driveName[0])); try { diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.cs index fb11cded0..06fb3207b 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.cs @@ -87,8 +87,8 @@ public DriveInfo(string driveName) _dsi = new DiskSpaceInfo(_name, null, false, true); - // Initiate PhysicalDriveInfo lazyload instance. - _physicalDriveInfo = null; + //// Initiate PhysicalDriveInfo lazyload instance. + //_physicalDriveInfo = null; } #endregion // .NET @@ -261,12 +261,12 @@ public bool IsVolume } - /// [AlphaFS] Contains information about the physical drive. - /// A object that contains information of the physical drive. - public PhysicalDriveInfo PhysicalDriveInfo - { - get { return (PhysicalDriveInfo) GetDeviceInfo(4, 0); } - } + ///// [AlphaFS] Contains information about the physical drive. + ///// A object that contains information of the physical drive. + //public PhysicalDriveInfo PhysicalDriveInfo + //{ + // get { return (PhysicalDriveInfo) GetDeviceInfo(4, 0); } + //} /// [AlphaFS] Contains information about a file system volume. @@ -288,7 +288,7 @@ public VolumeInfo VolumeInfo [SecurityCritical] public static DriveInfo[] GetDrives() { - return EnumerateLogicalDrivesCore(false, false).OrderBy(drive => drive.Name).ToArray(); + return EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName).Select(driveName => new DriveInfo(driveName)).ToArray(); } @@ -306,7 +306,7 @@ public override string ToString() /// [AlphaFS] Refreshes the state of the object. public void Refresh() { - _physicalDriveInfo = null; + //_physicalDriveInfo = null; _volumeInfo.Refresh(); From ebde6a1bdb7bdc9cb01c9f0efa0c8eb255e2afc0 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 31 Jan 2018 12:09:48 +0100 Subject: [PATCH 009/133] -Code improvement, work in progress; -Update unit tests; --- .../AlphaFS_DeviceTest.cs | 2 +- ...lphaFS_Directory_GetFileSystemEntryInfo.cs | 10 +- .../AlphaFS_TimestampsTest.cs | 31 ++++++ .../Directory_GetTimestamps.cs | 3 +- .../Directory_SetTimestamps.cs | 3 +- .../File_GetTimestamps.cs | 3 +- .../File_SetTimestamps.cs | 3 +- ...phaFS.Volume.EnumerateVolumeMountPoints.cs | 2 +- .../AlphaFS.VolumeTest.cs | 3 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 14 +-- ...FS_Directory.DeleteEmptySubdirectories.cs} | 8 +- .../AlphaFS_Directory.IsEmpty.cs} | 19 ++-- .../Directory.GetLogicalDrives.cs | 80 ++++++++++++++++ .../Directory Class/DirectoryTest.cs | 44 +-------- .../DriveInfo Class/DriveInfo_GetDrives.cs | 5 - .../DriveInfo_InitializeInstance.cs | 4 +- AlphaFS/Device/Device.GetPhysicalDriveInfo.cs | 2 + AlphaFS/Device/DiskSpaceInfo.cs | 34 ++++--- .../DriveInfo.EnumerateLogicalDrives.cs | 35 +++---- AlphaFS/Device/DriveInfo/DriveInfo.cs | 17 +++- AlphaFS/Device/PhysicalDriveInfo.cs | 48 +++++++++- .../Device/Volume/Volume.GetDriveFormat.cs | 2 +- .../Volume.GetDriveNameForNtDeviceName.cs | 2 +- .../Volume.GetVolumeGuidForNtDeviceName.cs | 2 +- .../Directory.EnumerateLogicalDrives.cs | 96 ++----------------- .../Directory.GetLogicalDrives.cs | 11 ++- .../Path.GetFinalPathNameByHandle.cs | 6 +- .../Path Class/Path.ValidationAndChecks.cs | 4 +- 28 files changed, 282 insertions(+), 211 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS Timestamps/AlphaFS_TimestampsTest.cs rename AlphaFS.UnitTest/{Directory Class => AlphaFS Timestamps}/Directory_GetTimestamps.cs (99%) rename AlphaFS.UnitTest/{Directory Class => AlphaFS Timestamps}/Directory_SetTimestamps.cs (99%) rename AlphaFS.UnitTest/{File Class => AlphaFS Timestamps}/File_GetTimestamps.cs (99%) rename AlphaFS.UnitTest/{File Class => AlphaFS Timestamps}/File_SetTimestamps.cs (99%) rename AlphaFS.UnitTest/Directory Class/{AlphaFS_Directory_DeleteEmptySubdirectories.cs => Directory.Delete/AlphaFS_Directory.DeleteEmptySubdirectories.cs} (97%) rename AlphaFS.UnitTest/Directory Class/{AlphaFS_Directory_IsEmpty.cs => Directory.Delete/AlphaFS_Directory.IsEmpty.cs} (87%) create mode 100644 AlphaFS.UnitTest/Directory Class/Directory.GetLogicalDrives.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs index 56db976af..7c3e6dd41 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs @@ -23,7 +23,7 @@ namespace AlphaFS.UnitTest { - /// This is a test class for DeviceInfoTest and is intended to contain all Device and DeviceInfo Unit Tests. + /// This is a test class for Device and DeviceInfo and is intended to contain all Device and DeviceInfo Unit Tests. [TestClass] public partial class AlphaFS_DeviceTest { diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_GetFileSystemEntryInfo.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_GetFileSystemEntryInfo.cs index ff8f97e2c..5cb5c162c 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_GetFileSystemEntryInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_GetFileSystemEntryInfo.cs @@ -89,15 +89,15 @@ private void Directory_GetFileSystemEntryInfo_LogicalDrives() UnitTestConstants.PrintUnitTestHeader(false); - var drives = Alphaleonis.Win32.Filesystem.Directory.EnumerateLogicalDrives().ToList(); + var drives = Alphaleonis.Win32.Filesystem.Directory.GetLogicalDrives(); foreach (var drive in drives) { - Console.WriteLine("\nInput Logical Drive: [{0}]", drive.Name); + Console.WriteLine("\nInput Logical Drive: [{0}]", drive); try { - var fsei = Alphaleonis.Win32.Filesystem.Directory.GetFileSystemEntryInfo(drive.Name); + var fsei = Alphaleonis.Win32.Filesystem.Directory.GetFileSystemEntryInfo(drive); UnitTestConstants.Dump(fsei, -19); @@ -106,7 +106,7 @@ private void Directory_GetFileSystemEntryInfo_LogicalDrives() // Fixed local drives should have these attributes. - if (new Alphaleonis.Win32.Filesystem.DriveInfo(drive.Name).DriveType == System.IO.DriveType.Fixed) + if (new Alphaleonis.Win32.Filesystem.DriveInfo(drive).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."); @@ -114,7 +114,7 @@ private void Directory_GetFileSystemEntryInfo_LogicalDrives() Assert.AreEqual(".", fsei.FileName, "The file names are not equal, but are expected to be."); - Assert.AreEqual(drive.Name, fsei.FullPath, "The full paths are not equal, but are expected to be."); + Assert.AreEqual(drive, fsei.FullPath, "The full paths are not equal, but are expected to be."); } catch (Exception ex) { diff --git a/AlphaFS.UnitTest/AlphaFS Timestamps/AlphaFS_TimestampsTest.cs b/AlphaFS.UnitTest/AlphaFS Timestamps/AlphaFS_TimestampsTest.cs new file mode 100644 index 000000000..3ffe7007f --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Timestamps/AlphaFS_TimestampsTest.cs @@ -0,0 +1,31 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace AlphaFS.UnitTest +{ + /// This is a test class for Timestamps and is intended to contain all Timestamps Unit Tests. + [TestClass] + public partial class AlphaFS_TimestampsTest + { + } +} diff --git a/AlphaFS.UnitTest/Directory Class/Directory_GetTimestamps.cs b/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_GetTimestamps.cs similarity index 99% rename from AlphaFS.UnitTest/Directory Class/Directory_GetTimestamps.cs rename to AlphaFS.UnitTest/AlphaFS Timestamps/Directory_GetTimestamps.cs index 47d982c82..c83ea1ef8 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_GetTimestamps.cs +++ b/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_GetTimestamps.cs @@ -26,10 +26,11 @@ namespace AlphaFS.UnitTest { - partial class DirectoryTest + public partial class AlphaFS_TimestampsTest { // Pattern: ___ + [TestMethod] public void Directory_GetXxxTimeXxx_LocalAndNetwork_Success() { diff --git a/AlphaFS.UnitTest/Directory Class/Directory_SetTimestamps.cs b/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_SetTimestamps.cs similarity index 99% rename from AlphaFS.UnitTest/Directory Class/Directory_SetTimestamps.cs rename to AlphaFS.UnitTest/AlphaFS Timestamps/Directory_SetTimestamps.cs index 31978ef94..010ea4699 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_SetTimestamps.cs +++ b/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_SetTimestamps.cs @@ -26,10 +26,11 @@ namespace AlphaFS.UnitTest { - partial class DirectoryTest + public partial class AlphaFS_TimestampsTest { // Pattern: ___ + [TestMethod] public void AlphaFS_Directory_SetTimestampsXxx_LocalAndNetwork_Success() { diff --git a/AlphaFS.UnitTest/File Class/File_GetTimestamps.cs b/AlphaFS.UnitTest/AlphaFS Timestamps/File_GetTimestamps.cs similarity index 99% rename from AlphaFS.UnitTest/File Class/File_GetTimestamps.cs rename to AlphaFS.UnitTest/AlphaFS Timestamps/File_GetTimestamps.cs index e6bd24dfd..877d64773 100644 --- a/AlphaFS.UnitTest/File Class/File_GetTimestamps.cs +++ b/AlphaFS.UnitTest/AlphaFS Timestamps/File_GetTimestamps.cs @@ -26,10 +26,11 @@ namespace AlphaFS.UnitTest { - partial class FileTest + public partial class AlphaFS_TimestampsTest { // Pattern: ___ + [TestMethod] public void File_GetXxxTimeXxx_LocalAndNetwork_Success() { diff --git a/AlphaFS.UnitTest/File Class/File_SetTimestamps.cs b/AlphaFS.UnitTest/AlphaFS Timestamps/File_SetTimestamps.cs similarity index 99% rename from AlphaFS.UnitTest/File Class/File_SetTimestamps.cs rename to AlphaFS.UnitTest/AlphaFS Timestamps/File_SetTimestamps.cs index a7dd84fe0..0d52b43a2 100644 --- a/AlphaFS.UnitTest/File Class/File_SetTimestamps.cs +++ b/AlphaFS.UnitTest/AlphaFS Timestamps/File_SetTimestamps.cs @@ -26,10 +26,11 @@ namespace AlphaFS.UnitTest { - partial class FileTest + public partial class AlphaFS_TimestampsTest { // Pattern: ___ + [TestMethod] public void AlphaFS_File_SetTimestampsXxx_LocalAndNetwork_Success() { diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumeMountPoints.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumeMountPoints.cs index 82d5e5b24..b968c9b7a 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumeMountPoints.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumeMountPoints.cs @@ -44,7 +44,7 @@ public void AlphaFS_Volume_EnumerateVolumeMountPoints_Local_Success() 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)) + foreach (var drive in Alphaleonis.Win32.Filesystem.Directory.GetLogicalDrives()) { try { diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.VolumeTest.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.VolumeTest.cs index 365f1deee..6b7ca67b2 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.VolumeTest.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.VolumeTest.cs @@ -45,8 +45,7 @@ private void DumpGetDriveFormat(bool isLocal) var cnt = 0; - // Get Logical Drives from Environment. - foreach (var drv in Directory.GetLogicalDrives(false, true)) + foreach (var drv in Directory.GetLogicalDrives()) { UnitTestConstants.StopWatcher(true); diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 94d017b0c..c0c870de0 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -171,6 +171,7 @@ + @@ -195,6 +196,7 @@ + @@ -215,12 +217,12 @@ - + - + @@ -231,8 +233,8 @@ - - + + @@ -267,7 +269,7 @@ - + @@ -276,7 +278,7 @@ - + diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory_DeleteEmptySubdirectories.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.DeleteEmptySubdirectories.cs similarity index 97% rename from AlphaFS.UnitTest/Directory Class/AlphaFS_Directory_DeleteEmptySubdirectories.cs rename to AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.DeleteEmptySubdirectories.cs index 50f16d843..33f9665d0 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory_DeleteEmptySubdirectories.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.DeleteEmptySubdirectories.cs @@ -25,10 +25,11 @@ namespace AlphaFS.UnitTest { - partial class DirectoryTest + public partial class Directory_DeleteTest { // Pattern: ___ + [TestMethod] public void AlphaFS_Directory_DeleteEmptySubdirectories_LocalAndNetwork_Success() { @@ -49,6 +50,8 @@ public void AlphaFS_Directory_DeleteEmptySubdirectories_LocalAndNetwork_Success( private void Directory_DeleteEmptySubdirectories(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); + Console.WriteLine(); + var tempPath = System.IO.Path.GetTempPath(); if (isNetwork) @@ -58,7 +61,8 @@ private void Directory_DeleteEmptySubdirectories(bool isNetwork) using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) { var folder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(rootDir.Directory.FullName, "Source Folder")); - Console.WriteLine("\nInput Directory Path: [{0}]", folder.FullName); + + Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); const int maxDepth = 10; diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory_IsEmpty.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.IsEmpty.cs similarity index 87% rename from AlphaFS.UnitTest/Directory Class/AlphaFS_Directory_IsEmpty.cs rename to AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.IsEmpty.cs index afd938cb9..632351109 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory_IsEmpty.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.IsEmpty.cs @@ -25,7 +25,7 @@ namespace AlphaFS.UnitTest { - partial class DirectoryTest + public partial class Directory_DeleteTest { // Pattern: ___ @@ -51,8 +51,10 @@ public void AlphaFS_Directory_IsEmpty_ContainsAFile_IsFalse_LocalAndNetwork_Succ private void Directory_IsEmpty(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); + Console.WriteLine(); + - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -60,12 +62,14 @@ private void Directory_IsEmpty(bool isNetwork) using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) { var folder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(rootDir.Directory.FullName, "Empty Folder")); - Console.WriteLine("\nInput Directory Path: [{0}]", folder.FullName); + + Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); - Assert.IsTrue(Alphaleonis.Win32.Filesystem.Directory.IsEmpty(folder.FullName), "It is expected that the folder is empty."); + Assert.IsTrue(Alphaleonis.Win32.Filesystem.Directory.IsEmpty(folder.FullName), "The directory is not empty, but it is expected."); } + Console.WriteLine(); } @@ -73,8 +77,10 @@ private void Directory_IsEmpty(bool isNetwork) private void Directory_IsEmpty_ContainsAFile_IsFalse(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); + Console.WriteLine(); + - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -82,7 +88,8 @@ private void Directory_IsEmpty_ContainsAFile_IsFalse(bool isNetwork) using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) { var folder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(rootDir.Directory.FullName, "Empty Folder")); - Console.WriteLine("\nInput Directory Path: [{0}]", folder.FullName); + + Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); // Create file and test again. diff --git a/AlphaFS.UnitTest/Directory Class/Directory.GetLogicalDrives.cs b/AlphaFS.UnitTest/Directory Class/Directory.GetLogicalDrives.cs new file mode 100644 index 000000000..d4ebd99a3 --- /dev/null +++ b/AlphaFS.UnitTest/Directory Class/Directory.GetLogicalDrives.cs @@ -0,0 +1,80 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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: ___ + + + [TestMethod] + public void Directory_GetLogicalDrives_LocalAndNetwork_Success() + { + Directory_GetLogicalDrives(false); + Directory_GetLogicalDrives(true); + } + + + private void Directory_GetLogicalDrives(bool isNetwork) + { + UnitTestConstants.PrintUnitTestHeader(isNetwork); + Console.WriteLine(); + + + foreach (var drive in Alphaleonis.Win32.Filesystem.Directory.GetLogicalDrives()) + { + var inputPath = drive; + if (isNetwork) + inputPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(inputPath); + + + Console.WriteLine("Input Directory Path: [{0}]\n", inputPath); + + + try + { + var systemIOCount = System.IO.Directory.GetDirectories(inputPath).Length; + var alphaFSCount = Alphaleonis.Win32.Filesystem.Directory.GetDirectories(inputPath).Length; + + Console.WriteLine("\tSystem.IO directories get: {0:N0}", systemIOCount); + Console.WriteLine("\tAlphaFS directories get : {0:N0}", alphaFSCount); + + + Assert.AreEqual(systemIOCount, alphaFSCount, "No directories get, but it is expected."); + } + catch (Exception ex) + { + var exType = ex.GetType(); + + var gotException = exType == typeof(System.IO.IOException); + + Console.WriteLine("\n\tCaught {0} Exception: [{1}] {2}", gotException ? "EXPECTED" : "UNEXPECTED", exType.Name, ex.Message); + } + } + + Console.WriteLine(); + } + } +} diff --git a/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs b/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs index 4a78d8b2a..63bae0e7d 100644 --- a/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs +++ b/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs @@ -166,35 +166,6 @@ private void DumpEnumerateFileIdBothDirectoryInfo(bool isLocal) - private void DumpGetDrives(bool enumerate) - { - Console.WriteLine("\nIf you are missing drives, please see this topic: https://alphafs.codeplex.com/discussions/397693 \n"); - - var cnt = 0; - UnitTestConstants.StopWatcher(true); - foreach (var actual in enumerate ? Directory.EnumerateLogicalDrives(false, false) : DriveInfo.GetDrives()) - { - Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++cnt, actual.Name); - - if (actual.IsReady && actual.DriveType == DriveType.Fixed) - { - // GetFreeSpaceEx() - Assert.IsTrue(actual.AvailableFreeSpace > 0 && actual.TotalSize > 0 && actual.TotalFreeSpace > 0); - - // GetFreeSpace() - Assert.IsTrue(actual.DiskSpaceInfo.SectorsPerCluster > 0 && actual.DiskSpaceInfo.BytesPerSector > 0 && actual.DiskSpaceInfo.TotalNumberOfClusters > 0); - - // DriveInfo() - Assert.IsTrue(actual.DiskSpaceInfo.ClusterSize > 0 && - !Utils.IsNullOrWhiteSpace(actual.DiskSpaceInfo.TotalSizeUnitSize) && - !Utils.IsNullOrWhiteSpace(actual.DiskSpaceInfo.UsedSpaceUnitSize) && - !Utils.IsNullOrWhiteSpace(actual.DiskSpaceInfo.AvailableFreeSpaceUnitSize)); - } - } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); - } - - private void DumpGetProperties(bool isLocal) { Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); @@ -231,11 +202,8 @@ private bool HasInheritedPermissions(string path) return acl.GetAccessRules(false, true, typeof(SecurityIdentifier)).Count > 0; } - #region .NET - - - + #region .NET [TestMethod] public void Directory_GetDirectoryRoot() @@ -307,8 +275,6 @@ public void Directory_GetDirectoryRoot() Assert.AreEqual(0, errorCnt, "Encountered paths where AlphaFS != System.IO"); } - - [TestMethod] public void Directory_GetFileSystemEntries_LongPathWithPrefix_ShouldReturnCorrectEntries() { @@ -343,13 +309,6 @@ public void Directory_GetFileSystemEntries_LongPathWithoutPrefix_ShouldReturnCor } } - [TestMethod] - public void Directory_GetLogicalDrives() - { - Console.WriteLine("Directory.GetLogicalDrives()"); - - DumpGetDrives(false); - } [TestMethod] public void Directory_GetParent() @@ -407,6 +366,7 @@ public void Directory_GetParent() #endregion // .NET + #region AlphaFS [TestMethod] diff --git a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs index 1a0474450..888d5b072 100644 --- a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs +++ b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs @@ -49,12 +49,7 @@ public void DriveInfo_GetDrives_Local_Success() if (null != drive.DiskSpaceInfo) UnitTestConstants.Dump(drive.DiskSpaceInfo, -26, true); - - - //if (null != drive.PhysicalDriveInfo) - // UnitTestConstants.Dump(drive.PhysicalDriveInfo, -23, true); - if (null != drive.VolumeInfo) UnitTestConstants.Dump(drive.VolumeInfo, -26, true); diff --git a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs index 57eca578a..211a8ec88 100644 --- a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs +++ b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_InitializeInstance.cs @@ -95,12 +95,10 @@ private void DriveInfo_InitializeInstance(bool isNetwork) UnitTestConstants.Dump(actual, -21); + if (null != actual.DiskSpaceInfo) UnitTestConstants.Dump(actual.DiskSpaceInfo, -26, true); - //if (null != actual.PhysicalDriveInfo) - // UnitTestConstants.Dump(actual.PhysicalDriveInfo, -23, true); - if (null != actual.VolumeInfo) UnitTestConstants.Dump(actual.VolumeInfo, -26, true); diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs index 34968bb60..452a157e3 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs @@ -103,6 +103,8 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev var info = new PhysicalDriveInfo { + DriveName = !Utils.IsNullOrWhiteSpace(driveName) ? Path.AddTrailingDirectorySeparator(driveName, false) : null, + DeviceNumber = diskNumber, PartitionNumber = device.PartitionNumber }; diff --git a/AlphaFS/Device/DiskSpaceInfo.cs b/AlphaFS/Device/DiskSpaceInfo.cs index 76945c489..36873a9ce 100644 --- a/AlphaFS/Device/DiskSpaceInfo.cs +++ b/AlphaFS/Device/DiskSpaceInfo.cs @@ -35,44 +35,53 @@ namespace Alphaleonis.Win32.Filesystem [SecurityCritical] public sealed class DiskSpaceInfo { + #region Private Fields + [NonSerialized] private readonly bool _initGetClusterInfo = true; [NonSerialized] private readonly bool _initGetSpaceInfo = true; - [NonSerialized] private readonly CultureInfo _cultureInfo = CultureInfo.CurrentCulture; + [NonSerialized] private readonly CultureInfo _cultureInfo; [NonSerialized] private readonly bool _continueOnAccessError; + #endregion // Private Fields + + + #region Constructors /// Initializes a DiskSpaceInfo instance. - /// 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 + /// 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 /// This is a Lazyloading object; call to populate all properties first before accessing. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] - public DiskSpaceInfo(string drivePath) + public DiskSpaceInfo(string driveName) { - if (Utils.IsNullOrWhiteSpace(drivePath)) - throw new ArgumentNullException("drivePath"); + if (Utils.IsNullOrWhiteSpace(driveName)) + throw new ArgumentNullException("driveName"); - drivePath = drivePath.Length == 1 ? drivePath + Path.VolumeSeparatorChar : Path.GetPathRoot(drivePath, false); + driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); - if (Utils.IsNullOrWhiteSpace(drivePath)) + if (Utils.IsNullOrWhiteSpace(driveName)) throw new ArgumentException(Resources.InvalidDriveLetterArgument, "drivePath"); + _cultureInfo = CultureInfo.CurrentCulture; + + // 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); + DriveName = Path.AddTrailingDirectorySeparator(driveName, false); } /// Initializes a DiskSpaceInfo instance. - /// 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 + /// 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 /// gets both size- and disk cluster information. Get only disk cluster information, Get only size information. /// Refreshes the state of the object. /// suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. [SecurityCritical] - public DiskSpaceInfo(string drivePath, bool? spaceInfoType, bool refresh, bool continueOnException) : this(drivePath) + public DiskSpaceInfo(string driveName, bool? spaceInfoType, bool refresh, bool continueOnException) : this(driveName) { if (spaceInfoType == null) _initGetSpaceInfo = _initGetClusterInfo = true; @@ -89,6 +98,8 @@ public DiskSpaceInfo(string drivePath, bool? spaceInfoType, bool refresh, bool c Refresh(); } + #endregion // Constructors + /// Indicates the amount of available free space on a drive, formatted as percentage. public string AvailableFreeSpacePercent @@ -115,8 +126,7 @@ public long ClusterSize /// Gets the name of a drive. - /// The name of the drive. - /// This property is the name assigned to the drive, such as C:\ or E:\ + /// This property is the name assigned to the drive, such as: "C:\" or "D:\". public string DriveName { get; private set; } diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs index ea90e3664..7bf84d3bb 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs @@ -22,6 +22,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -40,20 +41,20 @@ internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvironm if (fromEnvironment) { var drivesEnv = isReady - ? Environment.GetLogicalDrives().Where(ld => File.ExistsCore(null, true, ld, PathFormat.FullPath)) - : Environment.GetLogicalDrives().Select(ld => ld); + ? Environment.GetLogicalDrives().Where(logicalDrive => File.ExistsCore(null, true, logicalDrive, PathFormat.LongFullPath)) + : Environment.GetLogicalDrives().Select(logicalDrive => logicalDrive); foreach (var drive in drivesEnv) { // Optionally check Drive .IsReady. if (isReady) { - if (File.ExistsCore(null, true, drive, PathFormat.FullPath)) - yield return drive; + if (File.ExistsCore(null, true, drive, PathFormat.LongFullPath)) + yield return Path.AddTrailingDirectorySeparator(drive, false); } else - yield return drive; + yield return Path.AddTrailingDirectorySeparator(drive, false); } yield break; @@ -61,15 +62,16 @@ internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvironm // Get through NativeMethod. + var allDrives = NativeMethods.GetLogicalDrives(); - var lastError = NativeMethods.GetLogicalDrives(); + var lastError = Marshal.GetLastWin32Error(); // MSDN: GetLogicalDrives(): If the function fails, the return value is zero. - if (lastError == Win32Errors.ERROR_SUCCESS) + if (allDrives == Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError); - var drives = lastError; + var drives = allDrives; var count = 0; while (drives != 0) { @@ -80,9 +82,9 @@ internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvironm } var result = new string[count]; - char[] root = { 'A', Path.VolumeSeparatorChar }; + char[] root = {'A', Path.VolumeSeparatorChar}; - drives = lastError; + drives = allDrives; count = 0; while (drives != 0) @@ -94,14 +96,15 @@ internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvironm if (isReady) { // Optionally check Drive .IsReady property. - if (File.ExistsCore(null, true, drive, PathFormat.FullPath)) - yield return drive; + + if (File.ExistsCore(null, true, drive, PathFormat.LongFullPath)) + + yield return Path.AddTrailingDirectorySeparator(drive, false); } + + // Ready or not. else - { - // Ready or not. - yield return drive; - } + yield return Path.AddTrailingDirectorySeparator(drive, false); result[count++] = drive; } diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.cs index 06fb3207b..1078bd615 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.cs @@ -41,7 +41,7 @@ public sealed partial class DriveInfo [NonSerialized] private readonly VolumeInfo _volumeInfo; [NonSerialized] private readonly DiskSpaceInfo _dsi; - [NonSerialized] private PhysicalDriveInfo _physicalDriveInfo; + //[NonSerialized] private PhysicalDriveInfo _physicalDriveInfo; [NonSerialized] private bool _initDsie; [NonSerialized] private readonly string _name; [NonSerialized] private string _dosDeviceName; @@ -114,7 +114,7 @@ public long AvailableFreeSpace } - /// Gets the name of the file system, such as NTFS or FAT32. + /// Gets the name of the file system, such as: "NTFS" or "FAT32". /// Use DriveFormat to determine what formatting a drive uses. public string DriveFormat { @@ -153,7 +153,7 @@ public bool IsReady /// Gets the name of the drive. /// The name of the drive. - /// This property is the name assigned to the drive, such as C:\ or E:\ + /// This property is the name assigned to the drive, such as: "C:\" or "D:\". public string Name { get { return _name; } @@ -283,7 +283,7 @@ public VolumeInfo VolumeInfo #region .NET - /// Retrieves the drive names of all logical drives on the Computer. + /// Retrieves the names of the logical drives on the Computer in the form "drive letter:\". /// An array of type that represents the logical drives on the Computer. [SecurityCritical] public static DriveInfo[] GetDrives() @@ -303,6 +303,15 @@ public override string ToString() #endregion // .NET + /// [AlphaFS] Retrieves the names of the logical drives on the Computer in the form "drive letter:\". + /// An array of type that represents the logical drives on the Computer. + [SecurityCritical] + public static DriveInfo[] GetDrives(bool fromEnvironment, bool isReady) + { + return EnumerateLogicalDrivesCore(fromEnvironment, isReady).OrderBy(driveName => driveName).Select(driveName => new DriveInfo(driveName)).ToArray(); + } + + /// [AlphaFS] Refreshes the state of the object. public void Refresh() { diff --git a/AlphaFS/Device/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo.cs index c52a6a756..53ab0220c 100644 --- a/AlphaFS/Device/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo.cs @@ -23,7 +23,6 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -34,19 +33,52 @@ namespace Alphaleonis.Win32.Filesystem public sealed class PhysicalDriveInfo { [NonSerialized] private string _productID; - [NonSerialized] private string _vendorID; + //[NonSerialized] private string _vendorID; + [NonSerialized] private readonly CultureInfo _cultureInfo; [NonSerialized] private IEnumerable _volumes; + #region Constructors + /// Initializes a PhysicalDriveInfo instance. public PhysicalDriveInfo() { + _cultureInfo = CultureInfo.CurrentCulture; + + PartitionNumber = -1; SerialNumber = -1; TotalSize = -1; } + /// Initializes a PhysicalDriveInfo instance. + /// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z'. + /// This is a Lazyloading object; call to populate all properties first before accessing. + [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] + [SecurityCritical] + public PhysicalDriveInfo(string driveName) : this() + { + 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"); + + + // 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(driveName, false); + } + + #endregion // Constructors + + /// Returns the product ID of the physical drive. /// A string that represents this instance. public override string ToString() @@ -63,6 +95,11 @@ public override string ToString() public int DeviceNumber { get; internal set; } + /// Gets the name of a drive. + /// This property is the name assigned to the drive, such as: "C:\" or "D:\". + public string DriveName { get; internal set; } + + /// Indicates the partition number of the device is returned in this member, if the device can be partitioned. Otherwise, -1 is returned. public int PartitionNumber { get; internal set; } @@ -97,6 +134,13 @@ public string Name public long TotalSize { get; internal set; } + /// 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. + public string TotalSizeUnitSize + { + get { return Utils.UnitSizeToText(TotalSize, _cultureInfo); } + } + + ///// The Vendor ID of the physical drive. //[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] //public string VendorID diff --git a/AlphaFS/Device/Volume/Volume.GetDriveFormat.cs b/AlphaFS/Device/Volume/Volume.GetDriveFormat.cs index fa77b0ad0..7f7520f65 100644 --- a/AlphaFS/Device/Volume/Volume.GetDriveFormat.cs +++ b/AlphaFS/Device/Volume/Volume.GetDriveFormat.cs @@ -26,7 +26,7 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { - /// [AlphaFS] Gets the name of the file system, such as NTFS or FAT32. + /// [AlphaFS] Gets the name of the file system, such as: "NTFS" or "FAT32". /// Use DriveFormat to determine what formatting a drive uses. /// /// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". diff --git a/AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs b/AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs index 4dc44e04c..3655752d2 100644 --- a/AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs +++ b/AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs @@ -34,7 +34,7 @@ public static partial class Volume [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nt")] public static string GetDriveNameForNtDeviceName(string deviceName) { - return (from drive in Directory.EnumerateLogicalDrivesCore(false, false) + return (from drive in DriveInfo.EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName).Select(driveName => new DriveInfo(driveName)) where drive.DosDeviceName.Equals(deviceName, StringComparison.OrdinalIgnoreCase) diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeGuidForNtDeviceName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeGuidForNtDeviceName.cs index c9bdbf6a5..4a427f761 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeGuidForNtDeviceName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeGuidForNtDeviceName.cs @@ -37,7 +37,7 @@ public static partial class Volume [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nt")] public static string GetVolumeGuidForNtDeviceName(string dosDevice) { - return (from drive in Directory.EnumerateLogicalDrivesCore(false, false) + return (from drive in DriveInfo.EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName).Select(driveName => new DriveInfo(driveName)) where drive.DosDeviceName.Equals(dosDevice, StringComparison.OrdinalIgnoreCase) diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateLogicalDrives.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateLogicalDrives.cs index 42aa67a4b..7bef59b69 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateLogicalDrives.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateLogicalDrives.cs @@ -29,108 +29,24 @@ namespace Alphaleonis.Win32.Filesystem partial class Directory { /// [AlphaFS] Enumerates the drive names of all logical drives on the Computer with the ready status. - /// An IEnumerable of type that represents the logical drives on the Computer. + /// An IEnumerable of type that represents the logical drives on the Computer. [SecurityCritical] + [Obsolete("Use DriveInfo.GetDrives()")] public static IEnumerable EnumerateLogicalDrives() { - return EnumerateLogicalDrivesCore(false, true); + return DriveInfo.EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName).Select(driveName => new DriveInfo(driveName)); } /// [AlphaFS] Enumerates the drive names of all logical drives on the Computer. - /// An IEnumerable of type that represents the logical drives on the Computer. + /// An IEnumerable of type that represents the logical drives on the Computer. /// Retrieve logical drives as known by the Environment. /// Retrieve only when accessible (IsReady) logical drives. [SecurityCritical] + [Obsolete("Use DriveInfo.GetDrives()")] public static IEnumerable EnumerateLogicalDrives(bool fromEnvironment, bool isReady) { - return EnumerateLogicalDrivesCore(fromEnvironment, isReady); - } - - - - - /// Enumerates the drive names of all logical drives on the Computer. - /// An IEnumerable of type that represents the logical drives on the Computer. - /// Retrieve logical drives as known by the Environment. - /// Retrieve only when accessible (IsReady) logical drives. - [SecurityCritical] - internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvironment, bool isReady) - { - // Get from Environment. - - if (fromEnvironment) - { - var drivesEnv = isReady - ? Environment.GetLogicalDrives().Where(ld => File.ExistsCore(null, true, ld, PathFormat.FullPath)) - : Environment.GetLogicalDrives().Select(ld => ld); - - foreach (var drive in drivesEnv) - { - // Optionally check Drive .IsReady. - if (isReady) - { - if (File.ExistsCore(null, true, drive, PathFormat.FullPath)) - yield return new DriveInfo(drive); - } - - else - yield return new DriveInfo(drive); - } - - yield break; - } - - - // Get through NativeMethod. - - var lastError = NativeMethods.GetLogicalDrives(); - - // MSDN: GetLogicalDrives(): If the function fails, the return value is zero. - if (lastError == Win32Errors.ERROR_SUCCESS) - NativeError.ThrowException(lastError); - - - var drives = lastError; - var count = 0; - while (drives != 0) - { - if ((drives & 1) != 0) - ++count; - - drives >>= 1; - } - - var result = new string[count]; - char[] root = {'A', Path.VolumeSeparatorChar}; - - drives = lastError; - count = 0; - - while (drives != 0) - { - if ((drives & 1) != 0) - { - var drive = new string(root); - - if (isReady) - { - // Optionally check Drive .IsReady property. - if (File.ExistsCore(null, true, drive, PathFormat.FullPath)) - yield return new DriveInfo(drive); - } - else - { - // Ready or not. - yield return new DriveInfo(drive); - } - - result[count++] = drive; - } - - drives >>= 1; - root[0]++; - } + return DriveInfo.EnumerateLogicalDrivesCore(fromEnvironment, isReady).OrderBy(driveName => driveName).Select(driveName => new DriveInfo(driveName)); } } } diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs index 6bc8d3f99..e7dc16a23 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System; using System.Linq; using System.Security; @@ -28,25 +29,25 @@ partial class Directory { #region .NET - /// Retrieves the names of the logical drives on the Computer in the form "<drive letter>:\". + /// Retrieves the names of the logical drives on the Computer in the form "drive letter:\". /// An array of type that represents the logical drives on the Computer. [SecurityCritical] public static string[] GetLogicalDrives() { - return EnumerateLogicalDrivesCore(false, false).Select(drive => drive.Name).ToArray(); + return DriveInfo.EnumerateLogicalDrivesCore(false, false).ToArray(); } #endregion // .NET - - /// [AlphaFS] Retrieves the names of the logical drives on the Computer in the form "C:\". + + /// [AlphaFS] Retrieves the names of the logical drives on the Computer in the form "drive letter:\". /// An array of type that represents the logical drives on the Computer. /// Retrieve logical drives as known by the Environment. /// Retrieve only when accessible (IsReady) logical drives. [SecurityCritical] public static string[] GetLogicalDrives(bool fromEnvironment, bool isReady) { - return EnumerateLogicalDrivesCore(fromEnvironment, isReady).Select(drive => drive.Name).ToArray(); + return DriveInfo.EnumerateLogicalDrivesCore(fromEnvironment, isReady).OrderBy(driveName => driveName).ToArray(); } } } diff --git a/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs b/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs index 1698b10d5..ba3dbdeca 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs @@ -157,7 +157,11 @@ internal static string GetFinalPathNameByHandleCore(SafeFileHandle handle, Final 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))) + + foreach (var drive in DriveInfo.EnumerateLogicalDrivesCore(false, false) + + .Where(drv => driveLetter.Equals(RemoveTrailingDirectorySeparator(drv), StringComparison.OrdinalIgnoreCase))) + return CombineCore(false, Volume.GetUniqueVolumeNameForPath(drive), GetSuffixedDirectoryNameWithoutRootCore(null, dosPath), file); } diff --git a/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs b/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs index c0455b7c2..e890dc49f 100644 --- a/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs +++ b/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs @@ -221,12 +221,14 @@ private static string DosDeviceToDosPath(string dosDevice, string deviceReplacem if (Utils.IsNullOrWhiteSpace(dosDevice)) return string.Empty; - foreach (var drive in Directory.EnumerateLogicalDrivesCore(false, false).Select(drv => drv.Name)) + foreach (var drive in DriveInfo.EnumerateLogicalDrivesCore(false, false)) { try { var path = RemoveTrailingDirectorySeparator(drive); + foreach (var devNt in Volume.QueryDosDevice(path).Where(dosDevice.StartsWith)) + return dosDevice.Replace(devNt, deviceReplacement ?? path); } catch From 0d2ddccc65defc0f62a1fcedd9f11534253bd8ba Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 31 Jan 2018 17:02:31 +0100 Subject: [PATCH 010/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 4 +- ...numeratePhysicalDrivesFromLogicalDrives.cs | 4 +- ...vice.EnumeratePhysicalDrivesFromVolumes.cs | 4 +- ...eFiles_UsingDirectoryEnumerationFilters.cs | 2 +- .../Device/Device.EnumeratePhysicalDrives.cs | 4 +- ...numeratePhysicalDrivesFromLogicalDrives.cs | 24 +++- ...vice.EnumeratePhysicalDrivesFromVolumes.cs | 12 +- AlphaFS/Device/Device.GetPhysicalDriveInfo.cs | 125 ++++++++++-------- AlphaFS/Device/Device.cs | 2 +- AlphaFS/Device/DiskSpaceInfo.cs | 2 +- .../DriveInfo.EnumerateLogicalDrives.cs | 1 + AlphaFS/Device/PhysicalDriveInfo.cs | 64 +++++---- .../Device/Volume/Volume.EnumerateVolumes.cs | 5 +- AlphaFS/Filesystem/File Class/File.Create.cs | 8 +- .../Native Other/STORAGE_DEVICE_NUMBER.cs | 5 +- .../StorageDeviceType.cs | 9 +- AlphaFS/Resources.Designer.cs | 6 +- AlphaFS/Resources.resx | 8 +- 18 files changed, 164 insertions(+), 125 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs index 2adcdf1af..1e2b0134e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -42,9 +42,9 @@ public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() foreach (var drive in drives) { Console.WriteLine(); - Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]", ++driveCount, drive.Name); + Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]", ++driveCount, drive.DeviceNumber); - UnitTestConstants.Dump(drive, -23); + UnitTestConstants.Dump(drive, -17); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs index 0ca92416e..e32bc5b05 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs @@ -42,9 +42,9 @@ public void AlphaFS_Device_EnumeratePhysicalDrivesFromLogicalDrives_Local_Succes foreach (var drive in drives) { Console.WriteLine(); - Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, drive.Name); + Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, drive.DevicePath); - UnitTestConstants.Dump(drive, -23); + UnitTestConstants.Dump(drive, -17); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs index f2162ce8a..8f088f409 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs @@ -42,9 +42,9 @@ public void AlphaFS_Device_EnumeratePhysicalDrivesFromVolumes_Local_Success() foreach (var drive in volumes) { Console.WriteLine(); - Console.WriteLine("#{0:000}\tVolume: [{1}]", ++volumeCount, drive.Name); + Console.WriteLine("#{0:000}\tVolume: [{1}]", ++volumeCount, drive.DevicePath); - UnitTestConstants.Dump(drive, -23); + UnitTestConstants.Dump(drive, -17); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs index 954b96cfd..3d63c052b 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs @@ -123,7 +123,7 @@ private void Test_DirectoryEnumerationFilters(string inputPath) }, - Filter to in-/exclude file system entries during the enumeration. + // Filter to in-/exclude file system entries during the enumeration. InclusionFilter = fsei => { if (abortEnumeration) diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs index ca03d65eb..a36625187 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// [AlphaFS] Enumerates the drive names of all physical drives on the Computer. + /// [AlphaFS] Enumerates the physical drives on the Computer. /// An IEnumerable of type that represents the physical drives on the Computer. [SecurityCritical] public static IEnumerable EnumeratePhysicalDrives() @@ -38,7 +38,7 @@ public static IEnumerable EnumeratePhysicalDrives() .Where(physicalDrive => null != physicalDrive) - .OrderBy(disk => disk.DeviceNumber).ThenBy(disk => disk.PartitionNumber); + .OrderBy(disk => disk.DeviceNumber); } } } diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs index 1adcca4dd..d697820d6 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs @@ -27,18 +27,34 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// [AlphaFS] Enumerates the drive names of all physical drives on the Computer. + /// [AlphaFS] Enumerates the logical drives and associated physical drives on the Computer. /// An IEnumerable of type that represents the physical drives on the Computer. [SecurityCritical] public static IEnumerable EnumeratePhysicalDrivesFromLogicalDrives() { - return DriveInfo.EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName) + var allPhysicalDrives = EnumeratePhysicalDrives().ToList(); + + + foreach (var drive in DriveInfo.EnumerateLogicalDrivesCore(false, false) + + .OrderBy(driveName => driveName) .Select(driveName => GetPhysicalDriveInfoCore(driveName, null)) - .Where(physicalDrive => null != physicalDrive) + .Where(pDrive => null != pDrive)) + { + foreach (var physicalDrive in allPhysicalDrives) + { + if (drive.DeviceNumber == physicalDrive.DeviceNumber) + { + drive.Name = physicalDrive.Name; + + yield return drive; - .OrderBy(disk => disk.DeviceNumber).ThenBy(disk => disk.PartitionNumber); + break; + } + } + } } } } diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs index 82b741d99..8c85e7330 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs @@ -27,14 +27,20 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// [AlphaFS] Enumerates the drive names of all physical drives on the Computer. + /// [AlphaFS] Enumerates the volumes and associated physical drives on the Computer. /// An IEnumerable of type that represents the physical drives on the Computer. [SecurityCritical] public static IEnumerable EnumeratePhysicalDrivesFromVolumes() { - return EnumerateDevicesCore(null, DeviceGuid.Volume, false) + // Retrieves more volumes. + return Volume.EnumerateVolumes() - .Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)) + .Select(volume => GetPhysicalDriveInfoCore(volume, null)) + + + //return EnumerateDevicesCore(null, DeviceGuid.Volume, false) + + // .Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)) .Where(physicalDrive => null != physicalDrive) diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs index 452a157e3..83037027b 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs @@ -31,38 +31,40 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// [AlphaFS] Gets the hardware information such as the serial number and Product ID. + /// [AlphaFS] Gets the physical drive information such as the serial number and Product ID. /// A instance that represents the physical drive on the Computer or null on error. /// /// /// /// - /// - /// A valid drive path or drive letter suc as: "C:", "D:\". - /// A string is also valid when is set to . + /// + /// A drive path such as: "C:", "D:\". + /// A volume path such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string (when is set to ). /// [SecurityCritical] - public static PhysicalDriveInfo GetPhysicalDriveInfo(string driveName) + public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) { - return GetPhysicalDriveInfoCore(driveName, null); + return GetPhysicalDriveInfoCore(devicePath, null); } - /// [AlphaFS] Gets the hardware information such as the serial number and Product ID. + /// [AlphaFS] Gets the physical drive information such as the serial number and Product ID. /// A instance that represents the physical drive on the Computer or null on error. /// /// /// /// - /// - /// A valid drive path or drive letter suc as: "C:", "D:\". - /// A string is also valid when is set to . + /// + /// A drive path such as: "C:", "D:\". + /// A volume path such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string (when is set to ). /// /// a instance. - ///Use either or , not both. + ///Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, DeviceInfo deviceInfo) + internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, DeviceInfo deviceInfo) { // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. @@ -75,7 +77,12 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - var pathToDevice = ValidateAndGetPathToDevice(driveName, deviceInfo); + bool isDrive; + bool isVolume; + bool isDeviceInfo = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); + + + var pathToDevice = ValidateAndGetPathToDevice(isDeviceInfo ? deviceInfo.DevicePath : devicePath, out isDrive, out isVolume, out isDeviceInfo); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; @@ -89,7 +96,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev using (safeHandle = OpenPhysicalDrive(pathToDevice, 0)) { - storageDevice = GetStorageDeviceDriveNumber(safeHandle, pathToDevice); + storageDevice = GetStorageDeviceNumberData(safeHandle, pathToDevice); if (null == storageDevice) return null; @@ -100,10 +107,10 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev var diskNumber = device.DeviceNumber; var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, diskNumber.ToString(CultureInfo.InvariantCulture)); - - var info = new PhysicalDriveInfo + + var physicalDriveInfo = new PhysicalDriveInfo { - DriveName = !Utils.IsNullOrWhiteSpace(driveName) ? Path.AddTrailingDirectorySeparator(driveName, false) : null, + DevicePath = isDeviceInfo ? pathToDevice : Path.AddTrailingDirectorySeparator(devicePath, false), DeviceNumber = diskNumber, PartitionNumber = device.PartitionNumber @@ -121,6 +128,10 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev //} + + + // Get storage device information. + using (safeHandle = OpenPhysicalDrive(physicalDrive, desiredAccess)) { uint bytesReturned; @@ -137,20 +148,18 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev var storageDescriptor = safeBuffer.PtrToStructure(0); - info.BusType = (StorageBusType) storageDescriptor.BusType; + physicalDriveInfo.BusType = (StorageBusType) storageDescriptor.BusType; - info.IsRemovable = storageDescriptor.RemovableMedia; + physicalDriveInfo.RemovableMedia = storageDescriptor.RemovableMedia; - info.SupportsCommandQueueing = storageDescriptor.CommandQueueing; + physicalDriveInfo.CommandQueueing = storageDescriptor.CommandQueueing; - info.ProductRevision = safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductRevisionOffset).Trim(); + physicalDriveInfo.ProductRevision = safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductRevisionOffset).Trim(); // "FriendlyName" usually contains a more complete name, as seen in Windows Explorer. - info.Name = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.FriendlyName) - ? deviceInfo.FriendlyName - : safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductIdOffset).Trim(); + physicalDriveInfo.Name = isDeviceInfo ? deviceInfo.FriendlyName : safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductIdOffset).Trim(); //info.InstanceID = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.InstanceID) @@ -162,7 +171,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev long serial; if (long.TryParse(safeBuffer.PtrToStringAnsi((int) storageDescriptor.SerialNumberOffset).Trim(), out serial)) - info.SerialNumber = serial; + physicalDriveInfo.SerialNumber = serial; } @@ -177,44 +186,23 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string driveName, Dev NativeError.ThrowException(lastError, string.Format(CultureInfo.InvariantCulture, "Drive: {0}", physicalDrive)); - info.TotalSize = diskSize; + physicalDriveInfo.TotalSize = diskSize; } } // "FriendlyName" usually contains a more complete name, as seen in Windows Explorer. - if (null == deviceInfo) - SetDeviceFriendlyName(info); - - - return info; - } - - - private static string ValidateAndGetPathToDevice(string driveName, DeviceInfo deviceInfo) - { - var hasDeviceInfo = null != deviceInfo; - if (!hasDeviceInfo) - { - if (Utils.IsNullOrWhiteSpace(driveName)) - throw new ArgumentNullException("driveName"); - - driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); - - if (!Path.IsLogicalDriveCore(driveName, PathFormat.LongFullPath)) - throw new ArgumentException(Resources.Argument_must_be_a_drive_letter_from_a_z, "driveName"); - - driveName = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.LogicalDrivePrefix, driveName); - } + if (!isDeviceInfo) + SetDeviceFriendlyName(physicalDriveInfo); - return Path.RemoveTrailingDirectorySeparator(hasDeviceInfo ? deviceInfo.DevicePath : driveName); + return physicalDriveInfo; } [SecurityCritical] - private static void SetDeviceFriendlyName(PhysicalDriveInfo info) + private static void SetDeviceFriendlyName(PhysicalDriveInfo physicalDriveInfo) { //foreach (var deviceInfo in EnumerateDevicesCore(null, null, DeviceGuid.Disk)) //{ @@ -222,11 +210,44 @@ private static void SetDeviceFriendlyName(PhysicalDriveInfo info) // { // if (!Utils.IsNullOrWhiteSpace(deviceInfo.FriendlyName)) // { - // info.Name = deviceInfo.FriendlyName; + // physicalDriveInfo.Name = deviceInfo.FriendlyName; // return; // } // } //} } + + + private static string ValidateAndGetPathToDevice(string devicePath, out bool isDrive, out bool isVolume, out bool isDeviceInfo) + { + if (Utils.IsNullOrWhiteSpace(devicePath)) + throw new ArgumentNullException("devicePath"); + + + isDrive = false; + isVolume = false; + isDeviceInfo = false; + + + // Resolve single drive letter or get root directory information. + devicePath = devicePath.Length == 1 ? devicePath + Path.VolumeSeparatorChar : Path.GetPathRoot(devicePath, false); + + + isDrive = Path.IsLogicalDriveCore(devicePath, PathFormat.LongFullPath); + + isVolume = devicePath.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase); + + isDeviceInfo = !isDrive && !isVolume && devicePath.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal); + + + if (!isDrive && !isVolume && !isDeviceInfo) + throw new ArgumentException(Resources.Argument_must_be_DriveLetter_or_VolumeGuid_or_DevicePath, "devicePath"); + + + devicePath = string.Format(CultureInfo.InvariantCulture, "{0}", isDrive ? Path.LogicalDrivePrefix + devicePath : devicePath); + + + return Path.RemoveTrailingDirectorySeparator(devicePath); + } } } diff --git a/AlphaFS/Device/Device.cs b/AlphaFS/Device/Device.cs index c001d5a10..d0705ae82 100644 --- a/AlphaFS/Device/Device.cs +++ b/AlphaFS/Device/Device.cs @@ -183,7 +183,7 @@ private static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandl [SecurityCritical] - private static NativeMethods.STORAGE_DEVICE_NUMBER? GetStorageDeviceDriveNumber(SafeFileHandle safeHandle, string pathForException) + private static NativeMethods.STORAGE_DEVICE_NUMBER? GetStorageDeviceNumberData(SafeFileHandle safeHandle, string pathForException) { using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, pathForException)) diff --git a/AlphaFS/Device/DiskSpaceInfo.cs b/AlphaFS/Device/DiskSpaceInfo.cs index 36873a9ce..e04792554 100644 --- a/AlphaFS/Device/DiskSpaceInfo.cs +++ b/AlphaFS/Device/DiskSpaceInfo.cs @@ -61,7 +61,7 @@ public DiskSpaceInfo(string driveName) driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); if (Utils.IsNullOrWhiteSpace(driveName)) - throw new ArgumentException(Resources.InvalidDriveLetterArgument, "drivePath"); + throw new ArgumentException(Resources.InvalidDriveLetterArgument, "driveName"); _cultureInfo = CultureInfo.CurrentCulture; diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs index 7bf84d3bb..182e883cf 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs @@ -50,6 +50,7 @@ internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvironm if (isReady) { if (File.ExistsCore(null, true, drive, PathFormat.LongFullPath)) + yield return Path.AddTrailingDirectorySeparator(drive, false); } diff --git a/AlphaFS/Device/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo.cs index 53ab0220c..0b760ae8c 100644 --- a/AlphaFS/Device/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo.cs @@ -32,7 +32,6 @@ namespace Alphaleonis.Win32.Filesystem [SecurityCritical] public sealed class PhysicalDriveInfo { - [NonSerialized] private string _productID; //[NonSerialized] private string _vendorID; [NonSerialized] private readonly CultureInfo _cultureInfo; [NonSerialized] private IEnumerable _volumes; @@ -52,38 +51,38 @@ public PhysicalDriveInfo() } - /// Initializes a PhysicalDriveInfo instance. - /// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z'. - /// This is a Lazyloading object; call to populate all properties first before accessing. - [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] - [SecurityCritical] - public PhysicalDriveInfo(string driveName) : this() - { - if (Utils.IsNullOrWhiteSpace(driveName)) - throw new ArgumentNullException("driveName"); + ///// Initializes a PhysicalDriveInfo instance. + ///// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z'. + ///// This is a Lazyloading object; call to populate all properties first before accessing. + //[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] + //[SecurityCritical] + //public PhysicalDriveInfo(string driveName) : this() + //{ + // if (Utils.IsNullOrWhiteSpace(driveName)) + // throw new ArgumentNullException("driveName"); - driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); + // driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); - if (Utils.IsNullOrWhiteSpace(driveName)) - throw new ArgumentException(Resources.InvalidDriveLetterArgument, "driveName"); + // if (Utils.IsNullOrWhiteSpace(driveName)) + // throw new ArgumentException(Resources.InvalidDriveLetterArgument, "driveName"); - // 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(driveName, false); - } + // // 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. + // DevicePath = Path.AddTrailingDirectorySeparator(driveName, false); + //} #endregion // Constructors - /// Returns the product ID of the physical drive. + /// Returns the "FriendlyName" of the physical drive. /// A string that represents this instance. public override string ToString() { - return !Utils.IsNullOrWhiteSpace(Name) ? Name : BusType.ToString(); + return Name; } @@ -95,9 +94,13 @@ public override string ToString() public int DeviceNumber { get; internal set; } - /// Gets the name of a drive. - /// This property is the name assigned to the drive, such as: "C:\" or "D:\". - public string DriveName { get; internal set; } + /// The path to the device. + /// A string that represents the path to the device. + /// A drive path such as: "C:", "D:\", + /// a volume path such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\" + /// or a string (when is set to ). + /// + public string DevicePath { get; internal set; } /// Indicates the partition number of the device is returned in this member, if the device can be partitioned. Otherwise, -1 is returned. @@ -106,20 +109,15 @@ public override string ToString() /// Indicates if the physical drive supports multiple outstanding commands (SCSI tagged queuing or equivalent). When false the physical drive does not support SCSI-tagged queuing or the equivalent. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Queueing")] - public bool SupportsCommandQueueing { get; internal set; } + public bool CommandQueueing { get; internal set; } /// Indicates if the physical drive is removable. When true the physical drive's media (if any) is removable. If the device has no media, this member should be ignored. When false the physical drive's media is not removable. - public bool IsRemovable { get; internal set; } - + public bool RemovableMedia { get; internal set; } - /// Returns the product ID or, when not available, the direct disk access (RAW I/O) path of the physical drive. - public string Name - { - get { return !Utils.IsNullOrWhiteSpace(_productID) ? _productID : Path.PhysicalDrivePrefix + DeviceNumber.ToString(CultureInfo.InvariantCulture); } - internal set { _productID = value; } - } + /// Returns the "FriendlyName" of the physical drive. + public string Name { get; internal set; } /// The product revision of the physical drive. diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs index 6e988e02a..83a237345 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs @@ -31,14 +31,13 @@ public static partial class Volume { /// [AlphaFS] Returns an enumerable collection of volumes on the computer. /// An enumerable collection of volume names on the computer. - [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public static IEnumerable EnumerateVolumes() { var buffer = new StringBuilder(50); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) - using (var handle = NativeMethods.FindFirstVolume(buffer, (uint)buffer.Capacity)) + using (var handle = NativeMethods.FindFirstVolume(buffer, (uint) buffer.Capacity)) { var lastError = Marshal.GetLastWin32Error(); @@ -50,7 +49,7 @@ public static IEnumerable EnumerateVolumes() yield return buffer.ToString(); - while (NativeMethods.FindNextVolume(handle, buffer, (uint)buffer.Capacity)) + while (NativeMethods.FindNextVolume(handle, buffer, (uint) buffer.Capacity)) { lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Filesystem/File Class/File.Create.cs b/AlphaFS/Filesystem/File Class/File.Create.cs index 4b5c65435..39fe011fa 100644 --- a/AlphaFS/Filesystem/File Class/File.Create.cs +++ b/AlphaFS/Filesystem/File Class/File.Create.cs @@ -268,8 +268,8 @@ internal static FileStream CreateFileStreamCore(KernelTransaction transaction, s } catch { - if (null != safeHandle) - safeHandle.Dispose(); + if (null != safeHandle && !safeHandle.IsClosed) + safeHandle.Close(); throw; } @@ -308,9 +308,7 @@ internal static SafeFileHandle CreateFileCore(KernelTransaction transaction, str 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:" + // When opening a VOLUME or removable media drive the path string should be the following form: "\\.\C:" // Do not use a trailing backslash (\), which indicates the root. var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator); diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs index a7ddcc792..6fe47572b 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs @@ -29,13 +29,10 @@ internal static partial class NativeMethods /// The STORAGE_DEVICE_NUMBER structure is used in conjunction with the IOCTL_STORAGE_GET_DEVICE_NUMBER request to retrieve the FILE_DEVICE_XXX device type, /// the device number, and, for a device that can be partitioned, the partition number assigned to a device by the driver when the device is started. /// - /// MSDN: http://msdn.microsoft.com/en-us/library/windows/hardware/ff566974(v=vs.85).aspx [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct STORAGE_DEVICE_NUMBER { - /// Specifies one of the system-defined FILE_DEVICE_XXX constants indicating the type of device (such as FILE_DEVICE_DISK, FILE_DEVICE_KEYBOARD, - /// and so forth) or a vendor-defined value for a new type of device. - /// + /// Specifies one of the system-defined FILE_DEVICE_XXX constants indicating the type of device (such as FILE_DEVICE_DISK, FILE_DEVICE_KEYBOARD, and so forth) or a vendor-defined value for a new type of device. internal readonly StorageDeviceType DeviceType; /// Indicates the number of this device. This value is set to 0xFFFFFFFF (-1) for the disks that represent the physical paths of an MPIO disk. diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs index 6ae488bf3..adf68763d 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs @@ -23,7 +23,8 @@ namespace Alphaleonis.Win32.Filesystem { - /// The storage device type. + /// The type of device. Values from 0 through 32,767 are reserved for use by Microsoft. Values from 32,768 through 65,535 are reserved for use by other vendors. + /// The following values are defined by Microsoft. [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags", Justification = "Enum values should not be combinable.")] public enum StorageDeviceType { @@ -34,10 +35,12 @@ public enum StorageDeviceType Beep = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BEEP, /// FILE_DEVICE_CD_ROM parameter. - CDRom = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM, + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CDROM")] + CDROM = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM, /// FILE_DEVICE_CD_ROM_FILE_SYSTEM parameter. - CDRomFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM_FILE_SYSTEM, + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CDROM")] + CDROMFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM_FILE_SYSTEM, /// FILE_DEVICE_CONTROLLER parameter. Controller = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CONTROLLER, diff --git a/AlphaFS/Resources.Designer.cs b/AlphaFS/Resources.Designer.cs index 8fb5fd6f7..d046c5b93 100644 --- a/AlphaFS/Resources.Designer.cs +++ b/AlphaFS/Resources.Designer.cs @@ -61,11 +61,11 @@ internal Resources() { } /// - /// Looks up a localized string similar to Argument must be a drive letter from a-z.. + /// Looks up a localized string similar to Argument must be a drive letter from a-z, volume GUID or a device path.. /// - internal static string Argument_must_be_a_drive_letter_from_a_z { + internal static string Argument_must_be_DriveLetter_or_VolumeGuid_or_DevicePath { get { - return ResourceManager.GetString("Argument_must_be_a_drive_letter_from_a_z", resourceCulture); + return ResourceManager.GetString("Argument_must_be_DriveLetter_or_VolumeGuid_or_DevicePath", resourceCulture); } } diff --git a/AlphaFS/Resources.resx b/AlphaFS/Resources.resx index 65d119a98..983d78154 100644 --- a/AlphaFS/Resources.resx +++ b/AlphaFS/Resources.resx @@ -1,4 +1,4 @@ - + - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.Compression.cs b/AlphaFS/Device/Device.Compression.cs index 19348908b..b7e23c907 100644 --- a/AlphaFS/Device/Device.Compression.cs +++ b/AlphaFS/Device/Device.Compression.cs @@ -25,7 +25,6 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides static methods to retrieve device resource information from a local or remote host. public static partial class Device { /// [AlphaFS] Sets the NTFS compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. diff --git a/AlphaFS/Device/Device.DeviceEnumeration.cs b/AlphaFS/Device/Device.DeviceEnumeration.cs index 6b775f26a..f4aa4cca2 100644 --- a/AlphaFS/Device/Device.DeviceEnumeration.cs +++ b/AlphaFS/Device/Device.DeviceEnumeration.cs @@ -131,6 +131,8 @@ internal static IEnumerable EnumerateDevicesCore(string hostName, De } + + [SecurityCritical] private static string GetDeviceInstanceID(SafeCmConnectMachineHandle safeMachineHandle, string hostName, NativeMethods.SP_DEVINFO_DATA diData) { @@ -167,5 +169,106 @@ private static string GetDeviceInstanceID(SafeCmConnectMachineHandle safeMachine return safeBuffer.PtrToStringUni(); } } + + + /// Builds a Device Interface Detail Data structure. + /// An initialized NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA instance. + [SecurityCritical] + private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetInterfaceDetails(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) + { + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize / 4)) + { + uint regDataType; + + var success = NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref infoData, property, out regDataType, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero); + + var lastError = Marshal.GetLastWin32Error(); + + + // 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 (!success) + { + if (lastError != Win32Errors.ERROR_INVALID_DATA) + NativeError.ThrowException(lastError); + + return string.Empty; + } + + + return safeBuffer.PtrToStringUni(); + } + } + + + [SecurityCritical] + private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) + { + deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.BaseContainerId)); + + deviceInfo.CompatibleIds = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.CompatibleIds); + + deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class); + + deviceInfo.DeviceDescription = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceDescription); + + //deviceInfo.DeviceType = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceType); + + deviceInfo.Driver = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Driver); + + deviceInfo.EnumeratorName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.EnumeratorName); + + deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); + + 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.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.PhysicalDeviceObjectName); + + deviceInfo.Service = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Service); + } + + + [SecurityCritical] + private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) + { + deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class); + + deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); + } + + + //private static uint IOCTL_STORAGE_QUERY_PROPERTY = CTL_CODE((uint) NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE, 0x500, 0,0); + //private static uint CTL_CODE(uint deviceType, uint function, uint method, uint access) + //{ + // return (deviceType << 16) | (access << 14) | (function << 2) | method; + //} } } diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs index 2d03611e9..782a0385d 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs @@ -20,8 +20,8 @@ */ using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Linq; +using System.Net.Sockets; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -44,44 +44,29 @@ public static IEnumerable EnumeratePhysicalDrivesFromLogicalD continue; - foreach (var physicalDrive in physicalDrives) + foreach (var physicalDrive in physicalDrives.Where(pd => pd.DeviceNumber == pDriveInfo.DeviceNumber)) + { + physicalDrive.CopyTo(pDriveInfo); - if (pDriveInfo.DeviceNumber == physicalDrive.DeviceNumber) - { - // Get the first entry that starts with a drive name, such as: "C:", "D:". - if (Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath)) - { - pDriveInfo.DriveInfo = new DriveInfo(drive); - - - var guid = Volume.GetVolumeGuid(drive); - - if (!Utils.IsNullOrWhiteSpace(guid)) - pDriveInfo.VolumeGuids = new[] {guid}; - } - - - pDriveInfo.BusType = physicalDrive.BusType; - pDriveInfo.CommandQueueing = physicalDrive.CommandQueueing; + // Get the first entry that starts with a logical drive path, such as: "C:", "D:". - pDriveInfo.DevicePath = physicalDrive.DevicePath; - - pDriveInfo.Name = physicalDrive.Name; - - pDriveInfo.ProductRevision = physicalDrive.ProductRevision; + if (Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath)) + { + pDriveInfo.DriveInfo = new DriveInfo(drive); - pDriveInfo.RemovableMedia = physicalDrive.RemovableMedia; - pDriveInfo.SerialNumber = physicalDrive.SerialNumber; + var guid = Volume.GetVolumeGuid(drive); - pDriveInfo.TotalSize = physicalDrive.TotalSize; + if (!Utils.IsNullOrWhiteSpace(guid)) + pDriveInfo.VolumeGuids = new[] {guid}; + } - yield return pDriveInfo; + yield return pDriveInfo; - break; - } + break; + } } } } diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs index ad62b3c83..b131bbd2f 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs @@ -58,46 +58,30 @@ public static IEnumerable EnumeratePhysicalDrivesFromVolumes( continue; - foreach (var physicalDrive in physicalDrives) + foreach (var physicalDrive in physicalDrives.Where(pd => pd.DeviceNumber == pDriveInfo.DeviceNumber)) + { + physicalDrive.CopyTo(pDriveInfo); - if (pDriveInfo.DeviceNumber == physicalDrive.DeviceNumber) - { - foreach (var drive in Volume.EnumerateVolumePathNames(volume)) - { - // Get the first entry that starts with a drive name, such as: "C:", "D:". - if (!Utils.IsNullOrWhiteSpace(drive) && Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath)) - { - pDriveInfo.DriveInfo = new DriveInfo(drive); - - break; - } - } - - - pDriveInfo.VolumeGuids = new[] {volume}; - - - pDriveInfo.BusType = physicalDrive.BusType; - - pDriveInfo.CommandQueueing = physicalDrive.CommandQueueing; - pDriveInfo.DevicePath = physicalDrive.DevicePath; - - pDriveInfo.Name = physicalDrive.Name; - - pDriveInfo.ProductRevision = physicalDrive.ProductRevision; + foreach (var drive in Volume.EnumerateVolumePathNames(volume)) + { + // Get the first entry that starts with a logical drive path, such as: "C:", "D:". - pDriveInfo.RemovableMedia = physicalDrive.RemovableMedia; + if (!Utils.IsNullOrWhiteSpace(drive) && Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath)) + { + pDriveInfo.DriveInfo = new DriveInfo(drive); - pDriveInfo.SerialNumber = physicalDrive.SerialNumber; + break; + } + } - pDriveInfo.TotalSize = physicalDrive.TotalSize; + pDriveInfo.VolumeGuids = new[] {volume}; - allDrives.Add(pDriveInfo); + allDrives.Add(pDriveInfo); - break; - } + break; + } } diff --git a/AlphaFS/Device/Device.GetDeviceIoData.cs b/AlphaFS/Device/Device.GetDeviceIoData.cs new file mode 100644 index 000000000..5de75282b --- /dev/null +++ b/AlphaFS/Device/Device.GetDeviceIoData.cs @@ -0,0 +1,64 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] + [SecurityCritical] + private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) + { + NativeMethods.IsValidHandle(safeHandle); + + //var nativeOverlapped = new NativeOverlapped(); + var bufferSize = size > -1 ? size : Marshal.SizeOf(typeof(T)); + + while (true) + { + uint bytesReturned; + var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); + + var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); + + var lastError = Marshal.GetLastWin32Error(); + + + if (success) + return safeBuffer; + + + // CDROM drive without a CD. + if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) + return null; + + + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + } + } + } +} diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs index 7b59c42ff..6352050ca 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs @@ -22,7 +22,6 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; @@ -100,50 +99,24 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De if (getStorageData) { - GetStorageData(physicalDrive, physicalDriveInfo); + SetStorageData(physicalDrive, physicalDriveInfo); - //physicalDriveInfo.Volumes = Volume.EnumerateVolumes().Select(volume => new VolumeInfo(volume)).ToArray(); + GetVolumeDiskExtents(physicalDrive); } - - - return physicalDriveInfo; - - //try - //{ - // GetVolumeDiskExtents(physicalDrive, desiredAccess); - //} - //catch (Exception ex) - //{ - // Console.WriteLine(ex.Message); - //} - } - - - private static NativeMethods.STORAGE_DEVICE_NUMBER? GetStorageDevice(string devicePath) - { - var pathToDevice = ValidateAndGetPathToDevice(devicePath); - - if (Utils.IsNullOrWhiteSpace(pathToDevice)) - return null; - - - // No elevation needed. - - using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) - return GetStorageDeviceNumberData(safeHandle, pathToDevice); + return physicalDriveInfo; } + - - private static void GetStorageData(string physicalDrive, PhysicalDriveInfo physicalDriveInfo) + private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physicalDriveInfo) { // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. //const int desiredAccess = 0; - // Requires elevation for: TotalNumberOfBytes + // Requires elevation for. const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; @@ -151,8 +124,6 @@ private static void GetStorageData(string physicalDrive, PhysicalDriveInfo physi using (var safeHandle = OpenPhysicalDrive(physicalDrive, desiredAccess)) { - uint bytesReturned; - var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { PropertyId = 0, // StorageDeviceProperty, from STORAGE_PROPERTY_ID enum. @@ -163,7 +134,7 @@ private static void GetStorageData(string physicalDrive, PhysicalDriveInfo physi using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, physicalDrive, NativeMethods.DefaultFileBufferSize / 4)) { var storageDescriptor = safeBuffer.PtrToStructure(0); - + physicalDriveInfo.BusType = (StorageBusType) storageDescriptor.BusType; @@ -177,35 +148,49 @@ private static void GetStorageData(string physicalDrive, PhysicalDriveInfo physi if (Utils.IsNullOrWhiteSpace(physicalDriveInfo.Name)) physicalDriveInfo.Name = safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductIdOffset).Trim(); - - - // Retrieve the device's hardware serial number. - long serial; - if (long.TryParse(safeBuffer.PtrToStringAnsi((int) storageDescriptor.SerialNumberOffset).Trim(), out serial)) + // Get the device hardware serial number. - physicalDriveInfo.SerialNumber = serial; + physicalDriveInfo.SerialNumber = safeBuffer.PtrToStringAnsi((int) storageDescriptor.SerialNumberOffset).Trim(); } - - - // Get disk size. + // Get the device size. - long diskSize; + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(long)))) + { + uint bytesReturned; + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); - var success = NativeMethods.DeviceIoControl5(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, IntPtr.Zero, 0, out diskSize, (uint) Marshal.SizeOf(typeof(long)), out bytesReturned, IntPtr.Zero); + var lastError = Marshal.GetLastWin32Error(); - var lastError = Marshal.GetLastWin32Error(); - if (!success) - NativeError.ThrowException(lastError, string.Format(CultureInfo.InvariantCulture, "Drive: {0}", physicalDrive)); + if (!success) + NativeError.ThrowException(lastError, string.Format(CultureInfo.InvariantCulture, "Drive: {0}", physicalDrive)); - physicalDriveInfo.TotalSize = diskSize; + physicalDriveInfo.TotalSize = safeBuffer.ReadInt64(); + } } } - + + + private static NativeMethods.STORAGE_DEVICE_NUMBER? GetStorageDevice(string devicePath) + { + var pathToDevice = ValidateAndGetPathToDevice(devicePath); + + if (Utils.IsNullOrWhiteSpace(pathToDevice)) + return null; + + + // No elevation needed. + + using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, pathToDevice)) + + return null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?) null; + } + private static string ValidateAndGetPathToDevice(string devicePath) { diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index c44016865..dda773ba1 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -19,69 +19,45 @@ * THE SOFTWARE. */ +using System; using System.Security; using System.Security.AccessControl; -using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// - /// - /// - /// - /// - /// [SecurityCritical] - public static void GetVolumeDiskExtents(string physicalDrive, FileSystemRights desiredAccess) + public static void GetVolumeDiskExtents(string logicalDrive) { - var structure = GetVolumeDiskExtentsCore(physicalDrive, desiredAccess); + // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes + // without accessing that file or device, even if GENERIC_READ access would have been denied. + // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + //const int desiredAccess = 0; - //Console.WriteLine("{0}: NumberOfDiskExtents: {1}", physicalDrive, structure.NumberOfDiskExtents); - } + // Requires elevation. + const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; + //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - /// - /// - /// - /// - /// - /// - /// - [SecurityCritical] - public static void GetVolumeDiskExtents(SafeFileHandle safeHandle, string physicalDrive, FileSystemRights desiredAccess) - { - } + //var volumeDiskExtents = new NativeMethods.VOLUME_DISK_EXTENTS(); - /// - /// - /// - /// - /// - /// - [SecurityCritical] - private static NativeMethods.VOLUME_DISK_EXTENTS GetVolumeDiskExtentsCore(string physicalDrive, FileSystemRights desiredAccess) - { - using (var safeHandle = OpenPhysicalDrive(physicalDrive, desiredAccess)) + logicalDrive = @"\\.\C:"; + using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) - using (var safeBuffer = GetDeviceIoData3(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, physicalDrive, 32)) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, logicalDrive)) { - var offset = 0; - - var structure = safeBuffer.PtrToStructure(0); - - safeBuffer.PtrToStructure(0); - - //for (var i = 0; i < structure.NumberOfDiskExtents; i += offset) - //{ - // structure.Extents[i] = new NativeMethods.DISK_EXTENT[structure.NumberOfDiskExtents]; - //} - + if (null != safeBuffer) + { + var structure = safeBuffer.PtrToStructure(0); - return structure; + for (var i = 0; i < structure.NumberOfDiskExtents; ++i) + { + var pDiskExtent = structure.Extents[i]; + } + } } } } diff --git a/AlphaFS/Device/Device.InvokeDeviceIoData.cs b/AlphaFS/Device/Device.InvokeDeviceIoData.cs new file mode 100644 index 000000000..0f89eaaf0 --- /dev/null +++ b/AlphaFS/Device/Device.InvokeDeviceIoData.cs @@ -0,0 +1,61 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + /// Invokes InvokeIoControl with the specified input and specified size. + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] + [SecurityCritical] + private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string pathForException, int size = -1) + { + NativeMethods.IsValidHandle(safeHandle); + + + var bufferSize = size > -1 ? size : Marshal.SizeOf(anyObject); + + while (true) + { + uint bytesReturned; + + var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); + + var success = NativeMethods.DeviceIoControlAnyObjectGetSet(safeHandle, controlCode, anyObject, (uint) bufferSize, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); + + var lastError = Marshal.GetLastWin32Error(); + + + if (success) + return safeBuffer; + + + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + } + } + } +} diff --git a/AlphaFS/Device/Device.cs b/AlphaFS/Device/Device.cs index bca8da071..59d360962 100644 --- a/AlphaFS/Device/Device.cs +++ b/AlphaFS/Device/Device.cs @@ -20,11 +20,9 @@ */ using System; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security; -using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { @@ -38,125 +36,6 @@ public static partial class Device private const int REPARSE_DATA_BUFFER_HEADER_SIZE = 8; - /// Builds a Device Interface Detail Data structure. - /// An initialized NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA instance. - [SecurityCritical] - private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetInterfaceDetails(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) - { - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize / 4)) - { - uint regDataType; - - var success = NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref infoData, property, out regDataType, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero); - - var lastError = Marshal.GetLastWin32Error(); - - - // MSDN: SetupDiGetDeviceRegistryProperty returns the ERROR_INVALID_DATA error code if the requested property - // does not exist for a device or if the property data is not valid. - - if (!success) - { - if (lastError != Win32Errors.ERROR_INVALID_DATA) - NativeError.ThrowException(lastError); - - return string.Empty; - } - - - return safeBuffer.PtrToStringUni(); - } - } - - - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] - [SecurityCritical] - private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) - { - NativeMethods.IsValidHandle(safeHandle); - - //var nativeOverlapped = new NativeOverlapped(); - var bufferSize = size > -1 ? size : Marshal.SizeOf(typeof(T)); - - while (true) - { - uint bytesReturned; - - var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - - var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); - - var lastError = Marshal.GetLastWin32Error(); - - - if (success) - return safeBuffer; - - - // Dynamic disk. - if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) - return null; - - - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); - } - } - - - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] - [SecurityCritical] - private static SafeGlobalMemoryBufferHandle GetDeviceIoData3(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) - { - NativeMethods.IsValidHandle(safeHandle); - - //var nativeOverlapped = new NativeOverlapped(); - var bufferSize = size > -1 ? size : Marshal.SizeOf(typeof(T)); - - while (true) - { - uint bytesReturned; - - var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - - var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); - - var lastError = Marshal.GetLastWin32Error(); - - - if (success) - return safeBuffer; - - - // Dynamic disk. - if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) - return null; - - - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); - } - } - - [SecurityCritical] internal static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandle safeBuffer, int bufferSize, string pathForException) { @@ -180,97 +59,5 @@ internal static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHand return bufferSize; } - - - [SecurityCritical] - private static NativeMethods.STORAGE_DEVICE_NUMBER? GetStorageDeviceNumberData(SafeFileHandle safeHandle, string pathForException) - { - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, pathForException)) - - return null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?) null; - } - - - /// Invokes InvokeIoControl with the specified input and specified size. - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] - [SecurityCritical] - private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string pathForException, int size = -1) - { - NativeMethods.IsValidHandle(safeHandle); - - - var bufferSize = size > -1 ? size : Marshal.SizeOf(anyObject); - - while (true) - { - uint bytesReturned; - - var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - - var success = NativeMethods.DeviceIoControlAnyObject(safeHandle, controlCode, anyObject, (uint) bufferSize, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); - - var lastError = Marshal.GetLastWin32Error(); - - - if (success) - return safeBuffer; - - - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); - } - } - - - [SecurityCritical] - private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) - { - deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.BaseContainerId)); - - deviceInfo.CompatibleIds = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.CompatibleIds); - - deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class); - - deviceInfo.DeviceDescription = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceDescription); - - //deviceInfo.DeviceType = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceType); - - deviceInfo.Driver = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Driver); - - deviceInfo.EnumeratorName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.EnumeratorName); - - deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); - - 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.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.PhysicalDeviceObjectName); - - deviceInfo.Service = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Service); - } - - - [SecurityCritical] - private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) - { - deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class); - - //deviceInfo.DeviceType = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceType); - - deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); - - //deviceInfo.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.PhysicalDeviceObjectName); - } - - - //private static uint IOCTL_STORAGE_QUERY_PROPERTY = CTL_CODE((uint) NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE, 0x500, 0,0); - //private static uint CTL_CODE(uint deviceType, uint function, uint method, uint access) - //{ - // return (deviceType << 16) | (access << 14) | (function << 2) | method; - //} } } diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs index 383246ef8..5941300ab 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs @@ -111,20 +111,6 @@ private object GetDeviceInfo(int type, int mode) break; #endregion // Drive - - - #region Physical Drive - - //// Physical Drive related. - //case 4: - // if (mode == 0) - // { - // return IsUnc ? null : (_physicalDriveInfo ?? (_physicalDriveInfo = Device.GetPhysicalDriveInfoCore(_name, null))); - // } - - // return null; - - #endregion // Physical Drive } //} //catch diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.cs index 1078bd615..a37c08a30 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.cs @@ -41,7 +41,6 @@ public sealed partial class DriveInfo [NonSerialized] private readonly VolumeInfo _volumeInfo; [NonSerialized] private readonly DiskSpaceInfo _dsi; - //[NonSerialized] private PhysicalDriveInfo _physicalDriveInfo; [NonSerialized] private bool _initDsie; [NonSerialized] private readonly string _name; [NonSerialized] private string _dosDeviceName; @@ -85,10 +84,6 @@ public DriveInfo(string driveName) // Initiate DiskSpaceInfo lazyload instance. _dsi = new DiskSpaceInfo(_name, null, false, true); - - - //// Initiate PhysicalDriveInfo lazyload instance. - //_physicalDriveInfo = null; } #endregion // .NET @@ -260,15 +255,7 @@ public bool IsVolume get { return null != GetDeviceInfo(0, 0); } } - - ///// [AlphaFS] Contains information about the physical drive. - ///// A object that contains information of the physical drive. - //public PhysicalDriveInfo PhysicalDriveInfo - //{ - // get { return (PhysicalDriveInfo) GetDeviceInfo(4, 0); } - //} - - + /// [AlphaFS] Contains information about a file system volume. /// A object that contains file system volume information of the drive. public VolumeInfo VolumeInfo @@ -315,8 +302,6 @@ public static DriveInfo[] GetDrives(bool fromEnvironment, bool isReady) /// [AlphaFS] Refreshes the state of the object. public void Refresh() { - //_physicalDriveInfo = null; - _volumeInfo.Refresh(); _dsi.Refresh(); diff --git a/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs b/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs index f1a33086f..86f234e7e 100644 --- a/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs +++ b/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs @@ -26,7 +26,6 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides static methods to retrieve device resource information from a local or remote host. public static partial class Device { /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). @@ -69,7 +68,7 @@ internal static void CreateDirectoryJunction(SafeFileHandle safeHandle, string d safeBuffer.StructureToPtr(reparseDataBuffer, false); uint bytesReturned; - var success = NativeMethods.DeviceIoControl2(safeHandle, NativeMethods.IoControlCode.FSCTL_SET_REPARSE_POINT, safeBuffer, (uint)(targetDirBytes.Length + 20), IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoJunctions(safeHandle, NativeMethods.IoControlCode.FSCTL_SET_REPARSE_POINT, safeBuffer, (uint)(targetDirBytes.Length + 20), IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); if (!success) diff --git a/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs b/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs index 07bbfbb38..ff15dc2e7 100644 --- a/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs +++ b/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs @@ -25,7 +25,6 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides static methods to retrieve device resource information from a local or remote host. public static partial class Device { /// [AlphaFS] Deletes an NTFS directory junction. @@ -44,7 +43,7 @@ internal static void DeleteDirectoryJunction(SafeFileHandle safeHandle) safeBuffer.StructureToPtr(reparseDataBuffer, false); uint bytesReturned; - var success = NativeMethods.DeviceIoControl2(safeHandle, NativeMethods.IoControlCode.FSCTL_DELETE_REPARSE_POINT, safeBuffer, REPARSE_DATA_BUFFER_HEADER_SIZE, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoJunctions(safeHandle, NativeMethods.IoControlCode.FSCTL_DELETE_REPARSE_POINT, safeBuffer, REPARSE_DATA_BUFFER_HEADER_SIZE, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); if (!success) diff --git a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs index b8e39cc2c..52c7a799a 100644 --- a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs +++ b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs @@ -28,7 +28,6 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides static methods to retrieve device resource information from a local or remote host. public static partial class Device { /// [AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system. @@ -94,7 +93,7 @@ private static SafeGlobalMemoryBufferHandle GetLinkTargetData(SafeFileHandle saf while (true) { uint bytesReturned; - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); if (!success) diff --git a/AlphaFS/Device/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo.cs index fa0f6f72d..722f80cf3 100644 --- a/AlphaFS/Device/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo.cs @@ -20,10 +20,8 @@ */ using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; -using System.Globalization; +using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -33,21 +31,12 @@ namespace Alphaleonis.Win32.Filesystem [SecurityCritical] public sealed class PhysicalDriveInfo { - //[NonSerialized] private string _vendorID; - [NonSerialized] private readonly CultureInfo _cultureInfo; - //[NonSerialized] private IEnumerable _volumes; - - #region Constructors /// Initializes a PhysicalDriveInfo instance. public PhysicalDriveInfo() { - _cultureInfo = CultureInfo.CurrentCulture; - - PartitionNumber = -1; - SerialNumber = -1; TotalSize = -1; } @@ -124,12 +113,15 @@ public override string ToString() public int PartitionNumber { get; internal set; } + /// The Partitions located on the physical drive. + public string[] Partitions { get; set; } + /// The product revision of the physical drive. public string ProductRevision { get; internal set; } /// Gets the serial number of the physical drive. If the physical drive has no serial number, this member is -1. - public long SerialNumber { get; internal set; } + public string SerialNumber { get; internal set; } /// The total size of the physical drive. If the session is not elevated, this member is -1. @@ -139,26 +131,31 @@ public override string ToString() /// 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. public string TotalSizeUnitSize { - get { return Utils.UnitSizeToText(TotalSize, _cultureInfo); } + get { return Utils.UnitSizeToText(TotalSize); } } - ///// The Vendor ID of the physical drive. - //[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] - //public string VendorID - //{ - // get { return !Utils.IsNullOrWhiteSpace(_vendorID) ? _vendorID : string.Empty; } + /// The Volumes located on the physical drive. + public string[] VolumeGuids { get; set; } - // internal set - // { - // // SanDisk X400 M.2 2280 256GB reports VendorID as: "(" - // _vendorID = null != value && value.Length > 1 ? value : string.Empty; - // } - //} - /// The Volumes located on the physical drive. - public string[] VolumeGuids { get; set; } + internal void CopyTo(T destination) + { + var srcProps = typeof(T).GetProperties().Where(x => x.CanRead).ToArray(); + var dstProps = typeof(T).GetProperties().Where(x => x.CanWrite).ToArray(); + + foreach (var sourceProp in srcProps) + { + if (dstProps.Any(x => x.Name.Equals(sourceProp.Name))) + { + var p = dstProps.First(x => x.Name.Equals(sourceProp.Name)); + + if (p.CanWrite) + p.SetValue(destination, sourceProp.GetValue(this, null), null); + } + } + } } } diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs index 1563f1db9..c42157d6d 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs @@ -147,34 +147,13 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControlAnyObject(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, [MarshalAs(UnmanagedType.AsAny)] object lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); + internal static extern bool DeviceIoControlAnyObjectGetSet(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, [MarshalAs(UnmanagedType.AsAny)] object lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl2(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, SafeGlobalMemoryBufferHandle lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, IntPtr lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); - - - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] - [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl3(SafeFileHandle hDevice, IoControlCode dwIoControlCode, IntPtr lpInBuffer, - int nInBufferSize, - SafeGlobalMemoryBufferHandle lpOutBuffer, - int nOutBufferSize, - out int lpBytesReturned, - IntPtr lpOverlapped); - - //internal static extern bool DeviceIoControl3(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, IntPtr lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); - - - - // Get size of a specified disk. - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] - [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl5(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, IntPtr lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, out long lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); + internal static extern bool DeviceIoJunctions(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, SafeGlobalMemoryBufferHandle lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, IntPtr lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); #endregion // DeviceIoControl diff --git a/AlphaFS/Filesystem/Native Other/IoControlCode.cs b/AlphaFS/Filesystem/Native Other/IoControlCode.cs index cd71cba3a..4b5ea68d8 100644 --- a/AlphaFS/Filesystem/Native Other/IoControlCode.cs +++ b/AlphaFS/Filesystem/Native Other/IoControlCode.cs @@ -38,6 +38,8 @@ internal enum IoControlCode : uint /// Retrieves the physical location of a specified volume on one or more disks. + //IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), + IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), From eeb240aa1e4621f79cbff2d50625f85f0425b576 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 2 Feb 2018 11:23:55 +0100 Subject: [PATCH 016/133] Code improvement, work in progress. --- AlphaFS/AlphaFS.csproj | 2 +- ...meration.cs => Device.EnumerateDevices.cs} | 4 ++ ...numeratePhysicalDrivesFromLogicalDrives.cs | 10 +++-- ...vice.EnumeratePhysicalDrivesFromVolumes.cs | 4 +- AlphaFS/Device/Device.GetDeviceIoData.cs | 2 +- AlphaFS/Device/Device.GetPhysicalDriveInfo.cs | 45 +++++++++++-------- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 2 - AlphaFS/Device/PhysicalDriveInfo.cs | 21 +++++---- AlphaFS/Resources.Designer.cs | 2 +- AlphaFS/Resources.resx | 2 +- 10 files changed, 54 insertions(+), 40 deletions(-) rename AlphaFS/Device/{Device.DeviceEnumeration.cs => Device.EnumerateDevices.cs} (98%) diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index adc6f9e7f..c5b124296 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -203,7 +203,7 @@ - + diff --git a/AlphaFS/Device/Device.DeviceEnumeration.cs b/AlphaFS/Device/Device.EnumerateDevices.cs similarity index 98% rename from AlphaFS/Device/Device.DeviceEnumeration.cs rename to AlphaFS/Device/Device.EnumerateDevices.cs index f4aa4cca2..48abe870b 100644 --- a/AlphaFS/Device/Device.DeviceEnumeration.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -261,7 +261,11 @@ private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo { deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class); + deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); + + if (Utils.IsNullOrWhiteSpace(deviceInfo.FriendlyName)) + deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceDescription); } diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs index 782a0385d..bdc5eccf4 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs @@ -34,9 +34,11 @@ public static partial class Device public static IEnumerable EnumeratePhysicalDrivesFromLogicalDrives() { var physicalDrives = EnumeratePhysicalDrives().ToArray(); - - foreach (var drive in DriveInfo.EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName)) + var logicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName).ToArray(); + + + foreach (var drive in logicalDrives) { var pDriveInfo = GetPhysicalDriveInfoCore(drive, null, false); @@ -44,9 +46,9 @@ public static IEnumerable EnumeratePhysicalDrivesFromLogicalD continue; - foreach (var physicalDrive in physicalDrives.Where(pd => pd.DeviceNumber == pDriveInfo.DeviceNumber)) + foreach (var pDrive in physicalDrives.Where(pDrive => pDrive.DeviceNumber == pDriveInfo.DeviceNumber)) { - physicalDrive.CopyTo(pDriveInfo); + pDrive.CopyTo(pDriveInfo); // Get the first entry that starts with a logical drive path, such as: "C:", "D:". diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs index b131bbd2f..493bd8687 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs @@ -58,9 +58,9 @@ public static IEnumerable EnumeratePhysicalDrivesFromVolumes( continue; - foreach (var physicalDrive in physicalDrives.Where(pd => pd.DeviceNumber == pDriveInfo.DeviceNumber)) + foreach (var pDrive in physicalDrives.Where(pDrive => pDrive.DeviceNumber == pDriveInfo.DeviceNumber)) { - physicalDrive.CopyTo(pDriveInfo); + pDrive.CopyTo(pDriveInfo); foreach (var drive in Volume.EnumerateVolumePathNames(volume)) diff --git a/AlphaFS/Device/Device.GetDeviceIoData.cs b/AlphaFS/Device/Device.GetDeviceIoData.cs index 5de75282b..ae1742eae 100644 --- a/AlphaFS/Device/Device.GetDeviceIoData.cs +++ b/AlphaFS/Device/Device.GetDeviceIoData.cs @@ -53,7 +53,7 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa // CDROM drive without a CD. - if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) + if (lastError == Win32Errors.ERROR_NOT_SUPPORTED) return null; diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs index 6352050ca..e9cab9a49 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs @@ -48,8 +48,8 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) } - - + + /// [AlphaFS] Gets the physical drive information such as the serial number and Product ID. /// A instance that represents the physical drive on the Computer or null on error. /// @@ -74,7 +74,8 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De devicePath = deviceInfo.DevicePath; - var storageDevice = GetStorageDevice(devicePath); + string logicalDrive; + var storageDevice = GetStorageDevice(devicePath, out logicalDrive); if (null == storageDevice) return null; @@ -94,20 +95,21 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De }; - var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, diskNumber.ToString(CultureInfo.InvariantCulture)); - - if (getStorageData) { - SetStorageData(physicalDrive, physicalDriveInfo); + var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, diskNumber.ToString(CultureInfo.InvariantCulture)); - GetVolumeDiskExtents(physicalDrive); + SetStorageData(physicalDrive, physicalDriveInfo); } - + + + if (null != logicalDrive) + GetVolumeDiskExtents(logicalDrive); + return physicalDriveInfo; } - + private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physicalDriveInfo) { @@ -121,7 +123,7 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - + using (var safeHandle = OpenPhysicalDrive(physicalDrive, desiredAccess)) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY @@ -134,7 +136,7 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, physicalDrive, NativeMethods.DefaultFileBufferSize / 4)) { var storageDescriptor = safeBuffer.PtrToStructure(0); - + physicalDriveInfo.BusType = (StorageBusType) storageDescriptor.BusType; @@ -155,7 +157,7 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi physicalDriveInfo.SerialNumber = safeBuffer.PtrToStringAnsi((int) storageDescriptor.SerialNumberOffset).Trim(); } - + // Get the device size. using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(long)))) @@ -175,9 +177,11 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi } - private static NativeMethods.STORAGE_DEVICE_NUMBER? GetStorageDevice(string devicePath) + private static NativeMethods.STORAGE_DEVICE_NUMBER? GetStorageDevice(string devicePath, out string logicalDrive) { - var pathToDevice = ValidateAndGetPathToDevice(devicePath); + logicalDrive = null; + + var pathToDevice = ValidateAndGetPathToDevice(devicePath, out logicalDrive); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; @@ -186,13 +190,14 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi // No elevation needed. using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, pathToDevice)) - return null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?) null; + return null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?)null; } - private static string ValidateAndGetPathToDevice(string devicePath) + private static string ValidateAndGetPathToDevice(string devicePath, out string logicalDrive) { if (Utils.IsNullOrWhiteSpace(devicePath)) throw new ArgumentNullException("devicePath"); @@ -214,10 +219,12 @@ private static string ValidateAndGetPathToDevice(string devicePath) throw new ArgumentException(Resources.Argument_must_be_DriveLetter_or_VolumeGuid_or_DevicePath, "devicePath"); - devicePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", isDrive ? Path.LogicalDrivePrefix : string.Empty, devicePath); + devicePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", isDrive ? Path.LogicalDrivePrefix : string.Empty, Path.RemoveTrailingDirectorySeparator(devicePath)); + + logicalDrive = isDrive ? devicePath : null; - return Path.RemoveTrailingDirectorySeparator(devicePath); + return devicePath; } } } diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index dda773ba1..9fb912c0a 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System; using System.Security; using System.Security.AccessControl; @@ -44,7 +43,6 @@ public static void GetVolumeDiskExtents(string logicalDrive) //var volumeDiskExtents = new NativeMethods.VOLUME_DISK_EXTENTS(); - logicalDrive = @"\\.\C:"; using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, logicalDrive)) diff --git a/AlphaFS/Device/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo.cs index 722f80cf3..b9bded5be 100644 --- a/AlphaFS/Device/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo.cs @@ -143,18 +143,21 @@ public string TotalSizeUnitSize internal void CopyTo(T destination) { - var srcProps = typeof(T).GetProperties().Where(x => x.CanRead).ToArray(); - var dstProps = typeof(T).GetProperties().Where(x => x.CanWrite).ToArray(); + // Properties listed here should not be overwritten by the physical drive template. - foreach (var sourceProp in srcProps) + var excludedProps = new[] {"PartitionNumber"}; + + + var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite && !excludedProps.Any(prop => prop.Equals(x.Name))).ToArray(); + + var dstProps = srcProps.Where(x => x.CanWrite).ToArray(); + + + foreach (var srcProp in srcProps) { - if (dstProps.Any(x => x.Name.Equals(sourceProp.Name))) - { - var p = dstProps.First(x => x.Name.Equals(sourceProp.Name)); + var dstProp = dstProps.First(x => x.Name.Equals(srcProp.Name)); - if (p.CanWrite) - p.SetValue(destination, sourceProp.GetValue(this, null), null); - } + dstProp.SetValue(destination, srcProp.GetValue(this, null), null); } } } diff --git a/AlphaFS/Resources.Designer.cs b/AlphaFS/Resources.Designer.cs index d046c5b93..5ccea7015 100644 --- a/AlphaFS/Resources.Designer.cs +++ b/AlphaFS/Resources.Designer.cs @@ -61,7 +61,7 @@ internal Resources() { } /// - /// Looks up a localized string similar to Argument must be a drive letter from a-z, volume GUID or a device path.. + /// Looks up a localized string similar to Argument must be a drive letter from a-z, a volume GUID or device path.. /// internal static string Argument_must_be_DriveLetter_or_VolumeGuid_or_DevicePath { get { diff --git a/AlphaFS/Resources.resx b/AlphaFS/Resources.resx index 983d78154..d299cd670 100644 --- a/AlphaFS/Resources.resx +++ b/AlphaFS/Resources.resx @@ -260,6 +260,6 @@ No drive letters available. - Argument must be a drive letter from a-z, volume GUID or a device path. + Argument must be a drive letter from a-z, a volume GUID or device path. From 1de63a025664ceede2967435d1f94050704ac925 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 3 Feb 2018 02:25:53 +0100 Subject: [PATCH 017/133] Code improvement, work in progress. --- ... AlphaFS_Device.EnumerateLogicalDrives.cs} | 12 +-- ....cs => AlphaFS_Device.EnumerateVolumes.cs} | 4 +- .../AlphaFS.Volume.SetVolumeLabel.cs | 2 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 4 +- AlphaFS/AlphaFS.csproj | 4 +- ...es.cs => Device.EnumerateLogicalDrives.cs} | 29 ++++++- .../Device/Device.EnumeratePhysicalDrives.cs | 61 ++++++++++++- ...mVolumes.cs => Device.EnumerateVolumes.cs} | 37 +++----- AlphaFS/Device/PhysicalDriveInfo.cs | 30 ++----- .../Volume/Volume.EnumerateVolumePathNames.cs | 29 +++++-- AlphaFS/Device/Volume/VolumeInfo.cs | 87 +++++++++---------- .../NativeMethods.VolumeManagement.cs | 2 +- .../Filesystem/Native Other/IoControlCode.cs | 19 ++-- .../Native Other/STORAGE_DEVICE_TYPE.cs | 9 +- .../Path.GetFinalPathNameByHandle.cs | 2 +- .../Structures, Enumerations/DeviceGuid.cs | 2 +- 16 files changed, 192 insertions(+), 141 deletions(-) rename AlphaFS.UnitTest/AlphaFS Device Class/{AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs => AlphaFS_Device.EnumerateLogicalDrives.cs} (89%) rename AlphaFS.UnitTest/AlphaFS Device Class/{AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs => AlphaFS_Device.EnumerateVolumes.cs} (93%) rename AlphaFS/Device/{Device.EnumeratePhysicalDrivesFromLogicalDrives.cs => Device.EnumerateLogicalDrives.cs} (76%) rename AlphaFS/Device/{Device.EnumeratePhysicalDrivesFromVolumes.cs => Device.EnumerateVolumes.cs} (62%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs similarity index 89% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs index e2d868167..856835222 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromLogicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs @@ -31,25 +31,25 @@ public partial class AlphaFS_DeviceTest [TestMethod] - public void AlphaFS_Device_EnumeratePhysicalDrivesFromLogicalDrives_Local_Success() + public void AlphaFS_Device_EnumerateLogicalDrives_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); var driveCount = 0; - var drives = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDrivesFromLogicalDrives().ToArray(); + var drives = Alphaleonis.Win32.Filesystem.Device.EnumerateLogicalDrives().ToArray(); foreach (var drive in drives) + foreach (var driveInfo in drive.DriveInfo) { Console.WriteLine(); - Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, drive.DriveInfo.Name); + Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, driveInfo.Name); UnitTestConstants.Dump(drive, -17); - - - Console.WriteLine(); } + Console.WriteLine(); + Assert.IsTrue(drives.Length > 0); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs similarity index 93% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs index 1a0a60c0a..542dbfc5b 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrivesFromVolumes.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs @@ -31,13 +31,13 @@ public partial class AlphaFS_DeviceTest [TestMethod] - public void AlphaFS_Device_EnumeratePhysicalDrivesFromVolumes_Local_Success() + public void AlphaFS_Device_EnumerateVolumes_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); var volumeCount = 0; - var volumes = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDrivesFromVolumes().ToArray(); + var volumes = Alphaleonis.Win32.Filesystem.Device.EnumerateVolumes().ToArray(); foreach (var drive in volumes) { diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs index 53e3a30ad..c57a4e5e5 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs @@ -29,7 +29,7 @@ public partial class AlphaFS_VolumeTest // Pattern: ___ - [TestMethod] + //[TestMethod] public void AlphaFS_Volume_SetVolumeLabel_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index c0c870de0..7a47902f2 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -148,8 +148,8 @@ - - + + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index c5b124296..04c0eba00 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -198,8 +198,8 @@ - - + + diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs b/AlphaFS/Device/Device.EnumerateLogicalDrives.cs similarity index 76% rename from AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs rename to AlphaFS/Device/Device.EnumerateLogicalDrives.cs index bdc5eccf4..21b1251b4 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromLogicalDrives.cs +++ b/AlphaFS/Device/Device.EnumerateLogicalDrives.cs @@ -20,8 +20,8 @@ */ using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; -using System.Net.Sockets; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -31,8 +31,25 @@ public static partial class Device /// [AlphaFS] Enumerates the logical drives and associated physical drives on the Computer. /// An IEnumerable of type that represents the physical drives on the Computer. [SecurityCritical] - public static IEnumerable EnumeratePhysicalDrivesFromLogicalDrives() + public static IEnumerable EnumerateLogicalDrives() { + //var pDrives = new Collection(); + + //var logicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName).ToArray(); + + + //foreach (var pDrive in EnumeratePhysicalDrives().Where(drive => null != drive.DriveInfo)) + //{ + // foreach (var driveInfo in pDrive.DriveInfo) + // { + // pDrives.Add(pDrive); + // } + //} + + + //return pDrives; + + var physicalDrives = EnumeratePhysicalDrives().ToArray(); var logicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName).ToArray(); @@ -48,14 +65,18 @@ public static IEnumerable EnumeratePhysicalDrivesFromLogicalD foreach (var pDrive in physicalDrives.Where(pDrive => pDrive.DeviceNumber == pDriveInfo.DeviceNumber)) { - pDrive.CopyTo(pDriveInfo); + CopyTo(pDrive, pDriveInfo); // Get the first entry that starts with a logical drive path, such as: "C:", "D:". if (Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath)) { - pDriveInfo.DriveInfo = new DriveInfo(drive); + if (null == pDriveInfo.DriveInfo) + pDriveInfo.DriveInfo= new Collection(); + + + pDriveInfo.DriveInfo.Add(new DriveInfo(drive)); var guid = Volume.GetVolumeGuid(drive); diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs index a36625187..9aff32eab 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs @@ -20,6 +20,7 @@ */ using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using System.Security; @@ -32,13 +33,65 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrives() { - return EnumerateDevicesCore(null, DeviceGuid.Disk, false) + var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ToArray(); - .Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)) + //var volumes = Volume.EnumerateVolumes().Select(volume => GetPhysicalDriveInfoCore(volume, null, false)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ThenBy(physicalDrive => physicalDrive.PartitionNumber).ToArray(); - .Where(physicalDrive => null != physicalDrive) + //var logicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(driveName, null, false)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ThenBy(physicalDrive => physicalDrive.PartitionNumber).ToArray(); - .OrderBy(disk => disk.DeviceNumber); + + //var populatedPhysicalDrives = new Collection(); + + + //foreach (var volume in volumes) + //{ + // foreach (var pDrive in physicalDrives.Where(pDrive => pDrive.DeviceNumber == volume.DeviceNumber)) + // { + // CopyTo(pDrive, volume); + + + // foreach (var lDrive in Volume.EnumerateVolumePathNames(volume.DevicePath).Where(drive => !Utils.IsNullOrWhiteSpace(drive) && Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath))) + // { + // if (null == volume.DriveInfo) + // volume.DriveInfo = new Collection(); + + // volume.DriveInfo.Add(new DriveInfo(lDrive)); + // } + + + // volume.VolumeGuids = new[] {volume.DevicePath}; + + // populatedPhysicalDrives.Add(volume); + + // break; + // } + //} + + + //return populatedPhysicalDrives.OrderBy(pDriveInfo => pDriveInfo.DeviceNumber).ThenBy(pDriveInfo => pDriveInfo.PartitionNumber); + + return physicalDrives.OrderBy(pDriveInfo => pDriveInfo.DeviceNumber).ThenBy(pDriveInfo => pDriveInfo.PartitionNumber); + } + + + private static void CopyTo(T source, T destination) + { + // Properties listed here should not be overwritten by the physical drive template. + + var excludedProps = new[] {"PartitionNumber"}; + + + var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite && !excludedProps.Any(prop => prop.Equals(x.Name))).ToArray(); + + var dstProps = srcProps.ToArray(); + + + foreach (var srcProp in srcProps) + { + var dstProp = dstProps.First(x => x.Name.Equals(srcProp.Name)); + + dstProp.SetValue(destination, srcProp.GetValue(source, null), null); + } } } } diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs b/AlphaFS/Device/Device.EnumerateVolumes.cs similarity index 62% rename from AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs rename to AlphaFS/Device/Device.EnumerateVolumes.cs index 493bd8687..19db46c77 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrivesFromVolumes.cs +++ b/AlphaFS/Device/Device.EnumerateVolumes.cs @@ -31,26 +31,17 @@ public static partial class Device /// [AlphaFS] Enumerates the volumes and associated physical drives on the Computer. /// An IEnumerable of type that represents the physical drives on the Computer. [SecurityCritical] - public static IEnumerable EnumeratePhysicalDrivesFromVolumes() + public static IEnumerable EnumerateVolumes() { - var physicalDrives = EnumeratePhysicalDrives().ToArray(); + var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).Where(physicalDrive => null != physicalDrive).OrderBy(disk => disk.DeviceNumber).ToArray(); - var volumes = Volume.EnumerateVolumes(); + var volumeGuids = Volume.EnumerateVolumes().ToArray(); - //var volumes = EnumerateDevicesCore(null, DeviceGuid.Volume, false) - // .Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo, false)) + var populatedPhysicalDrives = new Collection(); - // .Where(physicalDrive => null != physicalDrive) - // .OrderBy(disk => disk.DeviceNumber).ThenBy(disk => disk.PartitionNumber).ToArray(); - - - - var allDrives = new Collection(); - - - foreach (var volume in volumes) + foreach (var volume in volumeGuids) { var pDriveInfo = GetPhysicalDriveInfoCore(volume, null, false); @@ -60,32 +51,28 @@ public static IEnumerable EnumeratePhysicalDrivesFromVolumes( foreach (var pDrive in physicalDrives.Where(pDrive => pDrive.DeviceNumber == pDriveInfo.DeviceNumber)) { - pDrive.CopyTo(pDriveInfo); + CopyTo(pDrive, pDriveInfo); - foreach (var drive in Volume.EnumerateVolumePathNames(volume)) + foreach (var lDrive in Volume.EnumerateVolumePathNames(volume).Where(drive => !Utils.IsNullOrWhiteSpace(drive) && Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath))) { - // Get the first entry that starts with a logical drive path, such as: "C:", "D:". - - if (!Utils.IsNullOrWhiteSpace(drive) && Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath)) - { - pDriveInfo.DriveInfo = new DriveInfo(drive); + if (null == pDriveInfo.DriveInfo) + pDriveInfo.DriveInfo = new Collection(); - break; - } + pDriveInfo.DriveInfo.Add(new DriveInfo(lDrive)); } pDriveInfo.VolumeGuids = new[] {volume}; - allDrives.Add(pDriveInfo); + populatedPhysicalDrives.Add(pDriveInfo); break; } } - return allDrives.OrderBy(pDriveInfo => pDriveInfo.DeviceNumber).ThenBy(pDriveInfo => pDriveInfo.PartitionNumber); + return populatedPhysicalDrives.OrderBy(pDriveInfo => pDriveInfo.DeviceNumber).ThenBy(pDriveInfo => pDriveInfo.PartitionNumber); } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo.cs index b9bded5be..88730f3b0 100644 --- a/AlphaFS/Device/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo.cs @@ -20,6 +20,8 @@ */ using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Security; @@ -93,7 +95,8 @@ public override string ToString() public string DevicePath { get; internal set; } - public DriveInfo DriveInfo { get; internal set; } + /// The logical drives that are located on the physical drive. + public Collection DriveInfo { get; internal set; } /// Indicates if the physical drive supports multiple outstanding commands (SCSI tagged queuing or equivalent). When false the physical drive does not support SCSI-tagged queuing or the equivalent. @@ -135,30 +138,7 @@ public string TotalSizeUnitSize } - /// The Volumes located on the physical drive. + /// The volumes that are located on the physical drive. public string[] VolumeGuids { get; set; } - - - - - internal void CopyTo(T destination) - { - // Properties listed here should not be overwritten by the physical drive template. - - var excludedProps = new[] {"PartitionNumber"}; - - - var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite && !excludedProps.Any(prop => prop.Equals(x.Name))).ToArray(); - - var dstProps = srcProps.Where(x => x.CanWrite).ToArray(); - - - foreach (var srcProp in srcProps) - { - var dstProp = dstProps.First(x => x.Name.Equals(srcProp.Name)); - - dstProp.SetValue(destination, srcProp.GetValue(this, null), null); - } - } } } diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs index 492493a5a..0c93bc2a8 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs @@ -45,14 +45,14 @@ public static IEnumerable EnumerateVolumePathNames(string volumeGuid) throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid"); - var requiredLength = 50; - var buffer = new StringBuilder(requiredLength); + uint bufferSize = 50; + var buffer = new char[bufferSize]; volumeGuid = Path.AddTrailingDirectorySeparator(volumeGuid, false); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) - while (!NativeMethods.GetVolumePathNamesForVolumeName(volumeGuid, buffer, (uint) buffer.Capacity, out requiredLength)) + while (!NativeMethods.GetVolumePathNamesForVolumeName(volumeGuid, buffer, (uint) buffer.Length, out bufferSize)) { var lastError = Marshal.GetLastWin32Error(); @@ -60,8 +60,7 @@ public static IEnumerable EnumerateVolumePathNames(string volumeGuid) { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: - requiredLength *= 2; - buffer = new StringBuilder(requiredLength); + buffer = new char[bufferSize]; break; default: @@ -70,7 +69,25 @@ public static IEnumerable EnumerateVolumePathNames(string volumeGuid) } } - yield return buffer.ToString(); + + var pathNameBuffer = new StringBuilder(buffer.Length); + + foreach (var c in buffer) + { + if (c != Path.StringTerminatorChar) + + pathNameBuffer.Append(c); + + else + { + if (pathNameBuffer.Length > 0) + { + yield return pathNameBuffer.ToString(); + + pathNameBuffer.Length = 0; + } + } + } } } } diff --git a/AlphaFS/Device/Volume/VolumeInfo.cs b/AlphaFS/Device/Volume/VolumeInfo.cs index b15d4832f..9119c7871 100644 --- a/AlphaFS/Device/Volume/VolumeInfo.cs +++ b/AlphaFS/Device/Volume/VolumeInfo.cs @@ -38,6 +38,7 @@ public sealed class VolumeInfo [NonSerialized] private readonly bool _continueOnAccessError; [NonSerialized] private readonly SafeFileHandle _volumeHandle; + [NonSerialized] private string _guid; [NonSerialized] private NativeMethods.VOLUME_INFO_FLAGS _volumeInfoAttributes; #endregion // Private Fields @@ -48,32 +49,32 @@ public sealed class VolumeInfo /// Initializes a VolumeInfo instance. /// /// - /// 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. + /// 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. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] - public VolumeInfo(string volumeName) + public VolumeInfo(string driveName) { - if (Utils.IsNullOrWhiteSpace(volumeName)) - throw new ArgumentNullException("volumeName"); + if (Utils.IsNullOrWhiteSpace(driveName)) + throw new ArgumentNullException("driveName"); - if (!volumeName.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal)) - volumeName = Path.IsUncPathCore(volumeName, false, false) ? Path.GetLongPathCore(volumeName, GetFullPathOptions.None) : Path.LongPathPrefix + volumeName; + if (!driveName.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal)) + driveName = Path.IsUncPathCore(driveName, false, false) ? Path.GetLongPathCore(driveName, GetFullPathOptions.None) : Path.LongPathPrefix + driveName; else { - volumeName = volumeName.Length == 1 ? volumeName + Path.VolumeSeparatorChar : Path.GetPathRoot(volumeName, false); + driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); - if (!volumeName.StartsWith(Path.GlobalRootPrefix, StringComparison.OrdinalIgnoreCase)) - volumeName = Path.GetPathRoot(volumeName, false); + if (!driveName.StartsWith(Path.GlobalRootPrefix, StringComparison.OrdinalIgnoreCase)) + driveName = Path.GetPathRoot(driveName, false); } - if (Utils.IsNullOrWhiteSpace(volumeName)) - throw new ArgumentException(Resources.InvalidDriveLetterArgument, "volumeName"); + if (Utils.IsNullOrWhiteSpace(driveName)) + throw new ArgumentException(Resources.InvalidDriveLetterArgument, "driveName"); - Name = Path.AddTrailingDirectorySeparator(volumeName, false); + Name = Path.AddTrailingDirectorySeparator(driveName, false); _volumeHandle = null; } @@ -176,14 +177,15 @@ public bool DirectAccess public string FullPath { get; private set; } - private string _guid; /// The volume GUID. public string Guid { get { - return _guid ?? (_guid = !Utils.IsNullOrWhiteSpace(FullPath) ? Volume.GetUniqueVolumeNameForPath(FullPath) : null); + return _guid ?? (_guid = !Utils.IsNullOrWhiteSpace(FullPath) ? Volume.GetVolumeGuid(FullPath) : null); } + + private set { _guid = value; } } @@ -344,52 +346,49 @@ public void Refresh() { 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) + ? 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); + : 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) - break; - - - 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; - } + if (!success) + switch (lastError) + { + case Win32Errors.ERROR_NOT_READY: + if (!_continueOnAccessError) + throw new DeviceNotReadyException(Name, true); + break; + + case Win32Errors.ERROR_MORE_DATA: + //This code should never execute. + volumeNameBuffer.Capacity *= 2; + fileSystemNameBuffer.Capacity *= 2; + break; + + default: + if (!_continueOnAccessError) + NativeError.ThrowException(lastError, Name); + 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; + Name = volumeNameBuffer.ToString(); + MaximumComponentLength = maximumComponentLength; + SerialNumber = serialNumber; + FileSystemName = fileSystemNameBuffer.ToString(); + FileSystemName = !Utils.IsNullOrWhiteSpace(FileSystemName) ? FileSystemName : null; + DriveType = Volume.GetDriveType(FullPath); } diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs index cc8664ca9..14e35236f 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs @@ -260,7 +260,7 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumePathNamesForVolumeNameW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool GetVolumePathNamesForVolumeName([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName, StringBuilder lpszVolumePathNames, [MarshalAs(UnmanagedType.U4)] uint cchBuferLength, [MarshalAs(UnmanagedType.U4)] out int lpcchReturnLength); + internal static extern bool GetVolumePathNamesForVolumeName([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName, char[] lpszVolumePathNames, [MarshalAs(UnmanagedType.U4)] uint cchBuferLength, [MarshalAs(UnmanagedType.U4)] out uint lpcchReturnLength); /// Sets the label of a file system volume. diff --git a/AlphaFS/Filesystem/Native Other/IoControlCode.cs b/AlphaFS/Filesystem/Native Other/IoControlCode.cs index 4b5ea68d8..f220e9adb 100644 --- a/AlphaFS/Filesystem/Native Other/IoControlCode.cs +++ b/AlphaFS/Filesystem/Native Other/IoControlCode.cs @@ -31,15 +31,7 @@ internal static partial class NativeMethods [Flags] internal enum IoControlCode : uint { - // VIDEO - //VideoQuerySupportedBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0125 << 2) | IoMethod.Buffered | (0 << 14), - //VideoQueryDisplayBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0126 << 2) | IoMethod.Buffered | (0 << 14), - //VideoSetDisplayBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0127 << 2) | IoMethod.Buffered | (0 << 14), - - /// Retrieves the physical location of a specified volume on one or more disks. - //IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), - IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), @@ -47,8 +39,6 @@ internal enum IoControlCode : uint IOCTL_STORAGE_QUERY_PROPERTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x500 << 2) | IoMethod.Buffered | (0 << 14), - - #region FILE_DEVICE_MASS_STORAGE ///// Determines whether the media has changed on a removable-media device that the caller has opened for read or write access. If read or write access to the device is not necessary, the caller can improve performance by opening the device with FILE_READ_ATTRIBUTES and issuing anIOCTL_STORAGE_CHECK_VERIFY2 request instead. @@ -697,6 +687,15 @@ internal enum IoControlCode : uint //FSCTL_GET_BOOT_AREA_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (140 << 2) | IoMethod.Buffered | (0 << 14), #endregion // FILE_DEVICE_FILE_SYSTEM + + + #region VIDEO + + //VideoQuerySupportedBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0125 << 2) | IoMethod.Buffered | (0 << 14), + //VideoQueryDisplayBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0126 << 2) | IoMethod.Buffered | (0 << 14), + //VideoSetDisplayBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0127 << 2) | IoMethod.Buffered | (0 << 14), + + #endregion // VIDEO } } } diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs index eea8cd3df..2299105da 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs @@ -255,13 +255,8 @@ internal enum STORAGE_DEVICE_TYPE /// FILE_DEVICE_SYSENV parameter. FILE_DEVICE_SYSENV = 82, - - /// [AlphaFS] FILE_DEVICE_MASS_STORAGE parameter. - FILE_DEVICE_VOLUME = 86, - - - /// [AlphaFS] FILE_DEVICE_MASS_STORAGE parameter. - IOCTL_STORAGE_QUERY_PROPERTY = 86, + /// FILE_DEVICE_MASS_STORAGE parameter. + FILE_DEVICE_VOLUME = 86 } } } diff --git a/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs b/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs index ba3dbdeca..3d297e2e7 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs @@ -162,7 +162,7 @@ internal static string GetFinalPathNameByHandleCore(SafeFileHandle handle, Final .Where(drv => driveLetter.Equals(RemoveTrailingDirectorySeparator(drv), StringComparison.OrdinalIgnoreCase))) - return CombineCore(false, Volume.GetUniqueVolumeNameForPath(drive), GetSuffixedDirectoryNameWithoutRootCore(null, dosPath), file); + return CombineCore(false, Volume.GetVolumeGuid(drive), GetSuffixedDirectoryNameWithoutRootCore(null, dosPath), file); } break; diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs index 358e925e4..a489ed0cb 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs @@ -152,7 +152,7 @@ public enum DeviceGuid [Description("53F56312-B6BF-11D0-94F2-00A0C91EFB8B")] CDChanger, /// The GUID_DEVINTERFACE_CDROM device interface class is defined for CD-ROM storage devices. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "rom")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CDROM")] [Description("53F56308-B6BF-11D0-94F2-00A0C91EFB8B")] CDROM, From cc88f4eb7d1b5096ff9449acfb930e2849379cc2 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 3 Feb 2018 02:47:36 +0100 Subject: [PATCH 018/133] Fixed infinite loop. --- AlphaFS/Device/Volume/VolumeInfo.cs | 53 +++++++++++++++++------------ 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/AlphaFS/Device/Volume/VolumeInfo.cs b/AlphaFS/Device/Volume/VolumeInfo.cs index 9119c7871..1430e955c 100644 --- a/AlphaFS/Device/Volume/VolumeInfo.cs +++ b/AlphaFS/Device/Volume/VolumeInfo.cs @@ -182,10 +182,19 @@ public string Guid { get { - return _guid ?? (_guid = !Utils.IsNullOrWhiteSpace(FullPath) ? Volume.GetVolumeGuid(FullPath) : null); + if (null == _guid) + { + try + { + _guid = !Utils.IsNullOrWhiteSpace(FullPath) ? Volume.GetVolumeGuid(FullPath) : null; + } + catch + { + } + } + + return _guid; } - - private set { _guid = value; } } @@ -352,27 +361,29 @@ public void Refresh() : NativeMethods.GetVolumeInformation(Path.AddTrailingDirectorySeparator(Name, false), volumeNameBuffer, (uint) volumeNameBuffer.Capacity, out serialNumber, out maximumComponentLength, out _volumeInfoAttributes, fileSystemNameBuffer, (uint) fileSystemNameBuffer.Capacity); - lastError = (uint)Marshal.GetLastWin32Error(); + lastError = (uint) Marshal.GetLastWin32Error(); + + if (success) + break; - if (!success) - switch (lastError) - { - case Win32Errors.ERROR_NOT_READY: - if (!_continueOnAccessError) - throw new DeviceNotReadyException(Name, true); - break; + switch (lastError) + { + case Win32Errors.ERROR_NOT_READY: + if (!_continueOnAccessError) + throw new DeviceNotReadyException(Name, true); + break; - case Win32Errors.ERROR_MORE_DATA: - //This code should never execute. - volumeNameBuffer.Capacity *= 2; - fileSystemNameBuffer.Capacity *= 2; - break; + case Win32Errors.ERROR_MORE_DATA: + //This code should never execute. + volumeNameBuffer.Capacity *= 2; + fileSystemNameBuffer.Capacity *= 2; + break; - default: - if (!_continueOnAccessError) - NativeError.ThrowException(lastError, Name); - break; - } + default: + if (!_continueOnAccessError) + NativeError.ThrowException(lastError, Name); + break; + } } while (lastError == Win32Errors.ERROR_MORE_DATA); } From 1b527d2ddbde80428c0b3db003fbf496644d5b41 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 3 Feb 2018 02:59:54 +0100 Subject: [PATCH 019/133] Code improvement, work in progress. --- AlphaFS/Device/Device.GetDeviceIoData.cs | 6 ++++-- AlphaFS/Device/Device.GetPhysicalDriveInfo.cs | 15 +++++++++++++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/AlphaFS/Device/Device.GetDeviceIoData.cs b/AlphaFS/Device/Device.GetDeviceIoData.cs index ae1742eae..7189ddcd6 100644 --- a/AlphaFS/Device/Device.GetDeviceIoData.cs +++ b/AlphaFS/Device/Device.GetDeviceIoData.cs @@ -52,8 +52,10 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa return safeBuffer; - // CDROM drive without a CD. - if (lastError == Win32Errors.ERROR_NOT_SUPPORTED) + // ERROR_INVALID_FUNCTION: Dynamic disk. + // ERROR_NOT_SUPPORTED : CD/DVD without medium. + + if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_NOT_SUPPORTED) return null; diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs index e9cab9a49..8956bbb78 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs @@ -187,13 +187,24 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi return null; + // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes + // without accessing that file or device, even if GENERIC_READ access would have been denied. + // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + //const int desiredAccess = 0; + + // Requires elevation for. + const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; + + //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; + + // No elevation needed. - using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) + using (var safeHandle = OpenPhysicalDrive(pathToDevice, desiredAccess)) using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, pathToDevice)) - return null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?)null; + return null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?) null; } From e9b97f694d04d8689eb5249d5023f28b452cc4b5 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 3 Feb 2018 17:29:34 +0100 Subject: [PATCH 020/133] Update/cleanup of unit tests. --- ...Directory_EnumerateAlternateDataStreams.cs | 2 +- ...aFS_BackupFileStream_InitializeInstance.cs | 3 +- .../AlphaFS_Directory_GetFileInfo.cs | 2 +- .../AlphaFS_File_GetFileInfoByHandle.cs | 2 +- ...ltSeedAndPolynomialWithShortAsciiString.cs | 3 +- ...tSeedAndPolynomialWithShortAsciiString2.cs | 3 +- ...ltSeedAndPolynomialWithShortAsciiString.cs | 3 +- ...tSeedAndPolynomialWithShortAsciiString2.cs | 3 +- .../AlphaFS_Directory_Compress_Decompress.cs | 2 +- .../AlphaFS_File_Compress_Decompress.cs | 2 +- .../AlphaFS_File_GetCompressedSize.cs | 2 +- .../AlphaFS_Device.EnumerateLogicalDrives.cs | 3 + .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 3 + .../AlphaFS_Device.EnumerateVolumes.cs | 3 + .../AlphaFS_DfsInfoTest.cs | 6 +- .../AlphaFS_Directory_Encryption.cs | 4 +- ...ctory_ExportImportEncryptedDirectoryRaw.cs | 2 +- ...phaFS_File_ExportImportEncryptedFileRaw.cs | 2 +- .../AlphaFS_File_GetHash.cs | 2 +- .../AlphaFS_Directory_GetFileIdInfo.cs | 2 +- .../AlphaFS_File_GetFileIdInfo.cs | 2 +- ...Directory_EnumerateFileSystemEntryInfos.cs | 2 +- .../AlphaFS_Host_EnumerateDfsLinks.cs | 1 - .../AlphaFS_Host_EnumerateDfsRoot.cs | 3 +- .../AlphaFS_Host_EnumerateDomainDfsRoot.cs | 1 - .../AlphaFS_Directory_CopySymbolicLink.cs | 2 +- ...reateSymbolicLink_And_GetLinkTargetInfo.cs | 4 +- .../AlphaFS_Directory_Junction.cs | 6 +- .../AlphaFS_File_CopySymbolicLink.cs | 2 +- ..._File_CreateHardlink_EnumerateHardlinks.cs | 5 +- ..._CreateSymbolicLinkAndGetLinkTargetInfo.cs | 4 +- .../AlphaFS_Shell32Info_GetVerbCommand.cs | 2 +- .../AlphaFS_Shell32Info_InitializeInstance.cs | 2 +- .../AlphaFS_Shell32Test.cs | 11 +- .../Directory_GetTimestamps.cs | 54 +-- .../Directory_SetTimestamps.cs | 6 +- .../AlphaFS Timestamps/File_GetTimestamps.cs | 49 ++- .../AlphaFS Timestamps/File_SetTimestamps.cs | 6 +- .../AlphaFS.Volume.DefineDosDevice.cs | 7 +- ...phaFS.Volume.EnumerateVolumeMountPoints.cs | 6 +- .../AlphaFS.Volume.EnumerateVolumes.cs | 21 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 23 +- .../AlphaFS_Directory.Copy.cs | 2 +- ...ion_UserExplicitDenyOnDestinationFolder.cs | 2 +- ...lphaFS_Directory_CountFileSystemObjects.cs | 8 +- .../Directory_CreateDirectory_And_Delete.cs | 12 +- ...aFS_Directory.DeleteEmptySubdirectories.cs | 2 +- ...toryNotEmptyException_NonEmptyDirectory.cs | 2 +- ...oDifferentVolume_EmulateUsingCopyDelete.cs | 2 +- .../Directory Class/DirectoryTest.cs | 33 +- .../Directory Class/Directory_Exists.cs | 8 +- .../Directory_GetAccessControl.cs | 2 +- .../Directory_GetDirectories.cs | 2 +- .../Directory Class/Directory_GetFiles.cs | 2 +- .../Directory_SetAccessControl.cs | 2 +- .../DirectoryInfo_Attributes.cs | 2 +- .../DirectoryInfo_FolderName255Characters.cs | 4 +- .../DirectoryInfo_InitializeInstance.cs | 4 +- .../DirectoryInfo_MoveTo.cs | 4 +- .../DirectoryInfo_Refresh.cs | 2 +- .../File Class/AlphaFS_File_GetSize.cs | 2 +- .../File Class/AlphaFS_File_IsLocked.cs | 8 +- .../File Class/File.Delete/File_Delete.cs | 8 +- .../File Class/File.Move/File_Move.cs | 2 +- AlphaFS.UnitTest/File Class/FileTest.cs | 22 +- AlphaFS.UnitTest/File Class/File_Create.cs | 4 +- .../File Class/File_CreateText.cs | 2 +- AlphaFS.UnitTest/File Class/File_Exists.cs | 2 +- AlphaFS.UnitTest/File Class/File_Open.cs | 4 +- AlphaFS.UnitTest/File Class/File_OpenRead.cs | 2 +- AlphaFS.UnitTest/File Class/File_OpenText.cs | 2 +- AlphaFS.UnitTest/File Class/File_OpenWrite.cs | 2 +- AlphaFS.UnitTest/File Class/File_Replace.cs | 4 +- .../File Class/File_SetAccessControl.cs | 2 +- .../FileInfo Class/FileInfo_Attributes.cs | 2 +- ...ileInfo_InitializeInstance_ExistingFile.cs | 4 +- .../FileInfo Class/FileInfo_Refresh.cs | 2 +- AlphaFS.UnitTest/Path Class/PathTest.cs | 84 ++--- .../Path Class/Path_GetDirectoryName.cs | 3 +- .../Path Class/Path_GetExtension.cs | 3 +- .../Path Class/Path_GetRelativePath.cs | 4 +- .../Path Class/Path_IsPathRooted.cs | 3 +- .../CreateDirectoriesAndFiles.cs | 2 +- .../CreateFile.cs | 2 +- .../DirectoryAssert.cs | 0 .../{_Utils => UnitTest Utility}/Dump.cs | 0 .../FileAssert.cs | 0 .../FolderDenyPermission.cs | 0 ...etRandomFileNameWithDiacriticCharacters.cs | 67 ++++ .../UnitTest Utility/InputPaths.cs | 122 +++++++ .../{_Utils => UnitTest Utility}/IsAdmin.cs | 0 .../UnitTest Utility/PrintUnitTestHeader.cs | 34 ++ .../UnitTest Utility/StringToByteArray.cs | 37 +++ .../TemporaryDirectory.cs | 6 +- .../UnitTest Utility/TestAccessRules.cs | 80 +++++ .../UnitTest Utility/UnitTestConstants.cs | 74 +++++ AlphaFS.UnitTest/_Utils/UnitTestConstants.cs | 312 ------------------ 97 files changed, 694 insertions(+), 581 deletions(-) rename AlphaFS.UnitTest/{_Utils => UnitTest Utility}/CreateDirectoriesAndFiles.cs (98%) rename AlphaFS.UnitTest/{_Utils => UnitTest Utility}/CreateFile.cs (97%) rename AlphaFS.UnitTest/{_Utils => UnitTest Utility}/DirectoryAssert.cs (100%) rename AlphaFS.UnitTest/{_Utils => UnitTest Utility}/Dump.cs (100%) rename AlphaFS.UnitTest/{_Utils => UnitTest Utility}/FileAssert.cs (100%) rename AlphaFS.UnitTest/{_Utils => UnitTest Utility}/FolderDenyPermission.cs (100%) create mode 100644 AlphaFS.UnitTest/UnitTest Utility/GetRandomFileNameWithDiacriticCharacters.cs create mode 100644 AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs rename AlphaFS.UnitTest/{_Utils => UnitTest Utility}/IsAdmin.cs (100%) create mode 100644 AlphaFS.UnitTest/UnitTest Utility/PrintUnitTestHeader.cs create mode 100644 AlphaFS.UnitTest/UnitTest Utility/StringToByteArray.cs rename AlphaFS.UnitTest/{_Utils => UnitTest Utility}/TemporaryDirectory.cs (94%) create mode 100644 AlphaFS.UnitTest/UnitTest Utility/TestAccessRules.cs create mode 100644 AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs delete mode 100644 AlphaFS.UnitTest/_Utils/UnitTestConstants.cs diff --git a/AlphaFS.UnitTest/AlphaFS Alternate Data Streams/AlphaFS_Directory_EnumerateAlternateDataStreams.cs b/AlphaFS.UnitTest/AlphaFS Alternate Data Streams/AlphaFS_Directory_EnumerateAlternateDataStreams.cs index 05261f47f..7d25bc696 100644 --- a/AlphaFS.UnitTest/AlphaFS Alternate Data Streams/AlphaFS_Directory_EnumerateAlternateDataStreams.cs +++ b/AlphaFS.UnitTest/AlphaFS Alternate Data Streams/AlphaFS_Directory_EnumerateAlternateDataStreams.cs @@ -43,7 +43,7 @@ private void Directory_EnumerateAlternateDataStreams(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = Alphaleonis.Win32.Filesystem.Path.GetTempPath("Directory-EnumerateAlternateDataStreams-" + UnitTestConstants.GetRandomFileName()); + var tempPath = Alphaleonis.Win32.Filesystem.Path.GetTempPath("Directory-EnumerateAlternateDataStreams-" + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters()); if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs index 9fe4fabb3..adc0de507 100644 --- a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs +++ b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs @@ -47,7 +47,8 @@ private void BackupFileStream_InitializeInstance(bool isNetwork) UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_Directory_GetFileInfo.cs b/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_Directory_GetFileInfo.cs index 8e1eb5746..db6395e8c 100644 --- a/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_Directory_GetFileInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_Directory_GetFileInfo.cs @@ -44,7 +44,7 @@ private void Directory_GetFileInfoByHandle(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_File_GetFileInfoByHandle.cs b/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_File_GetFileInfoByHandle.cs index 7b08c7aaa..46e4f0d17 100644 --- a/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_File_GetFileInfoByHandle.cs +++ b/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_File_GetFileInfoByHandle.cs @@ -44,7 +44,7 @@ private void File_GetFileInfoByHandle(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc32_StaticDefaultSeedAndPolynomialWithShortAsciiString.cs b/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc32_StaticDefaultSeedAndPolynomialWithShortAsciiString.cs index 7010cb4d1..c4952f056 100644 --- a/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc32_StaticDefaultSeedAndPolynomialWithShortAsciiString.cs +++ b/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc32_StaticDefaultSeedAndPolynomialWithShortAsciiString.cs @@ -39,9 +39,10 @@ public void AlphaFS_Crc32_StaticDefaultSeedAndPolynomialWithShortAsciiString() var hash = crc32.ComputeHash(System.Text.Encoding.ASCII.GetBytes(text)).Aggregate(string.Empty, (current, b) => current + b.ToString("x2").ToLower()); Console.WriteLine("Input text: {0}", text); + Console.WriteLine("\n\tCRC32: {0}", hash); - Assert.AreEqual("7a18a923", hash); + Assert.AreEqual("742863eb", hash); } } } diff --git a/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc32_StaticDefaultSeedAndPolynomialWithShortAsciiString2.cs b/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc32_StaticDefaultSeedAndPolynomialWithShortAsciiString2.cs index 5ffd94cd6..39854f85c 100644 --- a/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc32_StaticDefaultSeedAndPolynomialWithShortAsciiString2.cs +++ b/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc32_StaticDefaultSeedAndPolynomialWithShortAsciiString2.cs @@ -39,9 +39,10 @@ public void AlphaFS_Crc32_StaticDefaultSeedAndPolynomialWithShortAsciiString2() var hash = crc32.ComputeHash(System.Text.Encoding.ASCII.GetBytes(text)).Aggregate(string.Empty, (current, b) => current + b.ToString("x2").ToLower()); Console.WriteLine("Input text: {0}", text); + Console.WriteLine("\n\tCRC32: {0}", hash); - Assert.AreEqual("85cd3815", hash); + Assert.AreEqual("c193b48c", hash); } } } diff --git a/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc64Iso_StaticDefaultSeedAndPolynomialWithShortAsciiString.cs b/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc64Iso_StaticDefaultSeedAndPolynomialWithShortAsciiString.cs index aca526ff5..dd3455422 100644 --- a/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc64Iso_StaticDefaultSeedAndPolynomialWithShortAsciiString.cs +++ b/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc64Iso_StaticDefaultSeedAndPolynomialWithShortAsciiString.cs @@ -39,9 +39,10 @@ public void AlphaFS_Crc64Iso_StaticDefaultSeedAndPolynomialWithShortAsciiString( var hash = crc64.ComputeHash(System.Text.Encoding.ASCII.GetBytes(text)).Aggregate(string.Empty, (current, b) => current + b.ToString("x2").ToLower()); Console.WriteLine("Input text: {0}", text); + Console.WriteLine("\n\tCRC64: {0}", hash); - Assert.AreEqual("724293319a37353f", hash); + Assert.AreEqual("d7931f909aa8e0c5", hash); } } } diff --git a/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc64Iso_StaticDefaultSeedAndPolynomialWithShortAsciiString2.cs b/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc64Iso_StaticDefaultSeedAndPolynomialWithShortAsciiString2.cs index dd4c40ba9..4a7df8af5 100644 --- a/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc64Iso_StaticDefaultSeedAndPolynomialWithShortAsciiString2.cs +++ b/AlphaFS.UnitTest/AlphaFS CRC Class/AlphaFS_Crc64Iso_StaticDefaultSeedAndPolynomialWithShortAsciiString2.cs @@ -39,9 +39,10 @@ public void AlphaFS_Crc64Iso_StaticDefaultSeedAndPolynomialWithShortAsciiString2 var hash = crc64.ComputeHash(System.Text.Encoding.ASCII.GetBytes(text)).Aggregate(string.Empty, (current, b) => current + b.ToString("x2").ToLower()); Console.WriteLine("Input text: {0}", text); + Console.WriteLine("\n\tCRC64: {0}", hash); - Assert.AreEqual("4553d9246a204d67", hash); + Assert.AreEqual("cff603319a3736cc", hash); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_Directory_Compress_Decompress.cs b/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_Directory_Compress_Decompress.cs index 671c16d9f..f81f27e99 100644 --- a/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_Directory_Compress_Decompress.cs +++ b/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_Directory_Compress_Decompress.cs @@ -52,7 +52,7 @@ private void Directory_Compress_And_Decompress(bool isNetwork, bool recursive) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File_Compress_Decompress.cs b/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File_Compress_Decompress.cs index e87be590c..b01b7f5bb 100644 --- a/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File_Compress_Decompress.cs +++ b/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File_Compress_Decompress.cs @@ -44,7 +44,7 @@ private void File_Compress_And_Decompress(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File_GetCompressedSize.cs b/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File_GetCompressedSize.cs index 051d2f2a2..b7511e3fb 100644 --- a/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File_GetCompressedSize.cs +++ b/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File_GetCompressedSize.cs @@ -44,7 +44,7 @@ private void File_GetCompressedSize(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs index 856835222..afa22d9cf 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs @@ -33,6 +33,9 @@ public partial class AlphaFS_DeviceTest [TestMethod] public void AlphaFS_Device_EnumerateLogicalDrives_Local_Success() { + if (!UnitTestConstants.IsAdmin()) + Assert.Inconclusive(); + UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs index d163750e6..8b85203b9 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -33,6 +33,9 @@ public partial class AlphaFS_DeviceTest [TestMethod] public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() { + if (!UnitTestConstants.IsAdmin()) + Assert.Inconclusive(); + UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs index 542dbfc5b..9a4bfae4a 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs @@ -33,6 +33,9 @@ public partial class AlphaFS_DeviceTest [TestMethod] public void AlphaFS_Device_EnumerateVolumes_Local_Success() { + if (!UnitTestConstants.IsAdmin()) + Assert.Inconclusive(); + UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS DfsInfo Class/AlphaFS_DfsInfoTest.cs b/AlphaFS.UnitTest/AlphaFS DfsInfo Class/AlphaFS_DfsInfoTest.cs index 3582255a0..578e8263e 100644 --- a/AlphaFS.UnitTest/AlphaFS DfsInfo Class/AlphaFS_DfsInfoTest.cs +++ b/AlphaFS.UnitTest/AlphaFS DfsInfo Class/AlphaFS_DfsInfoTest.cs @@ -37,7 +37,6 @@ public void AlphaFS_DfsInfo() var cnt = 0; var noDomainConnection = true; - UnitTestConstants.StopWatcher(true); try { foreach (var dfsNamespace in Host.EnumerateDomainDfsRoot()) @@ -69,7 +68,7 @@ public void AlphaFS_DfsInfo() Console.WriteLine("\n\t(1) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } } - Console.Write("\n{0}", UnitTestConstants.Reporter()); + Console.WriteLine(); if (cnt == 0) Assert.Inconclusive("Nothing is enumerated, but it is expected."); @@ -83,7 +82,8 @@ public void AlphaFS_DfsInfo() Console.WriteLine("\n\t(2) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } - Console.WriteLine("\n\n\t{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); + Console.WriteLine(); if (noDomainConnection) Assert.Inconclusive("Test ignored because the computer is either not connected to a domain or no DFS root exists."); diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encryption.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encryption.cs index d8a100989..3bff101f4 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encryption.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encryption.cs @@ -52,7 +52,7 @@ private void Directory_Encrypt_And_Decrypt(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -112,7 +112,7 @@ private void Directory_Encrypt_And_Decrypt_Recursive(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_ExportImportEncryptedDirectoryRaw.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_ExportImportEncryptedDirectoryRaw.cs index 277e6f5ed..884f70537 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_ExportImportEncryptedDirectoryRaw.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_ExportImportEncryptedDirectoryRaw.cs @@ -43,7 +43,7 @@ private void Directory_ExportImportEncryptedDirectoryRaw(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_ExportImportEncryptedFileRaw.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_ExportImportEncryptedFileRaw.cs index 10d874023..a05cc57db 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_ExportImportEncryptedFileRaw.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_ExportImportEncryptedFileRaw.cs @@ -43,7 +43,7 @@ private void File_ExportImportEncryptedFileRaw(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_GetHash.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_GetHash.cs index eb99453b9..7d64539a5 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_GetHash.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_GetHash.cs @@ -43,7 +43,7 @@ private void File_GetHash(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_Directory_GetFileIdInfo.cs b/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_Directory_GetFileIdInfo.cs index 9c01b5443..34da7d0a5 100644 --- a/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_Directory_GetFileIdInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_Directory_GetFileIdInfo.cs @@ -44,7 +44,7 @@ private void Directory_GetFileIdInfo(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_File_GetFileIdInfo.cs b/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_File_GetFileIdInfo.cs index c789b7420..8ea49c666 100644 --- a/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_File_GetFileIdInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_File_GetFileIdInfo.cs @@ -44,7 +44,7 @@ private void File_GetFileIdInfo(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_EnumerateFileSystemEntryInfos.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_EnumerateFileSystemEntryInfos.cs index f00fe3bef..ce9877244 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_EnumerateFileSystemEntryInfos.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_EnumerateFileSystemEntryInfos.cs @@ -76,7 +76,7 @@ private void Directory_EnumerateFileSystemEntryInfos_FolderWithSpaceAsName(bool { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDfsLinks.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDfsLinks.cs index c6d3bd355..26bad16b8 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDfsLinks.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDfsLinks.cs @@ -37,7 +37,6 @@ public void AlphaFS_Host_EnumerateDfsLinks_Network_Success() var cnt = 0; var noDomainConnection = true; - UnitTestConstants.StopWatcher(true); try { foreach (var dfsNamespace in Alphaleonis.Win32.Network.Host.EnumerateDomainDfsRoot()) diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDfsRoot.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDfsRoot.cs index 23c652a7c..e92d56527 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDfsRoot.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDfsRoot.cs @@ -36,7 +36,6 @@ public void AlphaFS_Host_EnumerateDfsRoot_Network_Success() var cnt = 0; var noDomainConnection = true; - UnitTestConstants.StopWatcher(true); // Drill down to get servers from the first namespace retrieved. @@ -71,7 +70,7 @@ public void AlphaFS_Host_EnumerateDfsRoot_Network_Success() } } - Console.Write("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); if (cnt == 0) Assert.Inconclusive("Nothing is enumerated, but it is expected."); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDomainDfsRoot.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDomainDfsRoot.cs index 96d52be19..dc71c4deb 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDomainDfsRoot.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateDomainDfsRoot.cs @@ -37,7 +37,6 @@ public void AlphaFS_Host_EnumerateDomainDfsRoot_Network_Success() Console.Write("Enumerating DFS Root from user domain: [{0}]\n", Alphaleonis.Win32.Network.NativeMethods.ComputerDomain); var cnt = 0; var noDomainConnection = true; - UnitTestConstants.StopWatcher(true); try { foreach (var dfsNamespace in Alphaleonis.Win32.Network.Host.EnumerateDomainDfsRoot()) diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_CopySymbolicLink.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_CopySymbolicLink.cs index 70957b691..170b4b759 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_CopySymbolicLink.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_CopySymbolicLink.cs @@ -48,7 +48,7 @@ private void Directory_Copy_CopySymbolicLink_SourceIsASymbolicLink_TargetMustAls { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_CreateSymbolicLink_And_GetLinkTargetInfo.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_CreateSymbolicLink_And_GetLinkTargetInfo.cs index 442e5eea7..5a9bfe250 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_CreateSymbolicLink_And_GetLinkTargetInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_CreateSymbolicLink_And_GetLinkTargetInfo.cs @@ -57,7 +57,7 @@ private void Directory_CreateSymbolicLink_And_GetLinkTargetInfo(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -110,7 +110,7 @@ private void Directory_CreateSymbolicLink_CatchIOException_FileExistsWithSameNam { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_Junction.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_Junction.cs index e07c4e859..ac6a623e8 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_Junction.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory_Junction.cs @@ -68,12 +68,12 @@ public void AlphaFS_Directory_CreateJunction_CatchArgumentException_MappedDrive_ { UnitTestConstants.PrintUnitTestHeader(false); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) using (var connection = new Alphaleonis.Win32.Network.DriveConnection(Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.TempFolder))) { - var mappedPath = connection.LocalName + @"\" + UnitTestConstants.GetRandomFileName(); + var mappedPath = connection.LocalName + @"\" + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters(); Console.WriteLine("\nUsing mapped drive: [{0}] to: [{1}]", connection.LocalName, connection.Share); var target = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(mappedPath); @@ -144,7 +144,7 @@ public void AlphaFS_Directory_CreateJunction_CatchDirectoryNotEmptyException_Loc { UnitTestConstants.PrintUnitTestHeader(false); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) { diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CopySymbolicLink.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CopySymbolicLink.cs index ab6bf6a8c..06102c874 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CopySymbolicLink.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CopySymbolicLink.cs @@ -48,7 +48,7 @@ private void File_Copy_CopySymbolicLink_SourceIsASymbolicLink_TargetMustAlsoBeAS { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CreateHardlink_EnumerateHardlinks.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CreateHardlink_EnumerateHardlinks.cs index 7fb080d74..bab12c399 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CreateHardlink_EnumerateHardlinks.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CreateHardlink_EnumerateHardlinks.cs @@ -44,7 +44,7 @@ private void File_CreateHardlink_And_EnumerateHardlinks(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) { @@ -67,7 +67,7 @@ private void File_CreateHardlink_And_EnumerateHardlinks(bool isNetwork) for (var i = 0; i < numCreate; i++) { - var newfile = System.IO.Path.Combine(hardlinkFolder, i + "-Hardlink-" + UnitTestConstants.GetRandomFileName() + ".txt"); + var newfile = System.IO.Path.Combine(hardlinkFolder, i + "-Hardlink-" + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters() + ".txt"); Alphaleonis.Win32.Filesystem.File.CreateHardlink(newfile, file); @@ -84,7 +84,6 @@ private void File_CreateHardlink_And_EnumerateHardlinks(bool isNetwork) using (var stream = System.IO.File.OpenRead(file)) { - UnitTestConstants.StopWatcher(true); var bhfi = Alphaleonis.Win32.Filesystem.File.GetFileInfoByHandle(stream.SafeFileHandle); Assert.AreEqual(numCreate + 1, bhfi.NumberOfLinks); diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CreateSymbolicLinkAndGetLinkTargetInfo.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CreateSymbolicLinkAndGetLinkTargetInfo.cs index 70ec20550..27e44d392 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CreateSymbolicLinkAndGetLinkTargetInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File_CreateSymbolicLinkAndGetLinkTargetInfo.cs @@ -57,7 +57,7 @@ private void File_CreateSymbolicLink_And_GetLinkTargetInfo(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -102,7 +102,7 @@ private void File_CreateSymbolicLink_CatchIOException_DirectoryExistsWithSameNam { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info_GetVerbCommand.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info_GetVerbCommand.cs index a1e49f1c0..2cbd19dc0 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info_GetVerbCommand.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info_GetVerbCommand.cs @@ -44,7 +44,7 @@ private void Shell32Info_GetVerbCommand(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info_InitializeInstance.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info_InitializeInstance.cs index c62f41867..1c49009a9 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info_InitializeInstance.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info_InitializeInstance.cs @@ -44,7 +44,7 @@ private void Shell32Info_InitializeInstance(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.cs index a1dcd7ab6..f72d3e250 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.cs @@ -34,7 +34,9 @@ public partial class AlphaFS_Shell32Test { private void DumpGetAssociation(bool isLocal) { - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); + + var path = isLocal ? UnitTestConstants.SysRoot : Path.LocalToUnc(UnitTestConstants.SysRoot); Console.WriteLine("\nInput Directory Path: [{0}]\n", path); @@ -59,16 +61,14 @@ private void DumpGetAssociation(bool isLocal) Console.WriteLine("\t\tGetFileOpenWithAppName(): [{0}]", openWithApp); Console.WriteLine("\t\tGetFileVerbCommand() : [{0}]", verbCommand); - UnitTestConstants.StopWatcher(true); var shell32Info = Shell32.GetShell32Info(file); - var report = UnitTestConstants.Reporter(true); var cmd = "print"; verbCommand = shell32Info.GetVerbCommand(cmd); Console.WriteLine("\n\t\tShell32Info.GetVerbCommand(\"{0}\"): [{1}]", cmd, verbCommand); UnitTestConstants.Dump(shell32Info, -15); - Console.WriteLine("\n\t{0}\n\n", report); + Console.WriteLine("\n\n\n"); } Console.WriteLine("\n"); Assert.IsTrue(cnt > 0, "No entries enumerated."); @@ -158,7 +158,6 @@ public void AlphaFS_Shell32_PathFileExists() DumpPathFileExists(Path.Combine(UnitTestConstants.SysRoot, "BlaBlaBla"), false); var cnt = 0; - UnitTestConstants.StopWatcher(true); foreach (var file in Directory.EnumerateFiles(UnitTestConstants.SysRoot)) { var fileExists = Shell32.PathFileExists(file); @@ -166,7 +165,7 @@ public void AlphaFS_Shell32_PathFileExists() Console.WriteLine("\t#{0:000}\tShell32.PathFileExists() == [{1}]: {2}\t\t[{3}]", ++cnt, UnitTestConstants.TextTrue, fileExists, file); Assert.IsTrue(fileExists); } - Console.WriteLine("\n\t{0}\n", UnitTestConstants.Reporter(true)); + Console.WriteLine("\n\n"); } diff --git a/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_GetTimestamps.cs b/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_GetTimestamps.cs index c83ea1ef8..e75bc40b6 100644 --- a/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_GetTimestamps.cs +++ b/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_GetTimestamps.cs @@ -40,44 +40,57 @@ public void Directory_GetXxxTimeXxx_LocalAndNetwork_Success() [TestMethod] - public void Directory_GetXxxTimeXxx_NonExistingDirectory_Success() + public void Directory_GetXxxTimeXxx_NonExistingDirectory_Local_Success() { - const string Path = @"z:\nonExistingPath\nonExistingSubFolder"; - Assert.IsFalse(System.IO.Directory.Exists(Path)); + Directory_GetXxxTimeXxx_NonExistingDirectory(); + } + + + + + private void Directory_GetXxxTimeXxx_NonExistingDirectory() + { + UnitTestConstants.PrintUnitTestHeader(false); + + var path = @"Z:\NonExistingPath\NonExistingDirectory"; + + Console.WriteLine("\nInput NonExisting Directory Path: [{0}]", path); + + + Assert.IsFalse(System.IO.Directory.Exists(path)); + var newDateTime = new DateTime(1601, 1, 1); var newDateTimeLocaltime = new DateTime(1601, 1, 1).ToLocalTime(); - Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetCreationTime(Path)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetCreationTime(Path)); + Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetCreationTime(path)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetCreationTime(path)); - Assert.AreEqual(newDateTime, System.IO.Directory.GetCreationTimeUtc(Path)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetCreationTimeUtc(Path)); + Assert.AreEqual(newDateTime, System.IO.Directory.GetCreationTimeUtc(path)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetCreationTimeUtc(path)); - Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetLastAccessTime(Path)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTime(Path)); + Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetLastAccessTime(path)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTime(path)); - Assert.AreEqual(newDateTime, System.IO.Directory.GetLastAccessTimeUtc(Path)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTimeUtc(Path)); + Assert.AreEqual(newDateTime, System.IO.Directory.GetLastAccessTimeUtc(path)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTimeUtc(path)); - Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetLastWriteTime(Path)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTime(Path)); + Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetLastWriteTime(path)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTime(path)); - Assert.AreEqual(newDateTime, System.IO.Directory.GetLastWriteTimeUtc(Path)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTimeUtc(Path)); + Assert.AreEqual(newDateTime, System.IO.Directory.GetLastWriteTimeUtc(path)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTimeUtc(path)); } - - private void Directory_GetXxxTimeXxx(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -102,7 +115,7 @@ private void Directory_GetXxxTimeXxx(bool isNetwork) folder = rootDir.RandomDirectoryFullPath; if (isNetwork) folder = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(folder); - Console.WriteLine("Input Directory Path: [{0}]", folder); + Console.WriteLine("\nInput Directory Path: [{0}]", folder); var dirInfo = new System.IO.DirectoryInfo(folder); dirInfo.Create(); @@ -127,6 +140,9 @@ private void Directory_GetXxxTimeXxx(bool isNetwork) newChangeTime = changeTimeUtcActual.AddSeconds(delay); Assert.AreEqual(changeTimeUtcActual.AddSeconds(delay), newChangeTime); } + + + Console.WriteLine(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_SetTimestamps.cs b/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_SetTimestamps.cs index 010ea4699..0f0caa6f5 100644 --- a/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_SetTimestamps.cs +++ b/AlphaFS.UnitTest/AlphaFS Timestamps/Directory_SetTimestamps.cs @@ -57,7 +57,7 @@ private void Directory_SetTimestampsXxx(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -67,7 +67,7 @@ private void Directory_SetTimestampsXxx(bool isNetwork) using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) { var folder = rootDir.RandomDirectoryFullPath; - var symlinkPath = System.IO.Path.Combine(rootDir.Directory.FullName, UnitTestConstants.GetRandomFileName()) + "-symlink"; + var symlinkPath = System.IO.Path.Combine(rootDir.Directory.FullName, UnitTestConstants.GetRandomFileNameWithDiacriticCharacters()) + "-symlink"; Console.WriteLine("\nInput Directory Path: [{0}]", folder); @@ -124,7 +124,7 @@ private void Directory_CopyTimestamps(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Timestamps/File_GetTimestamps.cs b/AlphaFS.UnitTest/AlphaFS Timestamps/File_GetTimestamps.cs index 877d64773..258d24181 100644 --- a/AlphaFS.UnitTest/AlphaFS Timestamps/File_GetTimestamps.cs +++ b/AlphaFS.UnitTest/AlphaFS Timestamps/File_GetTimestamps.cs @@ -40,44 +40,57 @@ public void File_GetXxxTimeXxx_LocalAndNetwork_Success() [TestMethod] - public void File_GetXxxTimeXxx_NonExistingFile_Success() + public void File_GetXxxTimeXxx_NonExistingFile_Local_Success() { - const string Path = @"z:\nonExistingPath\nonExistingFile.txt"; - Assert.IsFalse(System.IO.File.Exists(Path)); + File_GetXxxTimeXxx_NonExistingFile(); + } + + + + + private void File_GetXxxTimeXxx_NonExistingFile() + { + UnitTestConstants.PrintUnitTestHeader(false); + + var path = @"Z:\NonExistingPath\NonExistingFile.txt"; + + Console.WriteLine("\nInput NonExisting File Path: [{0}]", path); + + + Assert.IsFalse(System.IO.File.Exists(path)); + var newDateTime = new DateTime(1601, 1, 1); var newDateTimeLocaltime = new DateTime(1601, 1, 1).ToLocalTime(); - Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetCreationTime(Path)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetCreationTime(Path)); + Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetCreationTime(path)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetCreationTime(path)); - Assert.AreEqual(newDateTime, System.IO.File.GetCreationTimeUtc(Path)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetCreationTimeUtc(Path)); + Assert.AreEqual(newDateTime, System.IO.File.GetCreationTimeUtc(path)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetCreationTimeUtc(path)); - Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetLastAccessTime(Path)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetLastAccessTime(Path)); + Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetLastAccessTime(path)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetLastAccessTime(path)); - Assert.AreEqual(newDateTime, System.IO.File.GetLastAccessTimeUtc(Path)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetLastAccessTimeUtc(Path)); + Assert.AreEqual(newDateTime, System.IO.File.GetLastAccessTimeUtc(path)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetLastAccessTimeUtc(path)); - Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetLastWriteTime(Path)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetLastWriteTime(Path)); + Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetLastWriteTime(path)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetLastWriteTime(path)); - Assert.AreEqual(newDateTime, System.IO.File.GetLastWriteTimeUtc(Path)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetLastWriteTimeUtc(Path)); + Assert.AreEqual(newDateTime, System.IO.File.GetLastWriteTimeUtc(path)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetLastWriteTimeUtc(path)); } - - private void File_GetXxxTimeXxx(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Timestamps/File_SetTimestamps.cs b/AlphaFS.UnitTest/AlphaFS Timestamps/File_SetTimestamps.cs index 0d52b43a2..5b1a6e788 100644 --- a/AlphaFS.UnitTest/AlphaFS Timestamps/File_SetTimestamps.cs +++ b/AlphaFS.UnitTest/AlphaFS Timestamps/File_SetTimestamps.cs @@ -56,7 +56,7 @@ private void File_SetTimestampsXxx(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -66,7 +66,7 @@ private void File_SetTimestampsXxx(bool isNetwork) using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) { var file = UnitTestConstants.CreateFile(rootDir.Directory.FullName); - var symlinkPath = System.IO.Path.Combine(rootDir.Directory.FullName, UnitTestConstants.GetRandomFileName()) + "-symlink"; + var symlinkPath = System.IO.Path.Combine(rootDir.Directory.FullName, UnitTestConstants.GetRandomFileNameWithDiacriticCharacters()) + "-symlink"; Console.WriteLine("\nInput File Path: [{0}]", file); @@ -122,7 +122,7 @@ private void File_CopyTimestamps(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.DefineDosDevice.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.DefineDosDevice.cs index 07826539f..4323bc9a7 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.DefineDosDevice.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.DefineDosDevice.cs @@ -33,12 +33,12 @@ public partial class AlphaFS_VolumeTest [TestMethod] public void AlphaFS_Volume_DefineDosDevice_Local_Success() { - UnitTestConstants.PrintUnitTestHeader(false); - Console.WriteLine(); - if (!UnitTestConstants.IsAdmin()) Assert.Inconclusive(); + UnitTestConstants.PrintUnitTestHeader(false); + Console.WriteLine(); + var TempFolder = UnitTestConstants.TempFolder; @@ -104,7 +104,6 @@ public void AlphaFS_Volume_DefineDosDevice_Local_Success() try { drive = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter(true), Alphaleonis.Win32.Filesystem.Path.VolumeSeparatorChar, Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar); - UnitTestConstants.StopWatcher(true); // Create Symbolic Link. var createSymbolicLink = false; diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumeMountPoints.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumeMountPoints.cs index b968c9b7a..fd7a0e679 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumeMountPoints.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumeMountPoints.cs @@ -33,12 +33,12 @@ public partial class AlphaFS_VolumeTest [TestMethod] public void AlphaFS_Volume_EnumerateVolumeMountPoints_Local_Success() { - UnitTestConstants.PrintUnitTestHeader(false); - Console.WriteLine(); - if (!UnitTestConstants.IsAdmin()) Assert.Inconclusive(); + UnitTestConstants.PrintUnitTestHeader(false); + Console.WriteLine(); + var cnt = 0; Console.WriteLine("Logical Drives\n"); diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumes.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumes.cs index e293be18e..1dee9e527 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumes.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.EnumerateVolumes.cs @@ -40,7 +40,9 @@ public void AlphaFS_Volume_EnumerateVolumes_And_EnumerateVolumePathNames_Local_S var volumeCount = 0; - var volumes = Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumes().ToList(); + var pathNamesCount = 0; + + var volumes = Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumes().ToArray(); foreach (var volume in volumes) { @@ -51,11 +53,9 @@ public void AlphaFS_Volume_EnumerateVolumes_And_EnumerateVolumePathNames_Local_S Assert.IsTrue(volumes.Any(vol => vol.StartsWith(Alphaleonis.Win32.Filesystem.Path.VolumePrefix + "{") && vol.EndsWith("}" + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator)), "Volume path name is not valid, but it is expected."); + - - - - var pathNames = Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumePathNames(volume).ToList(); + var pathNames = Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumePathNames(volume).ToArray(); foreach (var displayName in pathNames) { @@ -67,19 +67,22 @@ public void AlphaFS_Volume_EnumerateVolumes_And_EnumerateVolumePathNames_Local_S if (!string.IsNullOrWhiteSpace(displayName)) Assert.IsTrue(char.IsLetter(displayName[0]) && displayName.EndsWith(Alphaleonis.Win32.Filesystem.Path.VolumeSeparator + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator)); + + + pathNamesCount++; } Console.WriteLine(); - if (pathNames.Count == 0) - Assert.Inconclusive("Nothing is enumerated, but it is expected."); + if (pathNamesCount == 0) + Assert.Inconclusive("No path names enumerated, but it is expected."); } - if (volumes.Count == 0) - Assert.Inconclusive("Nothing is enumerated, but it is expected."); + if (volumeCount == 0) + Assert.Inconclusive("No volumes enumerated, but it is expected."); } } } diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 0f6dab9ca..5660c04e4 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -322,21 +322,26 @@ - - - - - - + + + + + + - + - - + + + + + + + diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy.cs index f041300aa..eaee8898c 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy.cs @@ -44,7 +44,7 @@ private void Directory_Copy(bool isNetwork) Console.WriteLine(); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_CatchUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_CatchUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs index 2f4f11086..6c134df84 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_CatchUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_CatchUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs @@ -47,7 +47,7 @@ private void Directory_Copy_CatchUnauthorizedAccessException_UserExplicitDenyOnD var gotException = false; - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory_CountFileSystemObjects.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory_CountFileSystemObjects.cs index 6d89534a9..99e889bee 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory_CountFileSystemObjects.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory_CountFileSystemObjects.cs @@ -76,7 +76,7 @@ private void Directory_CountFileSystemObjects_FoldersOnly_NonRecursive(bool isNe { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -105,7 +105,7 @@ private void Directory_CountFileSystemObjects_FoldersOnly_Recursive(bool isNetwo { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -134,7 +134,7 @@ private void Directory_CountFileSystemObjects_FilesOnly_NonRecursive(bool isNetw { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -201,7 +201,7 @@ private void Directory_CountFileSystemObjects_FoldersAndFiles_Recursive(bool isN { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory_CreateDirectory_And_Delete.cs b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory_CreateDirectory_And_Delete.cs index 01e0c19f5..14687cc05 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory_CreateDirectory_And_Delete.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory_CreateDirectory_And_Delete.cs @@ -88,7 +88,7 @@ private void Directory_CreateDirectory_And_Delete(bool isNetwork) Console.WriteLine(); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -105,7 +105,7 @@ private void Directory_CreateDirectory_And_Delete(bool isNetwork) folder += UnitTestConstants.EMspace; #endif - Console.WriteLine("\tInput Directory Path: [{0}]", folder); + Console.WriteLine("Input Directory Path: [{0}]", folder); Console.WriteLine(); @@ -141,7 +141,7 @@ private void Directory_CreateDirectory_FolderWithSpaceAsName(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -177,7 +177,7 @@ private void Directory_CreateDirectory_WithMultipleSpacesAndSlashes(bool isNetwo { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -236,7 +236,7 @@ private void Directory_CreateDirectory_WithDirectorySecurity(bool isNetwork) Console.WriteLine(); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -283,7 +283,7 @@ private void Directory_CreateDirectory_CatchAlreadyExistsException_FileExistsWit { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.DeleteEmptySubdirectories.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.DeleteEmptySubdirectories.cs index b1c1180b8..7b6947e43 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.DeleteEmptySubdirectories.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.DeleteEmptySubdirectories.cs @@ -53,7 +53,7 @@ private void Directory_DeleteEmptySubdirectories(bool isNetwork) Console.WriteLine(); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_CatchDirectoryNotEmptyException_NonEmptyDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_CatchDirectoryNotEmptyException_NonEmptyDirectory.cs index fb682739b..0055dc8b4 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_CatchDirectoryNotEmptyException_NonEmptyDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_CatchDirectoryNotEmptyException_NonEmptyDirectory.cs @@ -55,7 +55,7 @@ private void Directory_Delete_CatchDirectoryNotEmptyException_NonEmptyDirectory( using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) { var folder = rootDir.RandomDirectoryFullPath; - var file = System.IO.Path.Combine(folder, UnitTestConstants.GetRandomFileName()); + var file = System.IO.Path.Combine(folder, UnitTestConstants.GetRandomFileNameWithDiacriticCharacters()); Console.WriteLine("Input Directory Path: [{0}]", folder); Console.WriteLine("Input File Path : [{0}]", file); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ToDifferentVolume_EmulateUsingCopyDelete.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ToDifferentVolume_EmulateUsingCopyDelete.cs index f4dcc7b3d..cdd18ff92 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ToDifferentVolume_EmulateUsingCopyDelete.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ToDifferentVolume_EmulateUsingCopyDelete.cs @@ -46,7 +46,7 @@ private void Directory_Move_ToDifferentVolume_EmulateUsingCopyDelete(bool isNetw using (var rootDir = new TemporaryDirectory(UnitTestConstants.TempFolder, MethodBase.GetCurrentMethod().Name)) { - var random = UnitTestConstants.GetRandomFileName(); + var random = UnitTestConstants.GetRandomFileNameWithDiacriticCharacters(); var srcFolderName = System.IO.Path.Combine(rootDir.Directory.FullName, "Existing Source Folder.") + random; var destFolderName = System.IO.Path.Combine(rootDir.Directory.FullName, "Destination Folder.") + random; diff --git a/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs b/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs index 63bae0e7d..93184c83e 100644 --- a/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs +++ b/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs @@ -40,7 +40,9 @@ public partial class DirectoryTest { private void DumpEnableDisableEncryption(bool isLocal) { - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); + + var tempPath = Path.Combine(Path.GetTempPath(), "Directory.EnableDisableEncryption()-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); @@ -59,9 +61,7 @@ private void DumpEnableDisableEncryption(bool isLocal) var action = false; try { - UnitTestConstants.StopWatcher(true); Directory.EnableEncryption(tempPath); - report = UnitTestConstants.Reporter(true); action = true; } catch (Exception ex) @@ -90,9 +90,7 @@ private void DumpEnableDisableEncryption(bool isLocal) action = false; try { - UnitTestConstants.StopWatcher(true); Directory.DisableEncryption(tempPath); - report = UnitTestConstants.Reporter(true); action = true; } catch (Exception ex) @@ -126,7 +124,9 @@ private void DumpEnableDisableEncryption(bool isLocal) private void DumpEnumerateFileIdBothDirectoryInfo(bool isLocal) { - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); + + var tempPath = UnitTestConstants.SysRoot; if (!isLocal) tempPath = Path.LocalToUnc(tempPath); @@ -141,7 +141,6 @@ private void DumpEnumerateFileIdBothDirectoryInfo(bool isLocal) long numDirectories = 0; long numFiles = 0; - UnitTestConstants.StopWatcher(true); foreach (var fibdi in Directory.EnumerateFileIdBothDirectoryInfo(tempPath)) { if ((fibdi.FileAttributes & FileAttributes.Directory) != 0) @@ -151,9 +150,8 @@ private void DumpEnumerateFileIdBothDirectoryInfo(bool isLocal) foundFse = UnitTestConstants.Dump(fibdi, -22); } - var report = UnitTestConstants.Reporter(); - Console.WriteLine("\n\tEnumerated: Directories = [{0}] Files = [{1}]\t{2}", numDirectories, numFiles, report); + Console.WriteLine("\n\tEnumerated: Directories = [{0}] Files = [{1}]", numDirectories, numFiles); if (!foundFse) Assert.Inconclusive("Nothing is enumerated, but it is expected."); @@ -168,14 +166,14 @@ private void DumpEnumerateFileIdBothDirectoryInfo(bool isLocal) private void DumpGetProperties(bool isLocal) { - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); + + var path = isLocal ? UnitTestConstants.SysRoot32 : Path.LocalToUnc(UnitTestConstants.SysRoot32); Console.WriteLine("\n\tAggregated properties of file system objects from Directory: [{0}]\n", path); - UnitTestConstants.StopWatcher(true); var props = Directory.GetProperties(path, DirectoryEnumerationOptions.FilesAndFolders | DirectoryEnumerationOptions.Recursive | DirectoryEnumerationOptions.ContinueOnException); - var report = UnitTestConstants.Reporter(); var total = props["Total"]; var file = props["File"]; @@ -185,7 +183,7 @@ private void DumpGetProperties(bool isLocal) foreach (var key in props.Keys) Console.WriteLine("\t\t#{0:000}\t{1, -17} = [{2}]", ++cnt, key, props[key]); - Console.WriteLine("\n\t{0}", report); + Console.WriteLine(); if (cnt == 0) Assert.Inconclusive("Nothing is enumerated, but it is expected."); @@ -231,7 +229,6 @@ public void Directory_GetDirectoryRoot() #endregion // ArgumentException - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { string expected = null; @@ -270,7 +267,7 @@ public void Directory_GetDirectoryRoot() } Console.WriteLine("\t AlphaFS : [{0}]", actual ?? "null"); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); Assert.AreEqual(0, errorCnt, "Encountered paths where AlphaFS != System.IO"); } @@ -318,7 +315,6 @@ public void Directory_GetParent() var pathCnt = 0; var errorCnt = 0; - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { string expected = null; @@ -359,7 +355,7 @@ public void Directory_GetParent() } Console.WriteLine("\t AlphaFS : [{0}]", actual ?? "null"); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); Assert.AreEqual(0, errorCnt, "Encountered paths where AlphaFS != System.IO"); } @@ -405,7 +401,6 @@ public void AlphaFS_Directory_HasInheritedPermissions() var searchOption = SearchOption.TopDirectoryOnly; var cnt = 0; - UnitTestConstants.StopWatcher(true); foreach (var dir in Directory.EnumerateDirectories(UnitTestConstants.SysRoot, searchPattern, searchOption)) { try @@ -422,7 +417,7 @@ public void AlphaFS_Directory_HasInheritedPermissions() Console.Write("\t#{0:000}\tCaught {1} for directory: [{2}]\t[{3}]\n", cnt, ex.GetType().FullName, dir, ex.Message.Replace(Environment.NewLine, " ")); } } - Console.Write("\n{0}", UnitTestConstants.Reporter()); + Console.WriteLine(); } #endregion // AlphaFS diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Exists.cs b/AlphaFS.UnitTest/Directory Class/Directory_Exists.cs index 1db85890d..43bfeb04d 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Exists.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Exists.cs @@ -81,7 +81,7 @@ private void Directory_Exists_ExistingDirectory_Exists(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -179,7 +179,7 @@ private void Directory_Exists_NonExistingDirectory_DoesNotExist(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -209,14 +209,14 @@ private void Directory_Exists_UseCases(bool isNetwork) UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); using (new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) { - var randomName = UnitTestConstants.GetRandomFileName(); + var randomName = UnitTestConstants.GetRandomFileNameWithDiacriticCharacters(); // C:\randomName var nonExistingFolder1 = UnitTestConstants.SysDrive + @"\" + randomName; diff --git a/AlphaFS.UnitTest/Directory Class/Directory_GetAccessControl.cs b/AlphaFS.UnitTest/Directory Class/Directory_GetAccessControl.cs index ec79eb447..5964c7e19 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_GetAccessControl.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_GetAccessControl.cs @@ -40,7 +40,7 @@ private void Directory_GetAccessControl(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Directory.GetAccessControl()-" + UnitTestConstants.GetRandomFileName()); + var tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Directory.GetAccessControl()-" + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters()); if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_GetDirectories.cs b/AlphaFS.UnitTest/Directory Class/Directory_GetDirectories.cs index 58e62c25e..f80f34334 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_GetDirectories.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_GetDirectories.cs @@ -58,7 +58,7 @@ private void Directory_GetDirectories_WithSearchPattern(bool isLocal) UnitTestConstants.PrintUnitTestHeader(!isLocal); - var tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Directory.GetDirectories_With_SearchPattern()-" + UnitTestConstants.GetRandomFileName()); + var tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Directory.GetDirectories_With_SearchPattern()-" + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters()); if (!isLocal) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); Console.WriteLine("\nInput Directory Path: [{0}]\n", tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_GetFiles.cs b/AlphaFS.UnitTest/Directory Class/Directory_GetFiles.cs index a1528d35b..698aa50f0 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_GetFiles.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_GetFiles.cs @@ -57,7 +57,7 @@ private void Directory_GetFiles_WithSearchPattern(bool isLocal) UnitTestConstants.PrintUnitTestHeader(!isLocal); - var tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Directory.GetDirectories_With_SearchPattern()-" + UnitTestConstants.GetRandomFileName()); + var tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Directory.GetDirectories_With_SearchPattern()-" + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters()); if (!isLocal) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); Console.WriteLine("\nInput Directory Path: [{0}]\n", tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_SetAccessControl.cs b/AlphaFS.UnitTest/Directory Class/Directory_SetAccessControl.cs index 52bb61393..eae18b37f 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_SetAccessControl.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_SetAccessControl.cs @@ -46,7 +46,7 @@ private void Directory_SetAccessControl(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_Attributes.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_Attributes.cs index 8baa4f5f4..102a329f2 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_Attributes.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_Attributes.cs @@ -44,7 +44,7 @@ private void DirectoryInfo_Attributes(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_FolderName255Characters.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_FolderName255Characters.cs index 78a4dd1b7..3c7d84c1d 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_FolderName255Characters.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_FolderName255Characters.cs @@ -52,7 +52,7 @@ private void DirectoryInfo_CatchPathTooLongException_FolderNameGreaterThan255Cha { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -102,7 +102,7 @@ private void DirectoryInfo_FolderName255Characters(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_InitializeInstance.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_InitializeInstance.cs index 343677431..5824b5b0b 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_InitializeInstance.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_InitializeInstance.cs @@ -71,7 +71,7 @@ private void DirectoryInfo_InitializeInstance_ExistingDirectory(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -93,7 +93,7 @@ private void DirectoryInfo_InitializeInstance_NonExistingDirectory(bool isNetwor { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_MoveTo.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_MoveTo.cs index c8001579b..35dbcb90c 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_MoveTo.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_MoveTo.cs @@ -57,7 +57,7 @@ private void DirectoryInfo_MoveTo_DelayUntilReboot(bool isNetwork) Console.WriteLine(); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -65,7 +65,7 @@ private void DirectoryInfo_MoveTo_DelayUntilReboot(bool isNetwork) using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name)) { var folder = rootDir.Directory.FullName; - var folderSrc = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(System.IO.Path.Combine(folder, "Source-" + UnitTestConstants.GetRandomFileName())); + var folderSrc = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(System.IO.Path.Combine(folder, "Source-" + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters())); var pendingEntry = folderSrc.FullName; Console.WriteLine("Src Directory Path: [{0}]", pendingEntry); diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_Refresh.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_Refresh.cs index 0915d6c25..68fda0154 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_Refresh.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo_Refresh.cs @@ -44,7 +44,7 @@ private void DirectoryInfo_Refresh(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize.cs b/AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize.cs index 83c540726..2ef1500dc 100644 --- a/AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize.cs +++ b/AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize.cs @@ -43,7 +43,7 @@ private void File_GetSize(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/AlphaFS_File_IsLocked.cs b/AlphaFS.UnitTest/File Class/AlphaFS_File_IsLocked.cs index b5a6303c8..2f61c208f 100644 --- a/AlphaFS.UnitTest/File Class/AlphaFS_File_IsLocked.cs +++ b/AlphaFS.UnitTest/File Class/AlphaFS_File_IsLocked.cs @@ -59,7 +59,7 @@ private void File_IsLocked(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -88,7 +88,7 @@ private void File_GetProcessForFileLock(bool isNetwork) UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -129,7 +129,7 @@ private void File_GetProcessForFileLock_NoLockReturnsNull(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -139,7 +139,7 @@ private void File_GetProcessForFileLock_NoLockReturnsNull(bool isNetwork) var file = rootDir.RandomFileFullPath; var fi = new System.IO.FileInfo(file); - Console.WriteLine("\nInput File Path: [{0}]]\n", file); + Console.WriteLine("\nInput File Path: [{0}]]", file); using (fi.CreateText()) { } diff --git a/AlphaFS.UnitTest/File Class/File.Delete/File_Delete.cs b/AlphaFS.UnitTest/File Class/File.Delete/File_Delete.cs index d089937e9..328fb9e49 100644 --- a/AlphaFS.UnitTest/File Class/File.Delete/File_Delete.cs +++ b/AlphaFS.UnitTest/File Class/File.Delete/File_Delete.cs @@ -76,7 +76,7 @@ private void File_Delete(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -131,7 +131,7 @@ private void File_Delete_CatchFileNotFoundException_NonExistingFile(bool isNetwo { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath() + "File.Delete-" + UnitTestConstants.GetRandomFileName(); + var tempPath = System.IO.Path.GetTempPath() + "File.Delete-" + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters(); if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -156,7 +156,7 @@ private void File_Delete_CatchUnauthorizedAccessException_PathIsADirectoryNotAFi { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -191,7 +191,7 @@ private void File_Delete_CatchFileReadOnlyException_ReadOnlyFile(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/File.Move/File_Move.cs b/AlphaFS.UnitTest/File Class/File.Move/File_Move.cs index 8bb34b2e3..eb6341ef5 100644 --- a/AlphaFS.UnitTest/File Class/File.Move/File_Move.cs +++ b/AlphaFS.UnitTest/File Class/File.Move/File_Move.cs @@ -43,7 +43,7 @@ private void File_Move_Overwrite_DestinationFileAlreadyExists(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/FileTest.cs b/AlphaFS.UnitTest/File Class/FileTest.cs index b36f211cf..dafc0f790 100644 --- a/AlphaFS.UnitTest/File Class/FileTest.cs +++ b/AlphaFS.UnitTest/File Class/FileTest.cs @@ -44,8 +44,10 @@ private void DumpAppendAllLines(bool isLocal) { #region Setup - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); - var tempFolder = Path.GetTempPath(); + UnitTestConstants.PrintUnitTestHeader(!isLocal); + + + var tempFolder = UnitTestConstants.TempFolder; var tempPath = Path.Combine(tempFolder, "File.Delete-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); @@ -111,7 +113,9 @@ private void DumpAppendAllLines(bool isLocal) private void DumpGetSetAttributes(bool isLocal) { - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); + + var tmp = Path.Combine(Path.GetTempPath(), "File.SetAttributes()-" + Path.GetRandomFileName()); var tempPath = isLocal ? tmp : Path.LocalToUnc(tmp); var sys32 = isLocal ? UnitTestConstants.SysRoot32 : Path.LocalToUnc(UnitTestConstants.SysRoot32); @@ -138,7 +142,6 @@ private void DumpGetSetAttributes(bool isLocal) var allOk = true; var cnt = 0; - UnitTestConstants.StopWatcher(true); foreach (var file in Directory.EnumerateFiles(tempPath)) { try @@ -162,7 +165,6 @@ private void DumpGetSetAttributes(bool isLocal) } } Console.WriteLine(); - Console.WriteLine(UnitTestConstants.Reporter()); Assert.IsTrue(allOk); @@ -171,7 +173,6 @@ private void DumpGetSetAttributes(bool isLocal) allOk = true; cnt = 0; - UnitTestConstants.StopWatcher(true); foreach (var file in Directory.EnumerateFiles(tempPath)) { try @@ -195,7 +196,6 @@ private void DumpGetSetAttributes(bool isLocal) } } Console.WriteLine(); - Console.WriteLine(UnitTestConstants.Reporter()); Directory.Delete(tempPath, true, true); @@ -210,7 +210,9 @@ private void DumpGetSetAttributes(bool isLocal) private void DumpReadAllLines(bool isLocal) { - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); + + var tmp = Path.Combine(Path.GetTempPath(), "File.SetAttributes()-" + Path.GetRandomFileName()); var tempPath = isLocal ? tmp : Path.LocalToUnc(tmp); @@ -245,7 +247,9 @@ private void DumpReadAllLines(bool isLocal) private void DumpReadWriteAllBytes(bool isLocal) { - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); + + var tempPath = Path.GetTempPath("File.ReadWriteAllBytes()-" + Path.GetRandomFileName()); if (!isLocal) { tempPath = Path.LocalToUnc(tempPath); } diff --git a/AlphaFS.UnitTest/File Class/File_Create.cs b/AlphaFS.UnitTest/File Class/File_Create.cs index 424d68d53..cad738227 100644 --- a/AlphaFS.UnitTest/File Class/File_Create.cs +++ b/AlphaFS.UnitTest/File Class/File_Create.cs @@ -56,7 +56,7 @@ private void File_Create(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -98,7 +98,7 @@ private void File_Create_WithFileSecurity(bool isNetwork) Console.WriteLine(); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/File_CreateText.cs b/AlphaFS.UnitTest/File Class/File_CreateText.cs index cad7e3d15..54763a98b 100644 --- a/AlphaFS.UnitTest/File Class/File_CreateText.cs +++ b/AlphaFS.UnitTest/File Class/File_CreateText.cs @@ -44,7 +44,7 @@ private void File_CreateText(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/File_Exists.cs b/AlphaFS.UnitTest/File Class/File_Exists.cs index 2a33d0e39..2a502a285 100644 --- a/AlphaFS.UnitTest/File Class/File_Exists.cs +++ b/AlphaFS.UnitTest/File Class/File_Exists.cs @@ -51,7 +51,7 @@ private void File_Exists(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/File_Open.cs b/AlphaFS.UnitTest/File Class/File_Open.cs index 60f339e7f..c47d9b980 100644 --- a/AlphaFS.UnitTest/File Class/File_Open.cs +++ b/AlphaFS.UnitTest/File Class/File_Open.cs @@ -51,7 +51,7 @@ private void Open_Create(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -85,7 +85,7 @@ private void Open_Append(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/File_OpenRead.cs b/AlphaFS.UnitTest/File Class/File_OpenRead.cs index 60e1c0d70..94c08f678 100644 --- a/AlphaFS.UnitTest/File Class/File_OpenRead.cs +++ b/AlphaFS.UnitTest/File Class/File_OpenRead.cs @@ -44,7 +44,7 @@ private void File_OpenRead(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/File_OpenText.cs b/AlphaFS.UnitTest/File Class/File_OpenText.cs index e62d0050f..9385dad1a 100644 --- a/AlphaFS.UnitTest/File Class/File_OpenText.cs +++ b/AlphaFS.UnitTest/File Class/File_OpenText.cs @@ -43,7 +43,7 @@ private void File_OpenText(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/File_OpenWrite.cs b/AlphaFS.UnitTest/File Class/File_OpenWrite.cs index 5ba155977..70faecf01 100644 --- a/AlphaFS.UnitTest/File Class/File_OpenWrite.cs +++ b/AlphaFS.UnitTest/File Class/File_OpenWrite.cs @@ -44,7 +44,7 @@ private void File_OpenWrite(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/File_Replace.cs b/AlphaFS.UnitTest/File Class/File_Replace.cs index e3105d656..e77b2c5a5 100644 --- a/AlphaFS.UnitTest/File Class/File_Replace.cs +++ b/AlphaFS.UnitTest/File Class/File_Replace.cs @@ -51,7 +51,7 @@ private void File_Replace(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -91,7 +91,7 @@ private void File_Replace_NoBackup(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/File_SetAccessControl.cs b/AlphaFS.UnitTest/File Class/File_SetAccessControl.cs index 971e66d87..a7096935f 100644 --- a/AlphaFS.UnitTest/File Class/File_SetAccessControl.cs +++ b/AlphaFS.UnitTest/File Class/File_SetAccessControl.cs @@ -48,7 +48,7 @@ private void File_SetAccessControl(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/FileInfo Class/FileInfo_Attributes.cs b/AlphaFS.UnitTest/FileInfo Class/FileInfo_Attributes.cs index 66a82ce3f..f852fd5a5 100644 --- a/AlphaFS.UnitTest/FileInfo Class/FileInfo_Attributes.cs +++ b/AlphaFS.UnitTest/FileInfo Class/FileInfo_Attributes.cs @@ -44,7 +44,7 @@ private void FileInfo_Attributes(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/FileInfo Class/FileInfo_InitializeInstance_ExistingFile.cs b/AlphaFS.UnitTest/FileInfo Class/FileInfo_InitializeInstance_ExistingFile.cs index ca5418fa8..b2c009679 100644 --- a/AlphaFS.UnitTest/FileInfo Class/FileInfo_InitializeInstance_ExistingFile.cs +++ b/AlphaFS.UnitTest/FileInfo Class/FileInfo_InitializeInstance_ExistingFile.cs @@ -52,7 +52,7 @@ private void FileInfo_InitializeInstance_ExistingFile(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -77,7 +77,7 @@ private void FileInfo_InitializeInstance_NonExistingFile(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/FileInfo Class/FileInfo_Refresh.cs b/AlphaFS.UnitTest/FileInfo Class/FileInfo_Refresh.cs index 4813d9e95..b9b3c0c97 100644 --- a/AlphaFS.UnitTest/FileInfo Class/FileInfo_Refresh.cs +++ b/AlphaFS.UnitTest/FileInfo Class/FileInfo_Refresh.cs @@ -44,7 +44,7 @@ private void FileInfo_Refresh(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/Path Class/PathTest.cs b/AlphaFS.UnitTest/Path Class/PathTest.cs index 4916547c5..9fe22b12e 100644 --- a/AlphaFS.UnitTest/Path Class/PathTest.cs +++ b/AlphaFS.UnitTest/Path Class/PathTest.cs @@ -45,7 +45,8 @@ private void Dump83Path(bool isLocal) { #region Setup - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); + var myLongPath = Path.GetTempPath("My Long Data File Or Directory"); if (!isLocal) myLongPath = Path.LocalToUnc(myLongPath); @@ -62,11 +63,9 @@ private void Dump83Path(bool isLocal) { using (File.Create(myLongPath)) - UnitTestConstants.StopWatcher(true); - short83Path = Path.GetShort83Path(myLongPath); - Console.WriteLine("Short 8.3 file path : [{0}]\t\t\t{1}", short83Path, UnitTestConstants.Reporter(true)); + Console.WriteLine("Short 8.3 file path : [{0}]", short83Path); Assert.IsTrue(!short83Path.Equals(myLongPath)); @@ -74,11 +73,9 @@ private void Dump83Path(bool isLocal) - UnitTestConstants.StopWatcher(true); - var longFrom83Path = Path.GetLongFrom83ShortPath(short83Path); - Console.WriteLine("Long path from 8.3 path: [{0}]{1}", longFrom83Path, UnitTestConstants.Reporter(true)); + Console.WriteLine("Long path from 8.3 path: [{0}]", longFrom83Path); Assert.IsTrue(longFrom83Path.Equals(myLongPath)); @@ -104,11 +101,9 @@ private void Dump83Path(bool isLocal) { Directory.CreateDirectory(myLongPath); - UnitTestConstants.StopWatcher(true); - short83Path = Path.GetShort83Path(myLongPath); - Console.WriteLine("Short 8.3 directory path: [{0}]\t\t\t{1}", short83Path, UnitTestConstants.Reporter(true)); + Console.WriteLine("Short 8.3 directory path: [{0}]", short83Path); Assert.IsFalse(short83Path.Equals(myLongPath)); @@ -116,11 +111,9 @@ private void Dump83Path(bool isLocal) - UnitTestConstants.StopWatcher(true); - var longFrom83Path = Path.GetLongFrom83ShortPath(short83Path); - Console.WriteLine("Long path from 8.3 path : [{0}]{1}", longFrom83Path, UnitTestConstants.Reporter(true)); + Console.WriteLine("Long path from 8.3 path : [{0}]", longFrom83Path); Assert.IsTrue(longFrom83Path.Equals(myLongPath)); @@ -142,7 +135,7 @@ private void Dump83Path(bool isLocal) private void DumpGetDirectoryNameWithoutRoot(bool isLocal) { - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); const string neDir = "Non-Existing Directory"; const string sys32 = "system32"; @@ -150,7 +143,6 @@ private void DumpGetDirectoryNameWithoutRoot(bool isLocal) var fullPath = Path.Combine(Environment.SystemDirectory, neDir); if (!isLocal) fullPath = Path.LocalToUnc(fullPath); - UnitTestConstants.StopWatcher(true); var directoryNameWithoutRoot = Path.GetDirectoryNameWithoutRoot(fullPath); Console.WriteLine("\nInput Path: [{0}]\n\tGetDirectoryNameWithoutRoot() (Should be: [{1}]): [{2}]", fullPath, sys32, directoryNameWithoutRoot); Assert.IsTrue(directoryNameWithoutRoot.Equals(sys32, StringComparison.OrdinalIgnoreCase)); @@ -160,7 +152,6 @@ private void DumpGetDirectoryNameWithoutRoot(bool isLocal) fullPath = Path.Combine(fullPath, "Non-Existing file.txt"); if (!isLocal) fullPath = Path.LocalToUnc(fullPath); - UnitTestConstants.StopWatcher(true); directoryNameWithoutRoot = Path.GetDirectoryNameWithoutRoot(fullPath); Console.WriteLine("\nInput Path: [{0}]\n\tGetDirectoryNameWithoutRoot() (Should be: [{1}]): [{2}]", fullPath, neDir, directoryNameWithoutRoot); Assert.IsTrue(directoryNameWithoutRoot.Equals(neDir, StringComparison.OrdinalIgnoreCase)); @@ -170,7 +161,6 @@ private void DumpGetDirectoryNameWithoutRoot(bool isLocal) fullPath = UnitTestConstants.SysRoot; if (!isLocal) fullPath = Path.LocalToUnc(fullPath); - UnitTestConstants.StopWatcher(true); directoryNameWithoutRoot = Path.GetDirectoryNameWithoutRoot(fullPath); Console.WriteLine("\nInput Path: [{0}]\n\tGetDirectoryNameWithoutRoot() (Should be: [null]): [{1}]", fullPath, directoryNameWithoutRoot ?? "null"); Assert.AreEqual(null, directoryNameWithoutRoot); @@ -180,7 +170,7 @@ private void DumpGetDirectoryNameWithoutRoot(bool isLocal) private void DumpGetFinalPathNameByHandle(bool isLocal) { - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); var tempFile = Path.GetTempFileName(); if (!isLocal) tempFile = Path.LocalToUnc(tempFile); @@ -202,7 +192,6 @@ private void DumpGetFinalPathNameByHandle(bool isLocal) var handle = stream.SafeFileHandle; - UnitTestConstants.StopWatcher(true); var fileNameNormalized = Path.GetFinalPathNameByHandle(handle); var fileNameOpened = Path.GetFinalPathNameByHandle(handle, FinalPathFormats.FileNameOpened); @@ -231,7 +220,6 @@ private void DumpGetFinalPathNameByHandle(bool isLocal) Console.WriteLine("\tFinalPathFormats.VolumeNameNT : [{0}]", volumeNameNt); Console.WriteLine("\tFinalPathFormats.VolumeNameNone: [{0}]", volumeNameNone); - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); gotSomething = true; } @@ -275,7 +263,7 @@ private void DumpGetFinalPathNameByHandle(bool isLocal) private void DumpGetSuffixedDirectoryName(bool isLocal) { - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); var neDir = "Non-Existing Directory"; var sys32 = Environment.SystemDirectory + Path.DirectorySeparator; @@ -287,9 +275,8 @@ private void DumpGetSuffixedDirectoryName(bool isLocal) sys32 = Path.LocalToUnc(sys32); } - UnitTestConstants.StopWatcher(true); var suffixedDirectoryName = Path.GetSuffixedDirectoryName(fullPath); - Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [{1}]): [{2}]\n{3}", fullPath, sys32, suffixedDirectoryName, UnitTestConstants.Reporter()); + Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [{1}]): [{2}]", fullPath, sys32, suffixedDirectoryName); Assert.IsTrue(suffixedDirectoryName.Equals(sys32, StringComparison.OrdinalIgnoreCase)); @@ -302,9 +289,8 @@ private void DumpGetSuffixedDirectoryName(bool isLocal) neDir = Path.LocalToUnc(neDir); } - UnitTestConstants.StopWatcher(true); suffixedDirectoryName = Path.GetSuffixedDirectoryName(fullPath); - Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [{1}]): [{2}]\n{3}", fullPath, neDir, suffixedDirectoryName, UnitTestConstants.Reporter()); + Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [{1}]): [{2}]", fullPath, neDir, suffixedDirectoryName); Assert.IsTrue(suffixedDirectoryName.Equals(neDir, StringComparison.OrdinalIgnoreCase)); @@ -312,18 +298,16 @@ private void DumpGetSuffixedDirectoryName(bool isLocal) fullPath = UnitTestConstants.SysRoot; if (!isLocal) fullPath = Path.LocalToUnc(fullPath); - UnitTestConstants.StopWatcher(true); suffixedDirectoryName = Path.GetSuffixedDirectoryName(fullPath); - Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [null]): [{1}]\n{2}", fullPath, suffixedDirectoryName ?? "null", UnitTestConstants.Reporter()); + Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [null]): [{1}]", fullPath, suffixedDirectoryName ?? "null"); Assert.AreEqual(null, suffixedDirectoryName); fullPath = UnitTestConstants.SysDrive + Path.DirectorySeparator; if (!isLocal) fullPath = Path.LocalToUnc(fullPath); - UnitTestConstants.StopWatcher(true); suffixedDirectoryName = Path.GetSuffixedDirectoryNameWithoutRoot(fullPath); - Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [null]): [{1}]\n{2}", fullPath, suffixedDirectoryName ?? "null", UnitTestConstants.Reporter()); + Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [null]): [{1}]", fullPath, suffixedDirectoryName ?? "null"); Assert.AreEqual(null, suffixedDirectoryName); Console.WriteLine("\n"); @@ -331,7 +315,7 @@ private void DumpGetSuffixedDirectoryName(bool isLocal) private void DumpGetSuffixedDirectoryNameWithoutRoot(bool isLocal) { - Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); + UnitTestConstants.PrintUnitTestHeader(!isLocal); var neDir = "Non-Existing Directory"; var sys32 = (UnitTestConstants.SysRoot + Path.DirectorySeparator + "system32" + Path.DirectorySeparator).Replace(UnitTestConstants.SysDrive + Path.DirectorySeparator, ""); @@ -339,9 +323,8 @@ private void DumpGetSuffixedDirectoryNameWithoutRoot(bool isLocal) var fullPath = Path.Combine(UnitTestConstants.SysRoot + Path.DirectorySeparator + "system32" + Path.DirectorySeparator, neDir); if (!isLocal) fullPath = Path.LocalToUnc(fullPath); - UnitTestConstants.StopWatcher(true); var suffixedDirectoryNameWithoutRoot = Path.GetSuffixedDirectoryNameWithoutRoot(fullPath); - Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [{1}]): [{2}]\n{3}", fullPath, sys32, suffixedDirectoryNameWithoutRoot, UnitTestConstants.Reporter()); + Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [{1}]): [{2}]", fullPath, sys32, suffixedDirectoryNameWithoutRoot); Assert.IsTrue(suffixedDirectoryNameWithoutRoot.Equals(sys32, StringComparison.OrdinalIgnoreCase), "Path mismatch."); @@ -350,9 +333,8 @@ private void DumpGetSuffixedDirectoryNameWithoutRoot(bool isLocal) neDir = (Path.Combine(Environment.SystemDirectory, neDir) + Path.DirectorySeparator).Replace(UnitTestConstants.SysDrive + Path.DirectorySeparator, ""); if (!isLocal) fullPath = Path.LocalToUnc(fullPath); - UnitTestConstants.StopWatcher(true); suffixedDirectoryNameWithoutRoot = Path.GetSuffixedDirectoryNameWithoutRoot(fullPath); - Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [{1}]): [{2}]\n{3}", fullPath, neDir, suffixedDirectoryNameWithoutRoot, UnitTestConstants.Reporter()); + Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [{1}]): [{2}]", fullPath, neDir, suffixedDirectoryNameWithoutRoot); Assert.IsTrue(suffixedDirectoryNameWithoutRoot.Equals(neDir, StringComparison.OrdinalIgnoreCase), "Path mismatch."); @@ -360,9 +342,8 @@ private void DumpGetSuffixedDirectoryNameWithoutRoot(bool isLocal) fullPath = UnitTestConstants.SysRoot; if (!isLocal) fullPath = Path.LocalToUnc(fullPath); - UnitTestConstants.StopWatcher(true); suffixedDirectoryNameWithoutRoot = Path.GetSuffixedDirectoryNameWithoutRoot(fullPath); - Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [null]): [{1}]\n{2}", fullPath, suffixedDirectoryNameWithoutRoot ?? "null", UnitTestConstants.Reporter()); + Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [null]): [{1}]", fullPath, suffixedDirectoryNameWithoutRoot ?? "null"); Assert.AreEqual(null, suffixedDirectoryNameWithoutRoot, "Path mismatch."); @@ -370,9 +351,8 @@ private void DumpGetSuffixedDirectoryNameWithoutRoot(bool isLocal) fullPath = UnitTestConstants.SysDrive + Path.DirectorySeparator; if (!isLocal) fullPath = Path.LocalToUnc(fullPath); - UnitTestConstants.StopWatcher(true); suffixedDirectoryNameWithoutRoot = Path.GetSuffixedDirectoryNameWithoutRoot(fullPath); - Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [null]): [{1}]\n{2}", fullPath, suffixedDirectoryNameWithoutRoot ?? "null", UnitTestConstants.Reporter()); + Console.WriteLine("\nInput Path: [{0}]\n\tGetSuffixedDirectoryName() (Should be: [null]): [{1}]", fullPath, suffixedDirectoryNameWithoutRoot ?? "null"); Assert.AreEqual(null, suffixedDirectoryNameWithoutRoot, "Path mismatch."); Console.WriteLine("\n"); @@ -394,7 +374,6 @@ public void Path_Combine() var pathCnt = 0; var errorCnt = 0; - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { foreach (var path2 in UnitTestConstants.InputPaths) @@ -432,7 +411,7 @@ public void Path_Combine() Console.WriteLine("\t AlphaFS : [{0}]", actual ?? "null"); } } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); Assert.AreEqual(0, errorCnt, "Encountered paths where AlphaFS != System.IO"); } @@ -450,7 +429,6 @@ public void Path_GetFileName() var errorCnt = 0; var skipAssert = false; - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { string expected = null; @@ -488,7 +466,7 @@ public void Path_GetFileName() } Console.WriteLine("\t AlphaFS : [{0}]", actual ?? "null"); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); Assert.AreEqual(0, errorCnt, "Encountered paths where AlphaFS != System.IO"); } @@ -506,7 +484,6 @@ public void Path_GetFileNameWithoutExtension() var errorCnt = 0; var skipAssert = false; - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { string expected = null; @@ -544,7 +521,7 @@ public void Path_GetFileNameWithoutExtension() } Console.WriteLine("\t AlphaFS : [{0}]", actual ?? "null"); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); Assert.AreEqual(0, errorCnt, "Encountered paths where AlphaFS != System.IO"); } @@ -576,7 +553,6 @@ public void Path_GetPathRoot() #endregion // Exceptions - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { string expected = null; @@ -616,7 +592,7 @@ public void Path_GetPathRoot() } Console.WriteLine("\t AlphaFS : [{0}]", actual ?? "null"); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); Assert.AreEqual(0, errorCnt, "Encountered paths where AlphaFS != System.IO"); } @@ -726,7 +702,6 @@ public void AlphaFS_Path_GetLongPath() var pathCnt = 0; var errorCnt = 0; - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { string actual = null; @@ -760,7 +735,7 @@ public void AlphaFS_Path_GetLongPath() } Console.WriteLine("\t AlphaFS : [{0}]", actual ?? "null"); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); Assert.AreEqual(0, errorCnt, "No errors were expected."); } @@ -788,12 +763,10 @@ public void AlphaFS_Path_GetMappedConnectionName() Console.WriteLine("Path.GetMappedConnectionName()"); var cnt = 0; - UnitTestConstants.StopWatcher(true); foreach (var drive in Directory.GetLogicalDrives().Where(drive => new DriveInfo(drive).IsUnc)) { ++cnt; - UnitTestConstants.StopWatcher(true); var gmCn = Path.GetMappedConnectionName(drive); var gmUn = Path.GetMappedUncName(drive); Console.WriteLine("\n\tMapped drive: [{0}]\tGetMappedConnectionName(): [{1}]", drive, gmCn); @@ -802,7 +775,7 @@ public void AlphaFS_Path_GetMappedConnectionName() Assert.IsTrue(!Utils.IsNullOrWhiteSpace(gmCn)); Assert.IsTrue(!Utils.IsNullOrWhiteSpace(gmUn)); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); if (cnt == 0) Assert.Inconclusive("Nothing was enumerated because no mapped drives were found."); @@ -820,7 +793,6 @@ public void AlphaFS_Path_GetRegularPath() var pathCnt = 0; var errorCnt = 0; - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { string actual = null; @@ -846,7 +818,7 @@ public void AlphaFS_Path_GetRegularPath() } Console.WriteLine("\t AlphaFS : [{0}]", actual ?? "null"); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); Assert.AreEqual(0, errorCnt, "No errors were expected."); } @@ -864,7 +836,6 @@ public void AlphaFS_Path_IsLongPath() var errorCnt = 0; var longPathCnt = 0; - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { var actual = false; @@ -890,7 +861,7 @@ public void AlphaFS_Path_IsLongPath() } Console.WriteLine("\tAlphaFS : [{0}]", actual); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); // Hand counted 33 True's. Assert.AreEqual(33, longPathCnt, "Number of local paths do not match.", errorCnt); @@ -911,7 +882,6 @@ public void AlphaFS_Path_IsUncPath() var errorCnt = 0; var uncPathCnt = 0; - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { var actual = false; @@ -940,7 +910,7 @@ public void AlphaFS_Path_IsUncPath() } Console.WriteLine("\tAlphaFS : [{0}]", actual); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); // Hand counted 32 True's. Assert.AreEqual(32, uncPathCnt, "Number of UNC paths do not match.", errorCnt); diff --git a/AlphaFS.UnitTest/Path Class/Path_GetDirectoryName.cs b/AlphaFS.UnitTest/Path Class/Path_GetDirectoryName.cs index b2673020f..5dfc46222 100644 --- a/AlphaFS.UnitTest/Path Class/Path_GetDirectoryName.cs +++ b/AlphaFS.UnitTest/Path Class/Path_GetDirectoryName.cs @@ -34,7 +34,6 @@ public void Path_GetDirectoryName_LocalAndNetwork_Success() var errorCnt = 0; var skipAssert = false; - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { string expected = null; @@ -72,7 +71,7 @@ public void Path_GetDirectoryName_LocalAndNetwork_Success() } Console.WriteLine("\t AlphaFS : [{0}]", actual ?? "null"); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); Assert.AreEqual(0, errorCnt, "Encountered paths where AlphaFS != System.IO"); } diff --git a/AlphaFS.UnitTest/Path Class/Path_GetExtension.cs b/AlphaFS.UnitTest/Path Class/Path_GetExtension.cs index 2b7c29c34..8eb4c9f8a 100644 --- a/AlphaFS.UnitTest/Path Class/Path_GetExtension.cs +++ b/AlphaFS.UnitTest/Path Class/Path_GetExtension.cs @@ -42,7 +42,6 @@ public void Path_GetExtension_NullOrEmpty_Success() var errorCnt = 0; var skipAssert = false; - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { string expected = null; @@ -80,7 +79,7 @@ public void Path_GetExtension_NullOrEmpty_Success() } Console.WriteLine("\t AlphaFS : [{0}]", actual ?? "null"); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); Assert.AreEqual(0, errorCnt, "Encountered paths where AlphaFS != System.IO"); } diff --git a/AlphaFS.UnitTest/Path Class/Path_GetRelativePath.cs b/AlphaFS.UnitTest/Path Class/Path_GetRelativePath.cs index f7b28e8c7..37ea155cd 100644 --- a/AlphaFS.UnitTest/Path Class/Path_GetRelativePath.cs +++ b/AlphaFS.UnitTest/Path Class/Path_GetRelativePath.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -43,7 +43,7 @@ private void Path_GetRelativePath(bool isNetwork) Console.WriteLine(); - var tempPath = System.IO.Path.GetTempPath(); + var tempPath = UnitTestConstants.TempFolder + @"\"; var sysDrive = UnitTestConstants.SysDrive; if (isNetwork) diff --git a/AlphaFS.UnitTest/Path Class/Path_IsPathRooted.cs b/AlphaFS.UnitTest/Path Class/Path_IsPathRooted.cs index 635f9fff6..3df574b1a 100644 --- a/AlphaFS.UnitTest/Path Class/Path_IsPathRooted.cs +++ b/AlphaFS.UnitTest/Path Class/Path_IsPathRooted.cs @@ -32,14 +32,13 @@ public partial class PathTest [TestMethod] public void Path_IsPathRooted_LocalAndNetwork_Success() { - UnitTestConstants.StopWatcher(true); foreach (var path in UnitTestConstants.InputPaths) { var action = Alphaleonis.Win32.Filesystem.Path.IsPathRooted(path); Console.WriteLine("\tIsPathRooted: [{0}]\t\tInput Path: [{1}]", action, path); Assert.AreEqual(System.IO.Path.IsPathRooted(path), action); } - Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); + Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/_Utils/CreateDirectoriesAndFiles.cs b/AlphaFS.UnitTest/UnitTest Utility/CreateDirectoriesAndFiles.cs similarity index 98% rename from AlphaFS.UnitTest/_Utils/CreateDirectoriesAndFiles.cs rename to AlphaFS.UnitTest/UnitTest Utility/CreateDirectoriesAndFiles.cs index 175d299fb..08d560e07 100644 --- a/AlphaFS.UnitTest/_Utils/CreateDirectoriesAndFiles.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/CreateDirectoriesAndFiles.cs @@ -33,7 +33,7 @@ public static void CreateDirectoriesAndFiles(string rootPath, int max, bool read for (var i = 0; i < max; i++) { - var file = System.IO.Path.Combine(rootPath, GetRandomFileName()); + var file = System.IO.Path.Combine(rootPath, GetRandomFileNameWithDiacriticCharacters()); var dir = file + "-" + i + "-dir"; file = file + "-" + i + "-file"; diff --git a/AlphaFS.UnitTest/_Utils/CreateFile.cs b/AlphaFS.UnitTest/UnitTest Utility/CreateFile.cs similarity index 97% rename from AlphaFS.UnitTest/_Utils/CreateFile.cs rename to AlphaFS.UnitTest/UnitTest Utility/CreateFile.cs index a480c4bed..c67d0420f 100644 --- a/AlphaFS.UnitTest/_Utils/CreateFile.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/CreateFile.cs @@ -27,7 +27,7 @@ public static partial class UnitTestConstants { public static System.IO.FileInfo CreateFile(string rootFolder, int fileLength = 0) { - var file = System.IO.Path.Combine(rootFolder, GetRandomFileName()); + var file = System.IO.Path.Combine(rootFolder, GetRandomFileNameWithDiacriticCharacters()); using (var fs = System.IO.File.Create(file)) { diff --git a/AlphaFS.UnitTest/_Utils/DirectoryAssert.cs b/AlphaFS.UnitTest/UnitTest Utility/DirectoryAssert.cs similarity index 100% rename from AlphaFS.UnitTest/_Utils/DirectoryAssert.cs rename to AlphaFS.UnitTest/UnitTest Utility/DirectoryAssert.cs diff --git a/AlphaFS.UnitTest/_Utils/Dump.cs b/AlphaFS.UnitTest/UnitTest Utility/Dump.cs similarity index 100% rename from AlphaFS.UnitTest/_Utils/Dump.cs rename to AlphaFS.UnitTest/UnitTest Utility/Dump.cs diff --git a/AlphaFS.UnitTest/_Utils/FileAssert.cs b/AlphaFS.UnitTest/UnitTest Utility/FileAssert.cs similarity index 100% rename from AlphaFS.UnitTest/_Utils/FileAssert.cs rename to AlphaFS.UnitTest/UnitTest Utility/FileAssert.cs diff --git a/AlphaFS.UnitTest/_Utils/FolderDenyPermission.cs b/AlphaFS.UnitTest/UnitTest Utility/FolderDenyPermission.cs similarity index 100% rename from AlphaFS.UnitTest/_Utils/FolderDenyPermission.cs rename to AlphaFS.UnitTest/UnitTest Utility/FolderDenyPermission.cs diff --git a/AlphaFS.UnitTest/UnitTest Utility/GetRandomFileNameWithDiacriticCharacters.cs b/AlphaFS.UnitTest/UnitTest Utility/GetRandomFileNameWithDiacriticCharacters.cs new file mode 100644 index 000000000..c2abb959b --- /dev/null +++ b/AlphaFS.UnitTest/UnitTest Utility/GetRandomFileNameWithDiacriticCharacters.cs @@ -0,0 +1,67 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS.UnitTest +{ + /// Containts static variables, used by unit tests. + public static partial class UnitTestConstants + { + public static string GetRandomFileNameWithDiacriticCharacters() + { + var randomFileName = System.IO.Path.GetRandomFileName(); + + switch (new Random().Next(0, 4)) + { + case 0: + break; + + case 1: + randomFileName = randomFileName.Replace("a", "ä"); + randomFileName = randomFileName.Replace("e", "ë"); + randomFileName = randomFileName.Replace("i", "ï"); + randomFileName = randomFileName.Replace("o", "ö"); + randomFileName = randomFileName.Replace("u", "ü"); + break; + + case 2: + randomFileName = randomFileName.Replace("a", "á"); + randomFileName = randomFileName.Replace("e", "é"); + randomFileName = randomFileName.Replace("i", "í"); + randomFileName = randomFileName.Replace("o", "ó"); + randomFileName = randomFileName.Replace("u", "ú"); + break; + + case 3: + randomFileName = randomFileName.Replace("a", "â"); + randomFileName = randomFileName.Replace("e", "ê"); + randomFileName = randomFileName.Replace("i", "î"); + randomFileName = randomFileName.Replace("o", "ô"); + randomFileName = randomFileName.Replace("u", "û"); + break; + } + + + return randomFileName; + } + } +} diff --git a/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs b/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs new file mode 100644 index 000000000..4fdddcd0e --- /dev/null +++ b/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs @@ -0,0 +1,122 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Containts static variables, used by unit tests. + public static partial class UnitTestConstants + { + /// The Computer name. + public static readonly string LocalHost = Environment.MachineName; + + + /// The Computer system drive. For example "C:". + public static readonly string SysDrive = Environment.GetEnvironmentVariable("SystemDrive"); + + + 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.GlobalRootPrefix + @"device\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\f", + SysDrive + @"\a\b\c\f.", + SysDrive + @"\a\b\c\f.t", + SysDrive + @"\a\b\c\f.tx", + SysDrive + @"\a\b\c\f.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\f", + Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.", + Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.t", + Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.tx", + Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.txt", + + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\f", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fi", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fil", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.e", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ex", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ext", + + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\f", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fi", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fil", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.e", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ex", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ext" + }; + } +} diff --git a/AlphaFS.UnitTest/_Utils/IsAdmin.cs b/AlphaFS.UnitTest/UnitTest Utility/IsAdmin.cs similarity index 100% rename from AlphaFS.UnitTest/_Utils/IsAdmin.cs rename to AlphaFS.UnitTest/UnitTest Utility/IsAdmin.cs diff --git a/AlphaFS.UnitTest/UnitTest Utility/PrintUnitTestHeader.cs b/AlphaFS.UnitTest/UnitTest Utility/PrintUnitTestHeader.cs new file mode 100644 index 000000000..b9e22db66 --- /dev/null +++ b/AlphaFS.UnitTest/UnitTest Utility/PrintUnitTestHeader.cs @@ -0,0 +1,34 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS.UnitTest +{ + /// Containts static variables, used by unit tests. + public static partial class UnitTestConstants + { + public static void PrintUnitTestHeader(bool isNetwork) + { + Console.WriteLine("\n=== TEST {0} ===", isNetwork ? "NETWORK" : "LOCAL"); + } + } +} diff --git a/AlphaFS.UnitTest/UnitTest Utility/StringToByteArray.cs b/AlphaFS.UnitTest/UnitTest Utility/StringToByteArray.cs new file mode 100644 index 000000000..31a183821 --- /dev/null +++ b/AlphaFS.UnitTest/UnitTest Utility/StringToByteArray.cs @@ -0,0 +1,37 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Text; + +namespace AlphaFS.UnitTest +{ + /// Containts static variables, used by unit tests. + public static partial class UnitTestConstants + { + public static byte[] StringToByteArray(string str, params Encoding[] encoding) + { + var encode = encoding != null && encoding.Any() ? encoding[0] : new UTF8Encoding(true, true); + + return encode.GetBytes(str); + } + } +} diff --git a/AlphaFS.UnitTest/_Utils/TemporaryDirectory.cs b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs similarity index 94% rename from AlphaFS.UnitTest/_Utils/TemporaryDirectory.cs rename to AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs index f0cef9999..6d0fb7160 100644 --- a/AlphaFS.UnitTest/_Utils/TemporaryDirectory.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs @@ -36,7 +36,7 @@ public TemporaryDirectory(string root, string prefix) do { - Directory = new System.IO.DirectoryInfo(System.IO.Path.Combine(root, prefix + "." + UnitTestConstants.GetRandomFileName().Substring(0, 6))); + Directory = new System.IO.DirectoryInfo(System.IO.Path.Combine(root, prefix + "." + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters().Substring(0, 6))); } while (Directory.Exists); @@ -47,7 +47,7 @@ public TemporaryDirectory(string root, string prefix) public string RandomDirectoryFullPath { - get { return System.IO.Path.Combine(Directory.FullName, "Directory-" + UnitTestConstants.GetRandomFileName()); } + get { return System.IO.Path.Combine(Directory.FullName, "Directory-" + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters()); } } public string RandomFileFullPath @@ -57,7 +57,7 @@ public string RandomFileFullPath public string RandomFileFullPathNoExtension { - get { return System.IO.Path.Combine(Directory.FullName, "File-" + UnitTestConstants.GetRandomFileName()); } + get { return System.IO.Path.Combine(Directory.FullName, "File-" + UnitTestConstants.GetRandomFileNameWithDiacriticCharacters()); } } #region Disposable Members diff --git a/AlphaFS.UnitTest/UnitTest Utility/TestAccessRules.cs b/AlphaFS.UnitTest/UnitTest Utility/TestAccessRules.cs new file mode 100644 index 000000000..d464f75a6 --- /dev/null +++ b/AlphaFS.UnitTest/UnitTest Utility/TestAccessRules.cs @@ -0,0 +1,80 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Containts static variables, used by unit tests. + 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); + } + } +} diff --git a/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs b/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs new file mode 100644 index 000000000..7bbcd864e --- /dev/null +++ b/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs @@ -0,0 +1,74 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS.UnitTest +{ + /// Containts static variables, used by unit tests. + public static partial class UnitTestConstants + { +#if NET35 + public const string EMspace = "\u3000"; +#endif + + /// The User temp directory. For example "C:\Users\john\AppData\Local\Temp". + public static readonly string TempFolder = Environment.GetEnvironmentVariable("Temp"); + + + /// The Computer Windows directory. For example "C:\Windows". + public static readonly string SysRoot = Environment.GetEnvironmentVariable("SystemRoot"); + + + /// The Computer System32 directory. For example "C:\Windows\System32". + public static readonly string SysRoot32 = System.IO.Path.Combine(SysRoot, "System32"); + + + /// The User's app data directory. For example "C:\Users\john\AppData\Roaming". + public static readonly string AppData = Environment.GetEnvironmentVariable("AppData"); + + + public static readonly string NotepadExe = System.IO.Path.Combine(SysRoot32, "notepad.exe"); + + + public const string TextTrue = "IsTrue"; + public const string TextFalse = "IsFalse"; + public const string TenNumbers = "0123456789"; + public const string TextHelloWorld = "Hëllõ Wørld!"; + public const string TextGoodbyeWorld = "Góödbyé Wôrld!"; + public const string TextUnicode = "ÛņïÇòdè; ǖŤƑ"; + + public static readonly string MyStream = "ӍƔŞtrëƛɱ-" + GetRandomFileNameWithDiacriticCharacters(); + + public static readonly string MyStream2 = "myStreamTWO-" + GetRandomFileNameWithDiacriticCharacters(); + + public static readonly string[] AllStreams = {MyStream, MyStream2}; + + public static readonly string StreamStringContent = "(1) Computer: [" + Environment.MachineName + "]" + "\tHello there, " + Environment.UserName; + + 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) " + TextHelloWorld + " " + TextUnicode + }; + } +} diff --git a/AlphaFS.UnitTest/_Utils/UnitTestConstants.cs b/AlphaFS.UnitTest/_Utils/UnitTestConstants.cs deleted file mode 100644 index d4d75b76e..000000000 --- a/AlphaFS.UnitTest/_Utils/UnitTestConstants.cs +++ /dev/null @@ -1,312 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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.ComponentModel; -using System.Diagnostics; -using System.Globalization; -using System.Linq; -using System.Security.AccessControl; -using System.Text; - -namespace AlphaFS.UnitTest -{ - /// Containts static variables, used by unit tests. - public static partial class UnitTestConstants - { - #region Fields - - public const string Local = @"LOCAL"; - public const string Network = @"NETWORK"; - -#if NET35 - public const string EMspace = "\u3000"; -#endif - - /// The Computer name. - public static readonly string LocalHost = Environment.MachineName; - - /// The User temp directory. For example "C:\Users\john\AppData\Local\Temp". - public static readonly string TempFolder = Environment.GetEnvironmentVariable("Temp"); - - /// The Computer system drive. For example "C:". - public static readonly string SysDrive = Environment.GetEnvironmentVariable("SystemDrive"); - - /// The Computer Windows directory. For example "C:\Windows". - public static readonly string SysRoot = Environment.GetEnvironmentVariable("SystemRoot"); - - /// The Computer System32 directory. For example "C:\Windows\System32". - public static readonly string SysRoot32 = System.IO.Path.Combine(SysRoot, "System32"); - - /// The User's app data directory. For example "C:\Users\john\AppData\Roaming". - public static readonly string AppData = Environment.GetEnvironmentVariable("AppData"); - - public static readonly string NotepadExe = System.IO.Path.Combine(SysRoot32, "notepad.exe"); - - public const string TextTrue = "IsTrue"; - public const string TextFalse = "IsFalse"; - public const string TenNumbers = "0123456789"; - public const string TextHelloWorld = "Hëllõ Wørld!"; - public const string TextGoodbyeWorld = "Góödbyé Wôrld!"; - public const string TextUnicode = "ÛņïÇòdè; ǖŤƑ"; - - private static Stopwatch _stopWatcher; - - private static readonly string RandomName = GetRandomFileName(); - public static readonly string MyStream = "ӍƔŞtrëƛɱ-" + RandomName; - public static readonly string MyStream2 = "myStreamTWO-" + RandomName; - public static readonly string[] AllStreams = {MyStream, MyStream2}; - public static readonly string StreamStringContent = "(1) Computer: [" + LocalHost + "]" + "\tHello there, " + Environment.UserName; - public static readonly string[] StreamArrayContent = - { - "(1) The quick brown fox jumps over the lazy dog.", - "(2) Albert Einstein: \"Science is a wonderful thing if one does not have to earn one's living at it.\"", - "(3) " + TextHelloWorld + " " + TextUnicode - }; - - - #region InputPaths - - 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.GlobalRootPrefix + @"device\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\f", - SysDrive + @"\a\b\c\f.", - SysDrive + @"\a\b\c\f.t", - SysDrive + @"\a\b\c\f.tx", - SysDrive + @"\a\b\c\f.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\f", - Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.", - Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.t", - Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.tx", - Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.txt", - - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\f", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fi", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fil", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.e", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ex", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ext", - - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\f", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fi", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fil", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.e", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ex", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ext" - }; - - #endregion // InputPaths - - #endregion // Fields - - #region Methods - - public static string StopWatcher(bool start = false) - { - if (_stopWatcher == null) - _stopWatcher = new Stopwatch(); - - if (start) - { - _stopWatcher.Restart(); - return null; - } - - _stopWatcher.Stop(); - var ms = _stopWatcher.ElapsedMilliseconds; - var elapsed = _stopWatcher.Elapsed; - - return String.Format(CultureInfo.InvariantCulture, "*Duration: [{0}] ms. ({1})", ms, elapsed); - } - - - public static string Reporter(bool onlyTime = false) - { - var lastError = new Win32Exception(); - - StopWatcher(); - - return onlyTime - ? String.Format(CultureInfo.InvariantCulture, "\t\t{0}", StopWatcher()) - : String.Format(CultureInfo.InvariantCulture, "\t{0} [{1}: {2}]", StopWatcher(), lastError.NativeErrorCode, lastError.Message); - } - - - public static byte[] StringToByteArray(string str, params Encoding[] encoding) - { - var encode = encoding != null && encoding.Any() ? encoding[0] : new UTF8Encoding(true, true); - return encode.GetBytes(str); - } - - - 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); - } - - - public static void PrintUnitTestHeader(bool isNetwork) - { - Console.WriteLine("\n=== TEST {0} ===", isNetwork ? Network : Local); - } - - - public static string GetRandomFileName() - { - var randomFileName = System.IO.Path.GetRandomFileName(); - - switch (new Random().Next(0, 4)) - { - case 0: - break; - - case 1: - randomFileName = randomFileName.Replace("a", "ä"); - randomFileName = randomFileName.Replace("e", "ë"); - randomFileName = randomFileName.Replace("i", "ï"); - randomFileName = randomFileName.Replace("o", "ö"); - randomFileName = randomFileName.Replace("u", "ü"); - break; - - case 2: - randomFileName = randomFileName.Replace("a", "á"); - randomFileName = randomFileName.Replace("e", "é"); - randomFileName = randomFileName.Replace("i", "í"); - randomFileName = randomFileName.Replace("o", "ó"); - randomFileName = randomFileName.Replace("u", "ú"); - break; - - case 3: - randomFileName = randomFileName.Replace("a", "â"); - randomFileName = randomFileName.Replace("e", "ê"); - randomFileName = randomFileName.Replace("i", "î"); - randomFileName = randomFileName.Replace("o", "ô"); - randomFileName = randomFileName.Replace("u", "û"); - break; - } - - - return randomFileName; - } - - #endregion // Methods - } -} From 412dd4f721d77019c3d4fe9637d3c441e4eb7337 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 3 Feb 2018 17:38:40 +0100 Subject: [PATCH 021/133] Fixed unit test. --- .../AlphaFS Volume Class/AlphaFS.Volume.GetVolumeLabel.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetVolumeLabel.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetVolumeLabel.cs index 4a347f0ad..7f6582618 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetVolumeLabel.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetVolumeLabel.cs @@ -39,6 +39,10 @@ public void AlphaFS_Volume_GetVolumeLabel_Local_Success() foreach (var logicalDrive in System.IO.DriveInfo.GetDrives()) { + if (!logicalDrive.IsReady) + continue; + + Console.Write("\n#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, logicalDrive.Name); From 91ba6be1407cfb786e68cf82a899fd21a987d942 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 3 Feb 2018 18:24:33 +0100 Subject: [PATCH 022/133] Simplified unit test. --- .../AlphaFS.Volume.SetVolumeLabel.cs | 131 ++++++++---------- 1 file changed, 57 insertions(+), 74 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs index c57a4e5e5..23c58c970 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs @@ -21,6 +21,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; +using System.Reflection; namespace AlphaFS.UnitTest { @@ -29,97 +30,79 @@ public partial class AlphaFS_VolumeTest // Pattern: ___ - //[TestMethod] + [TestMethod] public void AlphaFS_Volume_SetVolumeLabel_Local_Success() { - UnitTestConstants.PrintUnitTestHeader(false); - Console.WriteLine(); - if (!UnitTestConstants.IsAdmin()) Assert.Inconclusive(); + UnitTestConstants.PrintUnitTestHeader(false); + Console.WriteLine(); + - const string newLabel = "ÂĽpĥæƑŞ ŠëtVőlümèĻāßƩl() Ťest"; - const string template = "\nSystem Drive: [{0}]\tCurrent Label: [{1}]"; var drive = UnitTestConstants.SysDrive; + const string newLabel = "ÂĽpĥæƑŞ ŠëtVőlümèĻāßƩl Ťest"; + + const string template = "System Drive: [{0}]\tCurrent Label: [{1}]"; + + - #region Get Label - var originalLabel = Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive); + // Get label. + + var originalLabel = new System.IO.DriveInfo(drive).VolumeLabel; + Console.WriteLine(template, drive, originalLabel); - Assert.IsTrue(originalLabel.Equals(Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive))); + Assert.AreEqual(originalLabel, Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive)); + + + + + // Set label. + + Console.WriteLine("\nSet label."); + + Alphaleonis.Win32.Filesystem.Volume.SetVolumeLabel(drive, newLabel); + + Console.WriteLine(template, drive, newLabel); + + Assert.AreEqual(newLabel, new System.IO.DriveInfo(drive).VolumeLabel); - #endregion // Get Label + Assert.AreEqual(newLabel, Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive)); - #region Set Label - var isLabelSet = false; + + // Remove label. + + Console.WriteLine("\nRemove label."); + + Alphaleonis.Win32.Filesystem.Volume.DeleteVolumeLabel(drive); + 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 + + Console.WriteLine(template, drive, currentLabel); + + Assert.AreEqual(new System.IO.DriveInfo(drive).VolumeLabel, Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive)); + + + + + // Restore label. + + Console.WriteLine("\nRestore label."); + + Alphaleonis.Win32.Filesystem.Volume.SetVolumeLabel(drive, originalLabel); + + currentLabel = Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive); + + Console.WriteLine(template, drive, currentLabel); + + Assert.AreEqual(currentLabel, new System.IO.DriveInfo(drive).VolumeLabel); + + Assert.AreEqual(currentLabel, Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(drive)); } } } From ec1dbf62119fb09d2d7a390c785f7e9f9558b763 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 4 Feb 2018 12:01:57 +0100 Subject: [PATCH 023/133] Modified method Utils.UnitSizeToText to treat negative values as zero. (#413) --- AlphaFS/Utils.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AlphaFS/Utils.cs b/AlphaFS/Utils.cs index b5f392f44..370e6f244 100644 --- a/AlphaFS/Utils.cs +++ b/AlphaFS/Utils.cs @@ -87,8 +87,12 @@ public static string UnitSizeToText(T numberOfBytes, CultureInfo cultureInfo) var sizeFormats = new[] {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}; var formatLength = sizeFormats.Length; + var bytes = Convert.ToDouble(numberOfBytes, CultureInfo.InvariantCulture); + if (bytes < 0) + bytes = 0; + var index = 0; while (index < formatLength && bytes > kb) { From 70056fa22a0f6a05321b364eac2791243b6bf340 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 5 Feb 2018 03:13:41 +0100 Subject: [PATCH 024/133] Initial commit: Network List Manager. --- .../AlphaFS_Host.EnumerateNetworks.cs | 47 +++++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 + AlphaFS/AlphaFS.csproj | 16 +- .../Host Class/Host.EnumerateNetworks.cs | 69 +++++++ .../NLM/Enumerations/ConnectivityStates.cs | 57 ++++++ .../Network/NLM/Enumerations/DomainType.cs | 38 ++++ .../NLM/Enumerations/NetworkCategory.cs | 36 ++++ .../Enumerations/NetworkConnectivityLevels.cs | 39 ++++ AlphaFS/Network/NLM/Interfaces/INetwork.cs | 154 +++++++++++++++ .../NLM/Interfaces/INetworkConnection.cs | 97 ++++++++++ .../NLM/Interfaces/INetworkListManager.cs | 114 ++++++++++++ AlphaFS/Network/NLM/Network.cs | 176 ++++++++++++++++++ AlphaFS/Network/NLM/NetworkCollection.cs | 58 ++++++ AlphaFS/Network/NLM/NetworkConnection.cs | 95 ++++++++++ .../NLM/NetworkConnectionCollection.cs | 58 ++++++ AlphaFS/Network/NLM/NetworkListManager.cs | 90 +++++++++ .../Network/NLM/NetworkListManagerClass.cs | 114 ++++++++++++ 17 files changed, 1258 insertions(+), 1 deletion(-) create mode 100644 AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs create mode 100644 AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs create mode 100644 AlphaFS/Network/NLM/Enumerations/ConnectivityStates.cs create mode 100644 AlphaFS/Network/NLM/Enumerations/DomainType.cs create mode 100644 AlphaFS/Network/NLM/Enumerations/NetworkCategory.cs create mode 100644 AlphaFS/Network/NLM/Enumerations/NetworkConnectivityLevels.cs create mode 100644 AlphaFS/Network/NLM/Interfaces/INetwork.cs create mode 100644 AlphaFS/Network/NLM/Interfaces/INetworkConnection.cs create mode 100644 AlphaFS/Network/NLM/Interfaces/INetworkListManager.cs create mode 100644 AlphaFS/Network/NLM/Network.cs create mode 100644 AlphaFS/Network/NLM/NetworkCollection.cs create mode 100644 AlphaFS/Network/NLM/NetworkConnection.cs create mode 100644 AlphaFS/Network/NLM/NetworkConnectionCollection.cs create mode 100644 AlphaFS/Network/NLM/NetworkListManager.cs create mode 100644 AlphaFS/Network/NLM/NetworkListManagerClass.cs diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs new file mode 100644 index 000000000..0180963e0 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs @@ -0,0 +1,47 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 Alphaleonis.Win32.Network; + +namespace AlphaFS.UnitTest +{ + public partial class AlphaFS_HostTest + { + [TestMethod] + public void AlphaFS_Host_EnumerateNetworks_Network_Success() + { + UnitTestConstants.PrintUnitTestHeader(true); + + + foreach (var network in Host.EnumerateNetworks()) + { + UnitTestConstants.Dump(network, -21); + + if (null != network.Connections) + { + foreach (var connection in network.Connections) + UnitTestConstants.Dump(connection, -21, true); + } + } + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 35c538a17..b0e5b7ff1 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -166,6 +166,7 @@ + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index a24adfae7..272a73f63 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -482,6 +482,7 @@ + @@ -489,15 +490,28 @@ + + + + + + + + + + + + + @@ -587,7 +601,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs b/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs new file mode 100644 index 000000000..208e59e21 --- /dev/null +++ b/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs @@ -0,0 +1,69 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Net.NetworkInformation; +using System.Security; + +namespace Alphaleonis.Win32.Network +{ + partial class Host + { + /// Enumerates drives from the local host. + /// drives from the local host. + /// + [SecurityCritical] + public static IEnumerable EnumerateNetworks() + { + return EnumerateNetworksCore(NetworkConnectivityLevels.All); + } + + + /// Enumerates drives from the local host. + /// drives from the local host. + /// + [SecurityCritical] + public static IEnumerable EnumerateNetworks(NetworkConnectivityLevels networkConnectivityLevels) + { + return EnumerateNetworksCore(networkConnectivityLevels); + } + + + /// Enumerates local drives from the specified host. + /// drives from the specified host. + /// + /// + /// The DNS or NetBIOS name of the remote server. refers to the local host. + /// + /// suppress any Exception that might be thrown as a result from a failure, + /// such as unavailable resources. + /// + [SecurityCritical] + private static IEnumerable EnumerateNetworksCore(NetworkConnectivityLevels networkConnectivityLevels) + { + foreach (var network in NetworkListManager.GetNetworks(networkConnectivityLevels)) + + yield return network; + } + } +} diff --git a/AlphaFS/Network/NLM/Enumerations/ConnectivityStates.cs b/AlphaFS/Network/NLM/Enumerations/ConnectivityStates.cs new file mode 100644 index 000000000..ac3a049e4 --- /dev/null +++ b/AlphaFS/Network/NLM/Enumerations/ConnectivityStates.cs @@ -0,0 +1,57 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Specifies types of network connectivity state. + [Flags] + public enum ConnectivityStates + { + /// The underlying network interfaces have no connectivity to any network. + None = 0, + + /// There is connectivity to a network, but the service cannot detect any IPv4 Network Traffic. + IPv4NoTraffic = 1, + + /// There is connectivity to a network, but the service cannot detect any IPv6 Network Traffic. + IPv6NoTraffic = 2, + + /// There is connectivity to the local subnet using the IPv4 protocol. + IPv4Subnet = 16, + + /// There is connectivity to a routed network using the IPv4 protocol. + IPv4LocalNetwork = 32, + + /// There is connectivity to the Internet using the IPv4 protocol. + IPv4Internet = 64, + + /// There is connectivity to the local subnet using the IPv6 protocol. + IPv6Subnet = 256, + + /// There is connectivity to a local network using the IPv6 protocol. + IPv6LocalNetwork = 512, + + /// There is connectivity to the Internet using the IPv6 protocol. + IPv6Internet = 1024 + } +} diff --git a/AlphaFS/Network/NLM/Enumerations/DomainType.cs b/AlphaFS/Network/NLM/Enumerations/DomainType.cs new file mode 100644 index 000000000..98ddb614b --- /dev/null +++ b/AlphaFS/Network/NLM/Enumerations/DomainType.cs @@ -0,0 +1,38 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Specifies the domain type of a network. + public enum DomainType + { + /// The Network is not an Active Directory Network. + None = 0, + + + /// The Network is an Active Directory Network, but this machine is not authenticated against it. + DomainNetwork = 1, + + + /// The Network is an Active Directory Network, and this machine is authenticated against it. + DomainAuthenticated = 2 + } +} diff --git a/AlphaFS/Network/NLM/Enumerations/NetworkCategory.cs b/AlphaFS/Network/NLM/Enumerations/NetworkCategory.cs new file mode 100644 index 000000000..08a1555e7 --- /dev/null +++ b/AlphaFS/Network/NLM/Enumerations/NetworkCategory.cs @@ -0,0 +1,36 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Specifies the category type of a network. + public enum NetworkCategory + { + /// The network is a public (untrusted) network. + Public, + + /// The network is a private (trusted) network. + Private, + + /// The network is authenticated against an Active Directory domain. + Authenticated + } +} diff --git a/AlphaFS/Network/NLM/Enumerations/NetworkConnectivityLevels.cs b/AlphaFS/Network/NLM/Enumerations/NetworkConnectivityLevels.cs new file mode 100644 index 000000000..56d350fa8 --- /dev/null +++ b/AlphaFS/Network/NLM/Enumerations/NetworkConnectivityLevels.cs @@ -0,0 +1,39 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Specifies what types of networks are enumerated. + [Flags] + public enum NetworkConnectivityLevels + { + /// Returns connected networks. + Connected = 1, + + /// Returns disconnected networks. + Disconnected = 2, + + /// Returns connected and disconnected networks. + All = Connected | Disconnected + } +} diff --git a/AlphaFS/Network/NLM/Interfaces/INetwork.cs b/AlphaFS/Network/NLM/Interfaces/INetwork.cs new file mode 100644 index 000000000..d0c0aca23 --- /dev/null +++ b/AlphaFS/Network/NLM/Interfaces/INetwork.cs @@ -0,0 +1,154 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// The INetwork interface represents a network on the local machine. It can also represent a collection of network connections with a similar network signature. + [ComImport, TypeLibType(0x1040), Guid("DCB00002-570F-4A9B-8D69-199FDBA5723B")] + internal interface INetwork + { + // Do not change the order of these interface members. + + + /// Returns the name of the network. + /// Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + [return: MarshalAs(UnmanagedType.BStr)] + string GetName(); + + + /// Sets or renames the network. This change occurs immediately. + /// 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. + /// + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + void SetName([In, MarshalAs(UnmanagedType.BStr)] string szNetworkNewName); + + + /// Returns a description string for the network. + /// Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + [return: MarshalAs(UnmanagedType.BStr)] + string GetDescription(); + + + /// Sets a new description for the network. + /// 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. + /// + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + void SetDescription([In, MarshalAs(UnmanagedType.BStr)] string szDescription); + + + /// Returns the unique identifier of a network. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + Guid GetNetworkId(); + + + /// Returns the type of network. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + DomainType GetDomainType(); + + + /// Returns an enumeration of all network connections for a network. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + [return: MarshalAs(UnmanagedType.Interface)] + IEnumerable GetNetworkConnections(); + + + /// Returns the local date and time when the network was created and connected. + /// Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + void GetTimeCreatedAndConnected(out uint pdwLowDateTimeCreated, out uint pdwHighDateTimeCreated, out uint pdwLowDateTimeConnected, out uint pdwHighDateTimeConnected); + + + /// Specifies if the network has any network connectivity. + /// If TRUE, this network is connected; if FALSE, it is not. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + bool IsConnected + { + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + get; + } + + + /// Specifies if the network has Internet connectivity. + /// If TRUE, this network has connectivity to the internet; if FALSE, it does not. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + bool IsConnectedToInternet + { + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + get; + } + + + /// Returns the connectivity state of the network. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + ConnectivityStates GetConnectivity(); + + + /// Returns the category of a network. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + NetworkCategory GetCategory(); + + + /// Sets the category of a network. Administrative privileges are needed for this API call. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + void SetCategory([In] NetworkCategory NewCategory); + } +} diff --git a/AlphaFS/Network/NLM/Interfaces/INetworkConnection.cs b/AlphaFS/Network/NLM/Interfaces/INetworkConnection.cs new file mode 100644 index 000000000..54f117b31 --- /dev/null +++ b/AlphaFS/Network/NLM/Interfaces/INetworkConnection.cs @@ -0,0 +1,97 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// The INetworkConnection interface represents a single network connection. + [ComImport, TypeLibType(0x1040), Guid("DCB00005-570F-4A9B-8D69-199FDBA5723B")] + internal interface INetworkConnection + { + // Do not change the order of these interface members. + + + /// Returns the associated network for the connection. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + [return: MarshalAs(UnmanagedType.Interface)] + INetwork GetNetwork(); + + + /// Specifies if the network has any network connectivity. + /// If TRUE, this network connection has connectivity; if FALSE, it does not. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + bool IsConnected + { + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + get; + } + + + /// Specifies if the network has Internet connectivity. + /// If TRUE, this network connection has connectivity to the Internet; if FALSE, it does not. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + bool IsConnectedToInternet + { + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + get; + } + + + /// Returns the connectivity state of the network. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + ConnectivityStates GetConnectivity(); + + + /// Returns the Connection ID associated with this network connection. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + Guid GetConnectionId(); + + + /// Returns the ID of the network adapter used by this connection. There may multiple connections using the same adapter ID. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + Guid GetAdapterId(); + + + /// Returns the type of network connection. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + DomainType GetDomainType(); + } +} diff --git a/AlphaFS/Network/NLM/Interfaces/INetworkListManager.cs b/AlphaFS/Network/NLM/Interfaces/INetworkListManager.cs new file mode 100644 index 000000000..4e37b9aab --- /dev/null +++ b/AlphaFS/Network/NLM/Interfaces/INetworkListManager.cs @@ -0,0 +1,114 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// The INetworkListManager interface provides a set of methods to perform network list management functions. + [ComImport, Guid("DCB00000-570F-4A9B-8D69-199FDBA5723B"), TypeLibType(0x1040)] + internal interface INetworkListManager + { + // Do not change the order of these interface members. + + + /// Retrieves networks based on the supplied Network IDs. + /// 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. + /// + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + [return: MarshalAs(UnmanagedType.Interface)] + IEnumerable GetNetworks([In] NetworkConnectivityLevels Flags); + + + /// Retrieves a network based on a supplied Network ID. + /// 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. + /// + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + [return: MarshalAs(UnmanagedType.Interface)] + INetwork GetNetwork([In] Guid gdNetworkId); + + + /// Gets an enumerator that contains a complete list of the network connections that have been made. + /// Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + [return: MarshalAs(UnmanagedType.Interface)] + IEnumerable GetNetworkConnections(); + + + /// Retrieves a network based on a supplied Network Connection ID. + /// 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. + /// + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + [return: MarshalAs(UnmanagedType.Interface)] + INetworkConnection GetNetworkConnection([In] Guid gdNetworkConnectionId); + + + /// Specifies if the machine has network connectivity. + /// + /// 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. + /// + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + bool IsConnected + { + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + get; + } + + + /// Specifies if the machine has Internet connectivity. + /// If TRUE, the local machine is connected to the internet; if FALSE, it is not. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + bool IsConnectedToInternet + { + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + get; + } + + + /// Returns the connectivity state of all the networks on a machine. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] + ConnectivityStates GetConnectivity(); + } +} diff --git a/AlphaFS/Network/NLM/Network.cs b/AlphaFS/Network/NLM/Network.cs new file mode 100644 index 000000000..9b7aa6d38 --- /dev/null +++ b/AlphaFS/Network/NLM/Network.cs @@ -0,0 +1,176 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Represents a network on the local machine. It can also represent a collection of network connections with a similar network signature. + /// Instances of this class are obtained by calling methods on the class. + public class Network + { + private readonly INetwork _network; + + + internal Network(INetwork network) + { + _network = network; + } + + + /// Gets or sets the category of a network. The categories are trusted, untrusted, or authenticated. + /// A value. + public NetworkCategory Category + { + get { return _network.GetCategory(); } + + set { _network.SetCategory(value); } + } + + + /// Gets the local date and time when the network was connected. + /// A object. + public DateTime ConnectionTime + { + get { return ConnectionTimeUtc.ToLocalTime(); } + } + + + /// Gets the local date and time when the network was connected. + /// A object. + public DateTime ConnectionTimeUtc + { + get + { + uint low, high, dummy1, dummy2; + + _network.GetTimeCreatedAndConnected(out dummy1, out dummy2, out low, out high); + + long time = high; + + // Shift the day info into the high order bits. + time <<= 32; + time |= low; + + return DateTime.FromFileTimeUtc(time); + } + } + + + /// Gets the network connections for the network. + /// A object. + public NetworkConnectionCollection Connections + { + get { return new NetworkConnectionCollection(_network.GetNetworkConnections()); } + } + + + /// Gets the connectivity state of the network. + /// A value. + /// Connectivity provides information on whether the network is connected, and the protocols in use for network traffic. + public ConnectivityStates Connectivity + { + get { return _network.GetConnectivity(); } + } + + + /// Gets the local date and time when the network was created. + /// A object. + public DateTime CreationTime + { + get { return CreationTimeUtc.ToLocalTime(); } + } + + + /// Gets the local date and time when the network was created. + /// A object. + public DateTime CreationTimeUtc + { + get + { + uint low, high, dummy1, dummy2; + + _network.GetTimeCreatedAndConnected(out low, out high, out dummy1, out dummy2); + + long time = high; + + // Shift the value into the high order bits. + time <<= 32; + time |= low; + + return DateTime.FromFileTimeUtc(time); + } + } + + + /// Gets a description for the network. + /// A value. + public string Description + { + get { return _network.GetDescription(); } + + //set { _network.SetDescription(value); } + } + + + /// Gets the domain type of the network. + /// A value. + /// The domain indictates whether the network is an Active Directory Network, and whether the machine has been authenticated by Active Directory. + public DomainType DomainType + { + get { return _network.GetDomainType(); } + } + + + /// Gets a value that indicates whether there is network connectivity. + /// A value. + public bool IsConnected + { + get { return _network.IsConnected; } + } + + + /// Gets a value that indicates whether there is Internet connectivity. + /// A value. + public bool IsConnectedToInternet + { + get { return _network.IsConnectedToInternet; } + } + + + /// Gets the name of the network. + /// A value. + public string Name + { + get { return _network.GetName(); } + + //set { _network.SetName(value); } + } + + + /// Gets a unique identifier for the network. + /// A value. + public Guid NetworkId + { + get { return _network.GetNetworkId(); } + } + } +} diff --git a/AlphaFS/Network/NLM/NetworkCollection.cs b/AlphaFS/Network/NLM/NetworkCollection.cs new file mode 100644 index 000000000..b98901d9f --- /dev/null +++ b/AlphaFS/Network/NLM/NetworkCollection.cs @@ -0,0 +1,58 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; +using System.Collections.Generic; + +namespace Alphaleonis.Win32.Network +{ + /// An enumerable collection of objects. + public class NetworkCollection : IEnumerable + { + private readonly IEnumerable _networkEnumerable; + + + internal NetworkCollection(IEnumerable networkEnumerable) + { + _networkEnumerable = networkEnumerable; + } + + + /// Returns the strongly typed enumerator for this collection. + /// An object. + public IEnumerator GetEnumerator() + { + foreach (INetwork network in _networkEnumerable) + + yield return new Network(network); + } + + + /// Returns the enumerator for this collection. + ///An object. + IEnumerator IEnumerable.GetEnumerator() + { + foreach (INetwork network in _networkEnumerable) + + yield return new Network(network); + } + } +} \ No newline at end of file diff --git a/AlphaFS/Network/NLM/NetworkConnection.cs b/AlphaFS/Network/NLM/NetworkConnection.cs new file mode 100644 index 000000000..47bd8afb1 --- /dev/null +++ b/AlphaFS/Network/NLM/NetworkConnection.cs @@ -0,0 +1,95 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Represents a connection to a network. + /// A collection containing instances of this class is obtained by calling + /// the property. + public class NetworkConnection + { + private readonly INetworkConnection _networkConnection; + + + internal NetworkConnection(INetworkConnection networkConnection) + { + _networkConnection = networkConnection; + } + + + /// Retrieves an object that represents the network associated with this connection. + /// A object. + public Network Network + { + get { return new Network(_networkConnection.GetNetwork()); } + } + + + /// Gets the adapter identifier for this connection. + /// A object. + public Guid AdapterId + { + get { return _networkConnection.GetAdapterId(); } + } + + + /// Gets the unique identifier for this connection. + /// A object. + public Guid ConnectionId + { + get { return _networkConnection.GetConnectionId(); } + } + + + /// Gets a value that indicates the connectivity of this connection. + /// A value. + public ConnectivityStates Connectivity + { + get { return _networkConnection.GetConnectivity(); } + } + + + /// 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. + /// A value. + public DomainType DomainType + { + get { return _networkConnection.GetDomainType(); } + } + + + /// Gets a value that indicates whether this connection has Internet access. + /// A value. + public bool IsConnectedToInternet + { + get { return _networkConnection.IsConnectedToInternet; } + } + + + /// Gets a value that indicates whether this connection has network connectivity. + /// A value. + public bool IsConnected + { + get { return _networkConnection.IsConnected; } + } + } +} diff --git a/AlphaFS/Network/NLM/NetworkConnectionCollection.cs b/AlphaFS/Network/NLM/NetworkConnectionCollection.cs new file mode 100644 index 000000000..26de44add --- /dev/null +++ b/AlphaFS/Network/NLM/NetworkConnectionCollection.cs @@ -0,0 +1,58 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; +using System.Collections.Generic; + +namespace Alphaleonis.Win32.Network +{ + /// An enumerable collection of objects. + public class NetworkConnectionCollection : IEnumerable + { + private readonly IEnumerable _networkConnectionEnumerable; + + + internal NetworkConnectionCollection(IEnumerable networkConnectionEnumerable) + { + _networkConnectionEnumerable = networkConnectionEnumerable; + } + + + /// Returns the strongly typed enumerator for this collection. + /// A object. + public IEnumerator GetEnumerator() + { + foreach (INetworkConnection networkConnection in _networkConnectionEnumerable) + + yield return new NetworkConnection(networkConnection); + } + + + /// Returns the enumerator for this collection. + ///A object. + IEnumerator IEnumerable.GetEnumerator() + { + foreach (INetworkConnection networkConnection in _networkConnectionEnumerable) + + yield return new NetworkConnection(networkConnection); + } + } +} diff --git a/AlphaFS/Network/NLM/NetworkListManager.cs b/AlphaFS/Network/NLM/NetworkListManager.cs new file mode 100644 index 000000000..71bb13867 --- /dev/null +++ b/AlphaFS/Network/NLM/NetworkListManager.cs @@ -0,0 +1,90 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Provides access to objects that represent networks and network connections. + public static class NetworkListManager + { + private static readonly NetworkListManagerClass Manager = new NetworkListManagerClass(); + + + /// Retrieves a collection of objects that represent the networks defined for this machine. + /// The that specify the connectivity level of the returned objects. + /// A of objects. + public static NetworkCollection GetNetworks(NetworkConnectivityLevels level) + { + return new NetworkCollection(Manager.GetNetworks(level)); + } + + + /// Retrieves the identified by the specified network identifier. + /// A that specifies the unique identifier for the network. + /// The that represents the network identified by the identifier. + public static Network GetNetwork(Guid networkId) + { + return new Network(Manager.GetNetwork(networkId)); + } + + + /// Retrieves a collection of objects that represent the connections for this machine. + /// A containing the network connections. + public static NetworkConnectionCollection GetNetworkConnections() + { + return new NetworkConnectionCollection(Manager.GetNetworkConnections()); + } + + + /// Retrieves the identified by the specified connection identifier. + /// A that specifies the unique identifier for the network connection. + /// The identified by the specified identifier. + public static NetworkConnection GetNetworkConnection(Guid networkConnectionId) + { + return new NetworkConnection(Manager.GetNetworkConnection(networkConnectionId)); + } + + + /// Gets a value that indicates whether this machine has Internet connectivity. + /// A value. + public static bool IsConnectedToInternet + { + get { return Manager.IsConnectedToInternet; } + } + + + /// Gets a value that indicates whether this machine has network connectivity. + /// A value. + public static bool IsConnected + { + get { return Manager.IsConnected; } + } + + + /// Gets the connectivity state of this machine. + /// A value. + public static ConnectivityStates Connectivity + { + get { return Manager.GetConnectivity(); } + } + } +} \ No newline at end of file diff --git a/AlphaFS/Network/NLM/NetworkListManagerClass.cs b/AlphaFS/Network/NLM/NetworkListManagerClass.cs new file mode 100644 index 000000000..cd5a6ac9f --- /dev/null +++ b/AlphaFS/Network/NLM/NetworkListManagerClass.cs @@ -0,0 +1,114 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// The NetworkListManagerClass class provides a set of methods to perform network list read-only management functions. + [ComImport, ClassInterface((short) 0), Guid("DCB00C01-570F-4A9B-8D69-199FDBA5723B")] + [ComSourceInterfaces("Microsoft.Windows.NetworkList.Internal.INetworkEvents\0Microsoft.Windows.NetworkList.Internal.INetworkConnectionEvents\0Microsoft.Windows.NetworkList.Internal.INetworkListManagerEvents\0"), TypeLibType(2)] + internal class NetworkListManagerClass : INetworkListManager + { + /// Returns the connectivity state of all the networks on a machine. + /// Returns S_OK if the method succeeds. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(7)] + public extern ConnectivityStates GetConnectivity(); + + + /// Retrieves a network based on a supplied Network ID. + /// 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. + /// + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2)] + [return: MarshalAs(UnmanagedType.Interface)] + public extern INetwork GetNetwork([In] Guid gdNetworkId); + + + /// Retrieves a network based on a supplied Network Connection ID. + /// 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. + /// + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(4)] + [return: MarshalAs(UnmanagedType.Interface)] + public extern INetworkConnection GetNetworkConnection([In] Guid gdNetworkConnectionId); + + + /// Gets an enumerator that contains a complete list of the network connections that have been made. + /// Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(3)] + [return: MarshalAs(UnmanagedType.Interface)] + public extern IEnumerable GetNetworkConnections(); + + + /// Retrieves networks based on the supplied Network IDs. + /// 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. + /// + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(1)] + [return: MarshalAs(UnmanagedType.Interface)] + public extern IEnumerable GetNetworks([In] NetworkConnectivityLevels Flags); + + + /// Specifies if the machine has network connectivity. + /// + /// 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. + /// + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [DispId(6)] + public extern bool IsConnected + { + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(6)] + get; + } + + + /// Specifies if the machine has Internet connectivity. + /// If TRUE, the local machine is connected to the internet; if FALSE, it is not. + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + [DispId(5)] + public extern bool IsConnectedToInternet + { + [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(5)] + get; + } + } +} From b266b7190f7be7ac3fd62c60b6e9b6a2dc6f3816 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 5 Feb 2018 03:14:30 +0100 Subject: [PATCH 025/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumerateLogicalDrives.cs | 4 +- .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 4 +- .../AlphaFS_Device.EnumerateVolumes.cs | 4 +- .../AlphaFS_DeviceInfo.InitializeInstance.cs | 59 ------------------- .../AlphaFS.Volume.GetVolumeLabel.cs | 2 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 - AlphaFS/Device/Device.GetPhysicalDriveInfo.cs | 18 ++++-- AlphaFS/Device/PhysicalDriveInfo.cs | 3 - 8 files changed, 21 insertions(+), 74 deletions(-) delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo.InitializeInstance.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs index afa22d9cf..8b95dab87 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs @@ -33,8 +33,8 @@ public partial class AlphaFS_DeviceTest [TestMethod] public void AlphaFS_Device_EnumerateLogicalDrives_Local_Success() { - if (!UnitTestConstants.IsAdmin()) - Assert.Inconclusive(); + //if (!UnitTestConstants.IsAdmin()) + // Assert.Inconclusive(); UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs index 8b85203b9..1f03eb8cc 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -33,8 +33,8 @@ public partial class AlphaFS_DeviceTest [TestMethod] public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() { - if (!UnitTestConstants.IsAdmin()) - Assert.Inconclusive(); + //if (!UnitTestConstants.IsAdmin()) + // Assert.Inconclusive(); UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs index 9a4bfae4a..b8a7b50ef 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs @@ -33,8 +33,8 @@ public partial class AlphaFS_DeviceTest [TestMethod] public void AlphaFS_Device_EnumerateVolumes_Local_Success() { - if (!UnitTestConstants.IsAdmin()) - Assert.Inconclusive(); + //if (!UnitTestConstants.IsAdmin()) + // Assert.Inconclusive(); UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo.InitializeInstance.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo.InitializeInstance.cs deleted file mode 100644 index 0f07fcba9..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo.InitializeInstance.cs +++ /dev/null @@ -1,59 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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_DeviceTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_DeviceInfo_InitializeInstance_Local_Success() - { - DeviceInfo_InitializeInstance(false); - } - - - private void DeviceInfo_InitializeInstance(bool isNetwork) - { - Console.WriteLine("MSDN 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."); - - UnitTestConstants.PrintUnitTestHeader(false); - - - var deviceInfo = new Alphaleonis.Win32.Filesystem.DeviceInfo(isNetwork ? UnitTestConstants.LocalHost : string.Empty); - - UnitTestConstants.Dump(deviceInfo, -24); - - Assert.AreEqual(deviceInfo.HostName, UnitTestConstants.LocalHost); - Assert.AreEqual(deviceInfo.DeviceClass, null); - Assert.AreEqual(deviceInfo.ClassGuid, new Guid()); - - - Console.WriteLine(); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetVolumeLabel.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetVolumeLabel.cs index 7f6582618..eb0b90762 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetVolumeLabel.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetVolumeLabel.cs @@ -48,7 +48,7 @@ public void AlphaFS_Volume_GetVolumeLabel_Local_Success() var volumeLabel = Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(logicalDrive.Name); - Console.WriteLine("\t\tLabel: [{2}]", ++logicalDriveCount, logicalDrive.Name, logicalDrive.VolumeLabel); + Console.WriteLine("\t\tLabel: [{0}]", volumeLabel); Assert.AreEqual(logicalDrive.VolumeLabel, volumeLabel, "The volume labels do not match, but it is expected."); diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 5660c04e4..7de8c41d7 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -167,7 +167,6 @@ - diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs index 8956bbb78..bf54be1e9 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs @@ -99,12 +99,22 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De { var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, diskNumber.ToString(CultureInfo.InvariantCulture)); - SetStorageData(physicalDrive, physicalDriveInfo); + try + { + SetStorageData(physicalDrive, physicalDriveInfo); + } + catch { } } if (null != logicalDrive) - GetVolumeDiskExtents(logicalDrive); + { + try + { + GetVolumeDiskExtents(logicalDrive); + } + catch { } + } return physicalDriveInfo; @@ -190,10 +200,10 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. - //const int desiredAccess = 0; + const int desiredAccess = 0; // Requires elevation for. - const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; + //const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; diff --git a/AlphaFS/Device/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo.cs index 88730f3b0..2c3c4805a 100644 --- a/AlphaFS/Device/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo.cs @@ -20,10 +20,8 @@ */ using System; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -39,7 +37,6 @@ public sealed class PhysicalDriveInfo public PhysicalDriveInfo() { PartitionNumber = -1; - TotalSize = -1; } From 63745e5e6cca0071362902ab0cf7f1e390e5bc47 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 5 Feb 2018 19:16:18 +0100 Subject: [PATCH 026/133] Completed. --- ...lphaFS_Host.EnumerateNetworkConnections.cs | 57 +++++++ .../AlphaFS_Host.EnumerateNetworks.cs | 21 ++- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 + AlphaFS/AlphaFS.csproj | 29 ++-- .../Enumerations/ConnectivityStates.cs | 11 +- .../{NLM => }/Enumerations/DomainType.cs | 0 .../{NLM => }/Enumerations/NetworkCategory.cs | 0 .../Enumerations/NetworkConnectivityLevels.cs | 5 +- .../Host.EnumerateNetworkConnections.cs | 58 +++++++ .../Host Class/Host.EnumerateNetworks.cs | 48 +++--- .../Host.GetNetwork.cs} | 45 ++---- .../Host Class/Host.GetNetworkConnection.cs | 43 +++++ AlphaFS/Network/Host Class/Host.GetUncName.cs | 55 +++++++ AlphaFS/Network/Host Class/Host.cs | 114 +++++-------- AlphaFS/Network/NLM/NetworkConnection.cs | 95 ----------- .../NLM/NetworkConnectionCollection.cs | 58 ------- AlphaFS/Network/NLM/NetworkListManager.cs | 90 ----------- .../NativeMethods.INetwork.cs} | 30 ++-- .../NativeMethods.INetworkConnection.cs} | 16 +- .../NativeMethods.INetworkListManager.cs} | 4 +- AlphaFS/Network/NetworkConnectionInfo.cs | 150 ++++++++++++++++++ .../{NLM/Network.cs => NetworkInfo.cs} | 97 ++++++----- ...tManagerClass.cs => NetworkListManager.cs} | 22 +-- 23 files changed, 580 insertions(+), 469 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs rename AlphaFS/Network/{NLM => }/Enumerations/ConnectivityStates.cs (71%) rename AlphaFS/Network/{NLM => }/Enumerations/DomainType.cs (100%) rename AlphaFS/Network/{NLM => }/Enumerations/NetworkCategory.cs (100%) rename AlphaFS/Network/{NLM => }/Enumerations/NetworkConnectivityLevels.cs (92%) create mode 100644 AlphaFS/Network/Host Class/Host.EnumerateNetworkConnections.cs rename AlphaFS/Network/{NLM/NetworkCollection.cs => Host Class/Host.GetNetwork.cs} (50%) create mode 100644 AlphaFS/Network/Host Class/Host.GetNetworkConnection.cs create mode 100644 AlphaFS/Network/Host Class/Host.GetUncName.cs delete mode 100644 AlphaFS/Network/NLM/NetworkConnection.cs delete mode 100644 AlphaFS/Network/NLM/NetworkConnectionCollection.cs delete mode 100644 AlphaFS/Network/NLM/NetworkListManager.cs rename AlphaFS/Network/{NLM/Interfaces/INetwork.cs => Native Methods/NativeMethods.INetwork.cs} (82%) rename AlphaFS/Network/{NLM/Interfaces/INetworkConnection.cs => Native Methods/NativeMethods.INetworkConnection.cs} (82%) rename AlphaFS/Network/{NLM/Interfaces/INetworkListManager.cs => Native Methods/NativeMethods.INetworkListManager.cs} (97%) create mode 100644 AlphaFS/Network/NetworkConnectionInfo.cs rename AlphaFS/Network/{NLM/Network.cs => NetworkInfo.cs} (59%) rename AlphaFS/Network/{NLM/NetworkListManagerClass.cs => NetworkListManager.cs} (83%) diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs new file mode 100644 index 000000000..3c23d6862 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs @@ -0,0 +1,57 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; +using Alphaleonis.Win32.Network; + +namespace AlphaFS.UnitTest +{ + public partial class AlphaFS_HostTest + { + [TestMethod] + public void AlphaFS_Host_EnumerateNetworkConnections_Local_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + + var networkConnectionCount = 0; + + foreach (var networkConnection in Host.EnumerateNetworkConnections().OrderBy(networkConnection => networkConnection.NetworkInfo.Name)) + { + Console.WriteLine("\n#{0:000}\tNetwork: [{1}]", ++networkConnectionCount, networkConnection.NetworkInfo.Name); + + + UnitTestConstants.Dump(networkConnection, -21); + + UnitTestConstants.Dump(networkConnection.NetworkInfo, -21, true); + + + Console.WriteLine(); + } + + + if (networkConnectionCount == 0) + Assert.Inconclusive("No network connections enumerated, but it is expected."); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs index 0180963e0..2b64d9d49 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs @@ -19,6 +19,8 @@ * THE SOFTWARE. */ +using System; +using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Alphaleonis.Win32.Network; @@ -27,21 +29,34 @@ namespace AlphaFS.UnitTest public partial class AlphaFS_HostTest { [TestMethod] - public void AlphaFS_Host_EnumerateNetworks_Network_Success() + public void AlphaFS_Host_EnumerateNetworks_Local_Success() { - UnitTestConstants.PrintUnitTestHeader(true); + UnitTestConstants.PrintUnitTestHeader(false); - foreach (var network in Host.EnumerateNetworks()) + var networkCount = 0; + + foreach (var network in Host.EnumerateNetworks().OrderBy(network => network.Name)) { + Console.WriteLine("\n#{0:000}\tNetwork: [{1}]", ++networkCount, network.Name); + + UnitTestConstants.Dump(network, -21); + if (null != network.Connections) { foreach (var connection in network.Connections) UnitTestConstants.Dump(connection, -21, true); } + + + Console.WriteLine(); } + + + if (networkCount == 0) + Assert.Inconclusive("No networks enumerated, but it is expected."); } } } diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index b0e5b7ff1..b189905c4 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -165,6 +165,7 @@ + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 272a73f63..b763f2e9e 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -482,6 +482,10 @@ + + + + @@ -490,28 +494,25 @@ - - - - - - + + + + + + - + - - - - - - + + + @@ -601,7 +602,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Network/NLM/Enumerations/ConnectivityStates.cs b/AlphaFS/Network/Enumerations/ConnectivityStates.cs similarity index 71% rename from AlphaFS/Network/NLM/Enumerations/ConnectivityStates.cs rename to AlphaFS/Network/Enumerations/ConnectivityStates.cs index ac3a049e4..9b6337296 100644 --- a/AlphaFS/Network/NLM/Enumerations/ConnectivityStates.cs +++ b/AlphaFS/Network/Enumerations/ConnectivityStates.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,7 @@ */ using System; +using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Network { @@ -31,27 +32,35 @@ public enum ConnectivityStates None = 0, /// There is connectivity to a network, but the service cannot detect any IPv4 Network Traffic. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")] IPv4NoTraffic = 1, /// There is connectivity to a network, but the service cannot detect any IPv6 Network Traffic. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")] IPv6NoTraffic = 2, /// There is connectivity to the local subnet using the IPv4 protocol. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")] IPv4Subnet = 16, /// There is connectivity to a routed network using the IPv4 protocol. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")] IPv4LocalNetwork = 32, /// There is connectivity to the Internet using the IPv4 protocol. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")] IPv4Internet = 64, /// There is connectivity to the local subnet using the IPv6 protocol. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")] IPv6Subnet = 256, /// There is connectivity to a local network using the IPv6 protocol. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")] IPv6LocalNetwork = 512, /// There is connectivity to the Internet using the IPv6 protocol. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pv")] IPv6Internet = 1024 } } diff --git a/AlphaFS/Network/NLM/Enumerations/DomainType.cs b/AlphaFS/Network/Enumerations/DomainType.cs similarity index 100% rename from AlphaFS/Network/NLM/Enumerations/DomainType.cs rename to AlphaFS/Network/Enumerations/DomainType.cs diff --git a/AlphaFS/Network/NLM/Enumerations/NetworkCategory.cs b/AlphaFS/Network/Enumerations/NetworkCategory.cs similarity index 100% rename from AlphaFS/Network/NLM/Enumerations/NetworkCategory.cs rename to AlphaFS/Network/Enumerations/NetworkCategory.cs diff --git a/AlphaFS/Network/NLM/Enumerations/NetworkConnectivityLevels.cs b/AlphaFS/Network/Enumerations/NetworkConnectivityLevels.cs similarity index 92% rename from AlphaFS/Network/NLM/Enumerations/NetworkConnectivityLevels.cs rename to AlphaFS/Network/Enumerations/NetworkConnectivityLevels.cs index 56d350fa8..9a4fe42b5 100644 --- a/AlphaFS/Network/NLM/Enumerations/NetworkConnectivityLevels.cs +++ b/AlphaFS/Network/Enumerations/NetworkConnectivityLevels.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -27,6 +27,9 @@ namespace Alphaleonis.Win32.Network [Flags] public enum NetworkConnectivityLevels { + /// Unknown. + None = 0, + /// Returns connected networks. Connected = 1, diff --git a/AlphaFS/Network/Host Class/Host.EnumerateNetworkConnections.cs b/AlphaFS/Network/Host Class/Host.EnumerateNetworkConnections.cs new file mode 100644 index 000000000..e4d8da51c --- /dev/null +++ b/AlphaFS/Network/Host Class/Host.EnumerateNetworkConnections.cs @@ -0,0 +1,58 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 partial class Host + { + /// [AlphaFS] Returns an enumerable collection of defined network connections on the local host. + /// An collection of defined network connections on the local host. + [SecurityCritical] + public static IEnumerable EnumerateNetworkConnections() + { + return EnumerateNetworkConnectionsCore(null); + } + + + + + /// [AlphaFS] Returns an enumerable collection of defined network connections on the local host. + /// A that specifies the network connection ID. + /// An collection of network connection ID's on the local host. + [SecurityCritical] + internal static IEnumerable EnumerateNetworkConnectionsCore(Guid? networkConnectionID) + { + if (null != networkConnectionID) + yield return new NetworkConnectionInfo(Manager.GetNetworkConnection((Guid) networkConnectionID)); + + else + { + foreach (INetworkConnection networkConnection in Manager.GetNetworkConnections()) + + yield return new NetworkConnectionInfo(networkConnection); + } + } + } +} diff --git a/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs b/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs index 208e59e21..ecd7760b6 100644 --- a/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs +++ b/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs @@ -19,51 +19,51 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Filesystem; using System; using System.Collections.Generic; -using System.Net.NetworkInformation; using System.Security; namespace Alphaleonis.Win32.Network { partial class Host { - /// Enumerates drives from the local host. - /// drives from the local host. - /// + /// [AlphaFS] Returns an enumerable collection of networks available on the local host. + /// An collection of connected and disconnected networks on the local host. [SecurityCritical] - public static IEnumerable EnumerateNetworks() + public static IEnumerable EnumerateNetworks() { - return EnumerateNetworksCore(NetworkConnectivityLevels.All); + return EnumerateNetworksCore(null, NetworkConnectivityLevels.All); } - /// Enumerates drives from the local host. - /// drives from the local host. - /// + /// [AlphaFS] Returns an enumerable collection of networks available on the local host. + /// An collection of networks on the local host, as specified by . + /// The that specify the connectivity level of the returned instances. [SecurityCritical] - public static IEnumerable EnumerateNetworks(NetworkConnectivityLevels networkConnectivityLevels) + public static IEnumerable EnumerateNetworks(NetworkConnectivityLevels networkConnectivityLevels) { - return EnumerateNetworksCore(networkConnectivityLevels); + return EnumerateNetworksCore(null, networkConnectivityLevels); } - /// Enumerates local drives from the specified host. - /// drives from the specified host. - /// - /// - /// The DNS or NetBIOS name of the remote server. refers to the local host. - /// - /// suppress any Exception that might be thrown as a result from a failure, - /// such as unavailable resources. - /// + + + /// [AlphaFS] Returns an enumerable collection of networks available on the local host. + /// An collection of networks on the local host, as specified by . + /// The that defines a network. + /// The that specify the connectivity level of the returned instances. [SecurityCritical] - private static IEnumerable EnumerateNetworksCore(NetworkConnectivityLevels networkConnectivityLevels) + internal static IEnumerable EnumerateNetworksCore(Guid? networkID, NetworkConnectivityLevels networkConnectivityLevels) { - foreach (var network in NetworkListManager.GetNetworks(networkConnectivityLevels)) + if (null != networkID) + yield return new NetworkInfo(Manager.GetNetwork((Guid) networkID)); + + else + { + foreach (INetwork network in Manager.GetNetworks(networkConnectivityLevels)) - yield return network; + yield return new NetworkInfo(network); + } } } } diff --git a/AlphaFS/Network/NLM/NetworkCollection.cs b/AlphaFS/Network/Host Class/Host.GetNetwork.cs similarity index 50% rename from AlphaFS/Network/NLM/NetworkCollection.cs rename to AlphaFS/Network/Host Class/Host.GetNetwork.cs index b98901d9f..5b89f9464 100644 --- a/AlphaFS/Network/NLM/NetworkCollection.cs +++ b/AlphaFS/Network/Host Class/Host.GetNetwork.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -19,40 +19,25 @@ * THE SOFTWARE. */ -using System.Collections; -using System.Collections.Generic; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Security; namespace Alphaleonis.Win32.Network { - /// An enumerable collection of objects. - public class NetworkCollection : IEnumerable + partial class Host { - private readonly IEnumerable _networkEnumerable; - - - internal NetworkCollection(IEnumerable networkEnumerable) - { - _networkEnumerable = networkEnumerable; - } - - - /// Returns the strongly typed enumerator for this collection. - /// An object. - public IEnumerator GetEnumerator() - { - foreach (INetwork network in _networkEnumerable) - - yield return new Network(network); - } - - - /// Returns the enumerator for this collection. - ///An object. - IEnumerator IEnumerable.GetEnumerator() + /// [AlphaFS] Rretrieves a network based on a supplied network ID from the local host. + /// A instance from the local host, as specified by . + /// The that defines a network. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] + [SecurityCritical] + public static NetworkInfo GetNetwork(Guid networkID) { - foreach (INetwork network in _networkEnumerable) + var network = EnumerateNetworksCore(networkID, NetworkConnectivityLevels.None); - yield return new Network(network); + return null != network ? network.ToArray()[0] : null; } } -} \ No newline at end of file +} diff --git a/AlphaFS/Network/Host Class/Host.GetNetworkConnection.cs b/AlphaFS/Network/Host Class/Host.GetNetworkConnection.cs new file mode 100644 index 000000000..152030cfe --- /dev/null +++ b/AlphaFS/Network/Host Class/Host.GetNetworkConnection.cs @@ -0,0 +1,43 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Network +{ + public partial class Host + { + /// [AlphaFS] Retrieves a network based on a specified network connection ID. + /// A that specifies the network connection ID. + /// A instance that represents the network connection ID. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] + [SecurityCritical] + public static NetworkConnectionInfo GetNetworkConnection(Guid networkConnectionID) + { + var networkConnection = EnumerateNetworkConnectionsCore(networkConnectionID); + + return null != networkConnection ? networkConnection.ToArray()[0] : null; + } + } +} diff --git a/AlphaFS/Network/Host Class/Host.GetUncName.cs b/AlphaFS/Network/Host Class/Host.GetUncName.cs new file mode 100644 index 000000000..649064c9f --- /dev/null +++ b/AlphaFS/Network/Host Class/Host.GetUncName.cs @@ -0,0 +1,55 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace Alphaleonis.Win32.Network +{ + /// Provides static methods to retrieve network resource information from a local- or remote host. + public static partial class Host + { + /// Return the host name in UNC format, for example: \\hostname + /// The host UNC name. + [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] + [SecurityCritical] + public static string GetUncName() + { + return string.Format(CultureInfo.InvariantCulture, "{0}{1}", Filesystem.Path.UncPrefix, Environment.MachineName); + } + + + /// Return the host name in UNC format, for example: \\hostname + /// Name of the computer. + /// The host UNC name. + [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] + [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] + [SecurityCritical] + public static string GetUncName(string computerName) + { + return Utils.IsNullOrWhiteSpace(computerName) + ? GetUncName() + : (computerName.StartsWith(Filesystem.Path.UncPrefix, StringComparison.Ordinal) ? computerName.Trim() : Filesystem.Path.UncPrefix + computerName.Trim()); + } + } +} diff --git a/AlphaFS/Network/Host Class/Host.cs b/AlphaFS/Network/Host Class/Host.cs index d0098e04b..98652b5bf 100644 --- a/AlphaFS/Network/Host Class/Host.cs +++ b/AlphaFS/Network/Host Class/Host.cs @@ -19,54 +19,23 @@ * 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 Path = Alphaleonis.Win32.Filesystem.Path; +using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network { /// Provides static methods to retrieve network resource information from a local- or remote host. public static partial class Host { - #region GetUncName - - /// Return the host name in UNC format, for example: \\hostname - /// The unc name. - [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] - [SecurityCritical] - public static string GetUncName() - { - return string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.UncPrefix, Environment.MachineName); - } - - /// Return the host name in UNC format, for example: \\hostname - /// Name of the computer. - /// The unc name. - [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] - [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] - [SecurityCritical] - public static string GetUncName(string computerName) - { - return Utils.IsNullOrWhiteSpace(computerName) - ? GetUncName() - : (computerName.StartsWith(Path.UncPrefix, StringComparison.Ordinal) - ? computerName.Trim() - : Path.UncPrefix + computerName.Trim()); - } - - #endregion // GetUncName + private static readonly NetworkListManager Manager = new NetworkListManager(); - #region Internal Methods - private 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); @@ -80,6 +49,44 @@ private struct FunctionData } + internal struct ConnectDisconnectArguments + { + /// Handle to a window that the provider of network resources can use as an owner window for dialog boxes. + public IntPtr WinOwner; + + /// The name of a local device to be redirected, such as "F:". When is or string.Empty, the last available drive letter will be used. Letters are assigned beginning with Z:, then Y: and so on. + public string LocalName; + + /// A network resource to connect to/disconnect from, for example: \\server or \\server\share. The string can be up to characters in length. + public string RemoteName; + + /// A instance. Use either this or the combination of and . + public NetworkCredential Credential; + + /// The user name for making the connection. If is , the function uses the default user name. (The user context for the process provides the default user name) + public string UserName; + + /// The password to be used for making the network connection. If is , the function uses the current default password associated with the user specified by . + public string Password; + + /// always pops-up an authentication dialog box. + public bool Prompt; + + /// successful network resource connections will be saved. + public bool UpdateProfile; + + /// When the operating system prompts for a credential, the credential should be saved by the credential manager when true. + public bool SaveCredentials; + + /// indicates that the operation concerns a drive mapping. + public bool IsDeviceMap; + + /// indicates that the operation needs to disconnect from the network resource, otherwise connect. + public bool IsDisconnect; + } + + + /// Used to enumerate network resources. [SecurityCritical] private static IEnumerable EnumerateNetworkObjectCore(FunctionData functionData, Func createTStruct, EnumerateNetworkObjectDelegate enumerateNetworkObject, bool continueOnException) { @@ -157,7 +164,7 @@ internal static NativeMethods.REMOTE_NAME_INFO GetRemoteNameInfoCore(string path throw new ArgumentNullException("path"); - path = Path.GetRegularPathCore(path, GetFullPathOptions.CheckInvalidPathChars, false); + path = Filesystem.Path.GetRegularPathCore(path, GetFullPathOptions.CheckInvalidPathChars, false); uint lastError; @@ -186,44 +193,5 @@ internal static NativeMethods.REMOTE_NAME_INFO GetRemoteNameInfoCore(string path // Return an empty structure (all fields set to null). return new NativeMethods.REMOTE_NAME_INFO(); } - - - internal struct ConnectDisconnectArguments - { - /// Handle to a window that the provider of network resources can use as an owner window for dialog boxes. - public IntPtr WinOwner; - - /// The name of a local device to be redirected, such as "F:". When is or string.Empty, the last available drive letter will be used. Letters are assigned beginning with Z:, then Y: and so on. - public string LocalName; - - /// A network resource to connect to/disconnect from, for example: \\server or \\server\share. The string can be up to characters in length. - public string RemoteName; - - /// A instance. Use either this or the combination of and . - public NetworkCredential Credential; - - /// The user name for making the connection. If is , the function uses the default user name. (The user context for the process provides the default user name) - public string UserName; - - /// The password to be used for making the network connection. If is , the function uses the current default password associated with the user specified by . - public string Password; - - /// always pops-up an authentication dialog box. - public bool Prompt; - - /// successful network resource connections will be saved. - public bool UpdateProfile; - - /// When the operating system prompts for a credential, the credential should be saved by the credential manager when true. - public bool SaveCredentials; - - /// indicates that the operation concerns a drive mapping. - public bool IsDeviceMap; - - /// indicates that the operation needs to disconnect from the network resource, otherwise connect. - public bool IsDisconnect; - } - - #endregion // Internal Methods } } diff --git a/AlphaFS/Network/NLM/NetworkConnection.cs b/AlphaFS/Network/NLM/NetworkConnection.cs deleted file mode 100644 index 47bd8afb1..000000000 --- a/AlphaFS/Network/NLM/NetworkConnection.cs +++ /dev/null @@ -1,95 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 -{ - /// Represents a connection to a network. - /// A collection containing instances of this class is obtained by calling - /// the property. - public class NetworkConnection - { - private readonly INetworkConnection _networkConnection; - - - internal NetworkConnection(INetworkConnection networkConnection) - { - _networkConnection = networkConnection; - } - - - /// Retrieves an object that represents the network associated with this connection. - /// A object. - public Network Network - { - get { return new Network(_networkConnection.GetNetwork()); } - } - - - /// Gets the adapter identifier for this connection. - /// A object. - public Guid AdapterId - { - get { return _networkConnection.GetAdapterId(); } - } - - - /// Gets the unique identifier for this connection. - /// A object. - public Guid ConnectionId - { - get { return _networkConnection.GetConnectionId(); } - } - - - /// Gets a value that indicates the connectivity of this connection. - /// A value. - public ConnectivityStates Connectivity - { - get { return _networkConnection.GetConnectivity(); } - } - - - /// 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. - /// A value. - public DomainType DomainType - { - get { return _networkConnection.GetDomainType(); } - } - - - /// Gets a value that indicates whether this connection has Internet access. - /// A value. - public bool IsConnectedToInternet - { - get { return _networkConnection.IsConnectedToInternet; } - } - - - /// Gets a value that indicates whether this connection has network connectivity. - /// A value. - public bool IsConnected - { - get { return _networkConnection.IsConnected; } - } - } -} diff --git a/AlphaFS/Network/NLM/NetworkConnectionCollection.cs b/AlphaFS/Network/NLM/NetworkConnectionCollection.cs deleted file mode 100644 index 26de44add..000000000 --- a/AlphaFS/Network/NLM/NetworkConnectionCollection.cs +++ /dev/null @@ -1,58 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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; -using System.Collections.Generic; - -namespace Alphaleonis.Win32.Network -{ - /// An enumerable collection of objects. - public class NetworkConnectionCollection : IEnumerable - { - private readonly IEnumerable _networkConnectionEnumerable; - - - internal NetworkConnectionCollection(IEnumerable networkConnectionEnumerable) - { - _networkConnectionEnumerable = networkConnectionEnumerable; - } - - - /// Returns the strongly typed enumerator for this collection. - /// A object. - public IEnumerator GetEnumerator() - { - foreach (INetworkConnection networkConnection in _networkConnectionEnumerable) - - yield return new NetworkConnection(networkConnection); - } - - - /// Returns the enumerator for this collection. - ///A object. - IEnumerator IEnumerable.GetEnumerator() - { - foreach (INetworkConnection networkConnection in _networkConnectionEnumerable) - - yield return new NetworkConnection(networkConnection); - } - } -} diff --git a/AlphaFS/Network/NLM/NetworkListManager.cs b/AlphaFS/Network/NLM/NetworkListManager.cs deleted file mode 100644 index 71bb13867..000000000 --- a/AlphaFS/Network/NLM/NetworkListManager.cs +++ /dev/null @@ -1,90 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 -{ - /// Provides access to objects that represent networks and network connections. - public static class NetworkListManager - { - private static readonly NetworkListManagerClass Manager = new NetworkListManagerClass(); - - - /// Retrieves a collection of objects that represent the networks defined for this machine. - /// The that specify the connectivity level of the returned objects. - /// A of objects. - public static NetworkCollection GetNetworks(NetworkConnectivityLevels level) - { - return new NetworkCollection(Manager.GetNetworks(level)); - } - - - /// Retrieves the identified by the specified network identifier. - /// A that specifies the unique identifier for the network. - /// The that represents the network identified by the identifier. - public static Network GetNetwork(Guid networkId) - { - return new Network(Manager.GetNetwork(networkId)); - } - - - /// Retrieves a collection of objects that represent the connections for this machine. - /// A containing the network connections. - public static NetworkConnectionCollection GetNetworkConnections() - { - return new NetworkConnectionCollection(Manager.GetNetworkConnections()); - } - - - /// Retrieves the identified by the specified connection identifier. - /// A that specifies the unique identifier for the network connection. - /// The identified by the specified identifier. - public static NetworkConnection GetNetworkConnection(Guid networkConnectionId) - { - return new NetworkConnection(Manager.GetNetworkConnection(networkConnectionId)); - } - - - /// Gets a value that indicates whether this machine has Internet connectivity. - /// A value. - public static bool IsConnectedToInternet - { - get { return Manager.IsConnectedToInternet; } - } - - - /// Gets a value that indicates whether this machine has network connectivity. - /// A value. - public static bool IsConnected - { - get { return Manager.IsConnected; } - } - - - /// Gets the connectivity state of this machine. - /// A value. - public static ConnectivityStates Connectivity - { - get { return Manager.GetConnectivity(); } - } - } -} \ No newline at end of file diff --git a/AlphaFS/Network/NLM/Interfaces/INetwork.cs b/AlphaFS/Network/Native Methods/NativeMethods.INetwork.cs similarity index 82% rename from AlphaFS/Network/NLM/Interfaces/INetwork.cs rename to AlphaFS/Network/Native Methods/NativeMethods.INetwork.cs index d0c0aca23..e5090f737 100644 --- a/AlphaFS/Network/NLM/Interfaces/INetwork.cs +++ b/AlphaFS/Network/Native Methods/NativeMethods.INetwork.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -33,7 +33,7 @@ internal interface INetwork // Do not change the order of these interface members. - /// Returns the name of the network. + /// The GetName method returns the name of a network. /// Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -42,7 +42,7 @@ internal interface INetwork string GetName(); - /// Sets or renames the network. This change occurs immediately. + /// The SetName method sets or renames a network. /// 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. @@ -53,7 +53,7 @@ internal interface INetwork void SetName([In, MarshalAs(UnmanagedType.BStr)] string szNetworkNewName); - /// Returns a description string for the network. + /// The GetDescription method returns a description string for the network. /// Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -62,7 +62,7 @@ internal interface INetwork string GetDescription(); - /// Sets a new description for the network. + /// The SetDescription method sets or replaces the description for a network. /// 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. @@ -73,7 +73,7 @@ internal interface INetwork void SetDescription([In, MarshalAs(UnmanagedType.BStr)] string szDescription); - /// Returns the unique identifier of a network. + /// The GetNetworkId method returns the unique identifier of a network. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -81,7 +81,7 @@ internal interface INetwork Guid GetNetworkId(); - /// Returns the type of network. + /// The GetDomainType method returns the domain type of a network. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -89,7 +89,7 @@ internal interface INetwork DomainType GetDomainType(); - /// Returns an enumeration of all network connections for a network. + /// 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. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -98,7 +98,7 @@ internal interface INetwork IEnumerable GetNetworkConnections(); - /// Returns the local date and time when the network was created and connected. + /// The GetTimeCreatedAndConnected method returns the local date and time when the network was created and connected. /// Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -106,7 +106,7 @@ internal interface INetwork void GetTimeCreatedAndConnected(out uint pdwLowDateTimeCreated, out uint pdwHighDateTimeCreated, out uint pdwLowDateTimeConnected, out uint pdwHighDateTimeConnected); - /// Specifies if the network has any network connectivity. + /// The IsConnected property specifies if the network has any network connectivity. /// If TRUE, this network is connected; if FALSE, it is not. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -117,7 +117,7 @@ bool IsConnected } - /// Specifies if the network has Internet connectivity. + /// The IsConnectedToInternet property specifies if the network has internet connectivity. /// If TRUE, this network has connectivity to the internet; if FALSE, it does not. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -128,7 +128,7 @@ bool IsConnectedToInternet } - /// Returns the connectivity state of the network. + /// The GetConnectivity method returns the connectivity state of the network. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -136,7 +136,7 @@ bool IsConnectedToInternet ConnectivityStates GetConnectivity(); - /// Returns the category of a network. + /// The GetCategory method returns the category of a network. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -144,11 +144,11 @@ bool IsConnectedToInternet NetworkCategory GetCategory(); - /// Sets the category of a network. Administrative privileges are needed for this API call. + /// 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. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - void SetCategory([In] NetworkCategory NewCategory); + void SetCategory([In] NetworkCategory newCategory); } } diff --git a/AlphaFS/Network/NLM/Interfaces/INetworkConnection.cs b/AlphaFS/Network/Native Methods/NativeMethods.INetworkConnection.cs similarity index 82% rename from AlphaFS/Network/NLM/Interfaces/INetworkConnection.cs rename to AlphaFS/Network/Native Methods/NativeMethods.INetworkConnection.cs index 54f117b31..a6df7d252 100644 --- a/AlphaFS/Network/NLM/Interfaces/INetworkConnection.cs +++ b/AlphaFS/Network/Native Methods/NativeMethods.INetworkConnection.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -32,7 +32,7 @@ internal interface INetworkConnection // Do not change the order of these interface members. - /// Returns the associated network for the connection. + /// The GetNetwork method returns the network associated with the connection. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -41,7 +41,7 @@ internal interface INetworkConnection INetwork GetNetwork(); - /// Specifies if the network has any network connectivity. + /// The IsConnected property specifies if the associated network connection has network connectivity. /// If TRUE, this network connection has connectivity; if FALSE, it does not. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -52,7 +52,7 @@ bool IsConnected } - /// Specifies if the network has Internet connectivity. + /// The IsConnectedToInternet property specifies if the associated network connection has internet connectivity. /// If TRUE, this network connection has connectivity to the Internet; if FALSE, it does not. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -63,7 +63,7 @@ bool IsConnectedToInternet } - /// Returns the connectivity state of the network. + /// The GetConnectivity method returns the connectivity state of the network connection. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -71,7 +71,7 @@ bool IsConnectedToInternet ConnectivityStates GetConnectivity(); - /// Returns the Connection ID associated with this network connection. + /// The GetConnectionId method returns the Connection ID associated with this network connection. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -79,7 +79,7 @@ bool IsConnectedToInternet Guid GetConnectionId(); - /// Returns the ID of the network adapter used by this connection. There may multiple connections using the same adapter ID. + /// The GetAdapterId method returns the ID of the network adapter used by this connection. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -87,7 +87,7 @@ bool IsConnectedToInternet Guid GetAdapterId(); - /// Returns the type of network connection. + /// The GetDomainType method returns the domain type of the network connection. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] diff --git a/AlphaFS/Network/NLM/Interfaces/INetworkListManager.cs b/AlphaFS/Network/Native Methods/NativeMethods.INetworkListManager.cs similarity index 97% rename from AlphaFS/Network/NLM/Interfaces/INetworkListManager.cs rename to AlphaFS/Network/Native Methods/NativeMethods.INetworkListManager.cs index 4e37b9aab..d14d69acf 100644 --- a/AlphaFS/Network/NLM/Interfaces/INetworkListManager.cs +++ b/AlphaFS/Network/Native Methods/NativeMethods.INetworkListManager.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -42,7 +42,7 @@ internal interface INetworkListManager /// Minimum supported server: Windows Server 2008 [desktop apps only] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [return: MarshalAs(UnmanagedType.Interface)] - IEnumerable GetNetworks([In] NetworkConnectivityLevels Flags); + IEnumerable GetNetworks([In] NetworkConnectivityLevels flags); /// Retrieves a network based on a supplied Network ID. diff --git a/AlphaFS/Network/NetworkConnectionInfo.cs b/AlphaFS/Network/NetworkConnectionInfo.cs new file mode 100644 index 000000000..d83c15b0a --- /dev/null +++ b/AlphaFS/Network/NetworkConnectionInfo.cs @@ -0,0 +1,150 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Net.NetworkInformation; +using System.Runtime.Remoting.Messaging; + +namespace Alphaleonis.Win32.Network +{ + /// Represents a connection to a network. + public class NetworkConnectionInfo + { + #region Private Fields + + private readonly INetworkConnection _networkConnection; + private string _adapterDescription = string.Empty; + + #endregion // Private Fields + + + #region Constructors + + internal NetworkConnectionInfo(INetworkConnection networkConnection) + { + _networkConnection = networkConnection; + } + + #endregion // Constructors + + + #region Properties + + /// Gets the adapter identifier for this connection. This value of this property is not cached. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] + public Guid AdapterID + { + get { return _networkConnection.GetAdapterId(); } + } + + + /// Gets the name of the adapter that points to. This value of this property is not cached. + public string AdapterName + { + get + { + var nicName = string.Empty; + + foreach (var nic in NetworkInterface.GetAllNetworkInterfaces()) + { + Guid guid; + + if (Guid.TryParse(nic.Id, out guid) && Equals(guid, AdapterID)) + { + nicName = nic.Name; + + _adapterDescription = nic.Description; + + break; + } + } + + return nicName; + } + } + + + /// Gets the description of the adapter that points to. This value of this property is not cached. + public string AdapterDescription + { + get + { + if (Utils.IsNullOrWhiteSpace(_adapterDescription)) + { + var unused = AdapterName; + } + + return _adapterDescription; + } + + + set { _adapterDescription = value; } + } + + + /// Gets the unique identifier for this connection. This value of this property is not cached. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] + public Guid ConnectionID + { + get { return _networkConnection.GetConnectionId(); } + } + + + /// Gets a value that indicates the connectivity of this connection. This value of this property is not cached. + public ConnectivityStates Connectivity + { + get { return _networkConnection.GetConnectivity(); } + } + + + /// 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. + public DomainType DomainType + { + get { return _networkConnection.GetDomainType(); } + } + + + /// Gets a value that indicates whether this connection has network connectivity. This value of this property is not cached. + public bool IsConnected + { + get { return _networkConnection.IsConnected; } + } + + + /// Gets a value that indicates whether this connection has Internet access. This value of this property is not cached. + public bool IsConnectedToInternet + { + get { return _networkConnection.IsConnectedToInternet; } + } + + + /// Retrieves an instance that represents the network associated with this connection. This value of this property is not cached. + /// A instance. + public NetworkInfo NetworkInfo + { + get { return new NetworkInfo(_networkConnection.GetNetwork()); } + } + + #endregion // Properties + } +} diff --git a/AlphaFS/Network/NLM/Network.cs b/AlphaFS/Network/NetworkInfo.cs similarity index 59% rename from AlphaFS/Network/NLM/Network.cs rename to AlphaFS/Network/NetworkInfo.cs index 9b7aa6d38..936759f9b 100644 --- a/AlphaFS/Network/NLM/Network.cs +++ b/AlphaFS/Network/NetworkInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,49 +20,70 @@ */ using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Network { /// Represents a network on the local machine. It can also represent a collection of network connections with a similar network signature. - /// Instances of this class are obtained by calling methods on the class. - public class Network + public class NetworkInfo { + #region Private Fields + private readonly INetwork _network; + #endregion // Private Fields + + + #region Constructors - internal Network(INetwork network) + internal NetworkInfo(INetwork network) { _network = network; } + #endregion // Constructors + + + #region Properties - /// Gets or sets the category of a network. The categories are trusted, untrusted, or authenticated. - /// A value. + /// Gets the category of a network. The categories are trusted, untrusted, or authenticated. This value of this property is not cached. public NetworkCategory Category { get { return _network.GetCategory(); } - set { _network.SetCategory(value); } + // Should we allow this in AlphaFS? + // set { _network.SetCategory(value); } + } + + + /// Gets the network connections for the network. This value of this property is not cached. + public IEnumerable Connections + { + get + { + foreach (var connection in _network.GetNetworkConnections()) + + yield return new NetworkConnectionInfo((INetworkConnection) connection); + } } - /// Gets the local date and time when the network was connected. - /// A object. + /// Gets the local date and time when the network was connected. This value of this property is not cached. public DateTime ConnectionTime { get { return ConnectionTimeUtc.ToLocalTime(); } } - /// Gets the local date and time when the network was connected. - /// A object. + /// Gets the date and time when the network was connected. This value of this property is not cached. public DateTime ConnectionTimeUtc { get { - uint low, high, dummy1, dummy2; + uint low, high, unused1, unused2; - _network.GetTimeCreatedAndConnected(out dummy1, out dummy2, out low, out high); + _network.GetTimeCreatedAndConnected(out unused1, out unused2, out low, out high); long time = high; @@ -75,16 +96,7 @@ public DateTime ConnectionTimeUtc } - /// Gets the network connections for the network. - /// A object. - public NetworkConnectionCollection Connections - { - get { return new NetworkConnectionCollection(_network.GetNetworkConnections()); } - } - - - /// Gets the connectivity state of the network. - /// A value. + /// Gets the connectivity state of the network. This value of this property is not cached. /// Connectivity provides information on whether the network is connected, and the protocols in use for network traffic. public ConnectivityStates Connectivity { @@ -92,23 +104,21 @@ public ConnectivityStates Connectivity } - /// Gets the local date and time when the network was created. - /// A object. + /// Gets the local date and time when the network was created. This value of this property is not cached. public DateTime CreationTime { get { return CreationTimeUtc.ToLocalTime(); } } - /// Gets the local date and time when the network was created. - /// A object. + /// Gets the date and time when the network was created. This value of this property is not cached. public DateTime CreationTimeUtc { get { - uint low, high, dummy1, dummy2; + uint low, high, unused1, unused2; - _network.GetTimeCreatedAndConnected(out low, out high, out dummy1, out dummy2); + _network.GetTimeCreatedAndConnected(out low, out high, out unused1, out unused2); long time = high; @@ -121,18 +131,17 @@ public DateTime CreationTimeUtc } - /// Gets a description for the network. - /// A value. + /// Gets a description for the network. This value of this property is not cached. public string Description { get { return _network.GetDescription(); } - //set { _network.SetDescription(value); } + // Should we allow this in AlphaFS? + //private set { _network.SetDescription(value); } } - /// Gets the domain type of the network. - /// A value. + /// Gets the domain type of the network. This value of this property is not cached. /// The domain indictates whether the network is an Active Directory Network, and whether the machine has been authenticated by Active Directory. public DomainType DomainType { @@ -140,37 +149,37 @@ public DomainType DomainType } - /// Gets a value that indicates whether there is network connectivity. - /// A value. + /// Gets a value that indicates whether there is network connectivity. This value of this property is not cached. public bool IsConnected { get { return _network.IsConnected; } } - /// Gets a value that indicates whether there is Internet connectivity. - /// A value. + /// Gets a value that indicates whether there is Internet connectivity. This value of this property is not cached. public bool IsConnectedToInternet { get { return _network.IsConnectedToInternet; } } - /// Gets the name of the network. - /// A value. + /// Gets the name of the network. This value of this property is not cached. public string Name { get { return _network.GetName(); } - //set { _network.SetName(value); } + // Should we allow this in AlphaFS? + //private set { _network.SetName(value); } } - /// Gets a unique identifier for the network. - /// A value. - public Guid NetworkId + /// Gets a unique identifier for the network. This value of this property is not cached. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] + public Guid NetworkID { get { return _network.GetNetworkId(); } } + + #endregion // Properties } } diff --git a/AlphaFS/Network/NLM/NetworkListManagerClass.cs b/AlphaFS/Network/NetworkListManager.cs similarity index 83% rename from AlphaFS/Network/NLM/NetworkListManagerClass.cs rename to AlphaFS/Network/NetworkListManager.cs index cd5a6ac9f..b19a5eba6 100644 --- a/AlphaFS/Network/NLM/NetworkListManagerClass.cs +++ b/AlphaFS/Network/NetworkListManager.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,12 +26,12 @@ namespace Alphaleonis.Win32.Network { - /// The NetworkListManagerClass class provides a set of methods to perform network list read-only management functions. + /// The NetworkListManager class provides a set of methods to perform network list management functions. [ComImport, ClassInterface((short) 0), Guid("DCB00C01-570F-4A9B-8D69-199FDBA5723B")] [ComSourceInterfaces("Microsoft.Windows.NetworkList.Internal.INetworkEvents\0Microsoft.Windows.NetworkList.Internal.INetworkConnectionEvents\0Microsoft.Windows.NetworkList.Internal.INetworkListManagerEvents\0"), TypeLibType(2)] - internal class NetworkListManagerClass : INetworkListManager + internal sealed class NetworkListManager : INetworkListManager { - /// Returns the connectivity state of all the networks on a machine. + /// The GetConnectivity method returns the overall connectivity state of the machine. /// Returns S_OK if the method succeeds. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -39,7 +39,7 @@ internal class NetworkListManagerClass : INetworkListManager public extern ConnectivityStates GetConnectivity(); - /// Retrieves a network based on a supplied Network ID. + /// The GetNetwork method retrieves a network based on a supplied network ID. /// 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. @@ -51,7 +51,7 @@ internal class NetworkListManagerClass : INetworkListManager public extern INetwork GetNetwork([In] Guid gdNetworkId); - /// Retrieves a network based on a supplied Network Connection ID. + /// The GetNetworkConnection method retrieves a network based on a supplied Network Connection ID. /// 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. @@ -64,7 +64,7 @@ internal class NetworkListManagerClass : INetworkListManager public extern INetworkConnection GetNetworkConnection([In] Guid gdNetworkConnectionId); - /// Gets an enumerator that contains a complete list of the network connections that have been made. + /// The GetNetworkConnections method enumerates a complete list of the network connections that have been made. /// Returns S_OK if the method succeeds. Otherwise, the method returns one of the following values: E_POINTER: The pointer passed is NULL. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] @@ -73,7 +73,7 @@ internal class NetworkListManagerClass : INetworkListManager public extern IEnumerable GetNetworkConnections(); - /// Retrieves networks based on the supplied Network IDs. + /// The GetNetworks method retrieves the list of networks available on the local machine. /// 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. @@ -82,10 +82,10 @@ internal class NetworkListManagerClass : INetworkListManager /// Minimum supported server: Windows Server 2008 [desktop apps only] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(1)] [return: MarshalAs(UnmanagedType.Interface)] - public extern IEnumerable GetNetworks([In] NetworkConnectivityLevels Flags); + public extern IEnumerable GetNetworks([In] NetworkConnectivityLevels flags); - /// Specifies if the machine has network connectivity. + /// The IsConnected property specifies if the local machine has network connectivity. /// /// 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. @@ -100,7 +100,7 @@ public extern bool IsConnected } - /// Specifies if the machine has Internet connectivity. + /// The IsConnectedToInternet property specifies if the local machine has internet connectivity. /// If TRUE, the local machine is connected to the internet; if FALSE, it is not. /// Minimum supported client: Windows Vista [desktop apps only] /// Minimum supported server: Windows Server 2008 [desktop apps only] From 3fc1888a583d2d8f8f6a049d2d55899067ec567d Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 7 Feb 2018 12:02:24 +0100 Subject: [PATCH 027/133] -Fixed NetworkConnectionInfo for .NET 3.5 build; -Removed unused references; --- .../AlphaFS_Directory_GetFileSystemEntryInfo.cs | 1 - .../AlphaFS.Volume.SetVolumeLabel.cs | 1 - AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 - AlphaFS.UnitTest/Directory Class/DirectoryTest.cs | 2 -- .../Directory Class/Directory_Exists.cs | 3 --- AlphaFS/AlphaFS.csproj | 4 ++-- AlphaFS/Device/Device.EnumeratePhysicalDrives.cs | 1 - AlphaFS/Device/Device.cs | 1 - .../Device/DriveInfo/DriveInfo.GetDeviceInfo.cs | 1 - .../Directory Class/Directory.GetLogicalDrives.cs | 1 - .../NativeMethods.DeviceManagement.cs | 1 - AlphaFS/Filesystem/Native Other/IoMethod.cs | 2 -- .../Path Class/Path.ValidationAndChecks.cs | 1 - .../NativeMethods.NetworkListManager.cs} | 0 AlphaFS/Network/NetworkConnectionInfo.cs | 15 +++++++++++---- 15 files changed, 13 insertions(+), 22 deletions(-) rename AlphaFS/Network/{NetworkListManager.cs => Native Methods/NativeMethods.NetworkListManager.cs} (100%) diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_GetFileSystemEntryInfo.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_GetFileSystemEntryInfo.cs index 5cb5c162c..0dad7880c 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_GetFileSystemEntryInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory_GetFileSystemEntryInfo.cs @@ -21,7 +21,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Linq; namespace AlphaFS.UnitTest { diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs index 23c58c970..677d00711 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.SetVolumeLabel.cs @@ -21,7 +21,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Reflection; namespace AlphaFS.UnitTest { diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 1f4366699..3614396fb 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -167,7 +167,6 @@ - diff --git a/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs b/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs index 93184c83e..66a489034 100644 --- a/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs +++ b/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs @@ -26,9 +26,7 @@ using System.Linq; using System.Reflection; using System.Security.Principal; -using Alphaleonis; using Directory = Alphaleonis.Win32.Filesystem.Directory; -using DriveInfo = Alphaleonis.Win32.Filesystem.DriveInfo; using File = Alphaleonis.Win32.Filesystem.File; using Path = Alphaleonis.Win32.Filesystem.Path; diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Exists.cs b/AlphaFS.UnitTest/Directory Class/Directory_Exists.cs index 43bfeb04d..44bf61e2e 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Exists.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Exists.cs @@ -59,9 +59,6 @@ public void Directory_Exists_DriveLetter_LocalAndNetwork_Success() [TestMethod] public void Directory_Exists_UseCases_LocalAndNetwork_Success() { - if (!UnitTestConstants.IsAdmin()) - Assert.Inconclusive(); - Directory_Exists_UseCases(false); Directory_Exists_UseCases(true); } diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 98706b457..50f3e3815 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -533,7 +533,7 @@ - + @@ -630,7 +630,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs index 9aff32eab..8e649d111 100644 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs @@ -20,7 +20,6 @@ */ using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Linq; using System.Security; diff --git a/AlphaFS/Device/Device.cs b/AlphaFS/Device/Device.cs index 59d360962..3bff779e2 100644 --- a/AlphaFS/Device/Device.cs +++ b/AlphaFS/Device/Device.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System; using System.Globalization; using System.Runtime.InteropServices; using System.Security; diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs index ef47f998c..c21e8484a 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs @@ -21,7 +21,6 @@ using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs index e7dc16a23..d26acca10 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System; using System.Linq; using System.Security; diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs index c42157d6d..d0241e989 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs @@ -23,7 +23,6 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; -using System.Threading; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem diff --git a/AlphaFS/Filesystem/Native Other/IoMethod.cs b/AlphaFS/Filesystem/Native Other/IoMethod.cs index 8849c6a64..95f28fe91 100644 --- a/AlphaFS/Filesystem/Native Other/IoMethod.cs +++ b/AlphaFS/Filesystem/Native Other/IoMethod.cs @@ -19,8 +19,6 @@ * THE SOFTWARE. */ -using System; - namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods diff --git a/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs b/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs index 3e63610e0..228018ed9 100644 --- a/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs +++ b/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs @@ -23,7 +23,6 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; -using System.Linq; using System.Security; using System.Text; diff --git a/AlphaFS/Network/NetworkListManager.cs b/AlphaFS/Network/Native Methods/NativeMethods.NetworkListManager.cs similarity index 100% rename from AlphaFS/Network/NetworkListManager.cs rename to AlphaFS/Network/Native Methods/NativeMethods.NetworkListManager.cs diff --git a/AlphaFS/Network/NetworkConnectionInfo.cs b/AlphaFS/Network/NetworkConnectionInfo.cs index d83c15b0a..87bb2dd34 100644 --- a/AlphaFS/Network/NetworkConnectionInfo.cs +++ b/AlphaFS/Network/NetworkConnectionInfo.cs @@ -21,9 +21,7 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Net.NetworkInformation; -using System.Runtime.Remoting.Messaging; namespace Alphaleonis.Win32.Network { @@ -64,12 +62,21 @@ public string AdapterName get { var nicName = string.Empty; + Guid guid; + + var adapterID = AdapterID; foreach (var nic in NetworkInterface.GetAllNetworkInterfaces()) { - Guid guid; +#if NET35 + guid = new Guid(nic.Id); + +#else + if (!Guid.TryParse(nic.Id, out guid)) + continue; +#endif - if (Guid.TryParse(nic.Id, out guid) && Equals(guid, AdapterID)) + if (Equals(adapterID, guid)) { nicName = nic.Name; From bfc904137d65264d9ad7d9a718edb1b3071ebf82 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 7 Feb 2018 12:36:28 +0100 Subject: [PATCH 028/133] -Fixed NetworkConnectionInfo for .NET 3.5 build; -Fixed broken unit test; --- ...merateFiles_UsingDirectoryEnumerationFilters.cs | 2 +- AlphaFS/Network/NetworkConnectionInfo.cs | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs index 954b96cfd..3d63c052b 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs @@ -123,7 +123,7 @@ private void Test_DirectoryEnumerationFilters(string inputPath) }, - Filter to in-/exclude file system entries during the enumeration. + // Filter to in-/exclude file system entries during the enumeration. InclusionFilter = fsei => { if (abortEnumeration) diff --git a/AlphaFS/Network/NetworkConnectionInfo.cs b/AlphaFS/Network/NetworkConnectionInfo.cs index d83c15b0a..00d2aa014 100644 --- a/AlphaFS/Network/NetworkConnectionInfo.cs +++ b/AlphaFS/Network/NetworkConnectionInfo.cs @@ -64,12 +64,21 @@ public string AdapterName get { var nicName = string.Empty; + Guid guid; + + var adapterID = AdapterID; foreach (var nic in NetworkInterface.GetAllNetworkInterfaces()) { - Guid guid; +#if NET35 + guid = new Guid(nic.Id); + +#else + if (!Guid.TryParse(nic.Id, out guid)) + continue; +#endif - if (Guid.TryParse(nic.Id, out guid) && Equals(guid, AdapterID)) + if (Equals(adapterID, guid)) { nicName = nic.Name; @@ -85,6 +94,7 @@ public string AdapterName /// Gets the description of the adapter that points to. This value of this property is not cached. + [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "unused")] public string AdapterDescription { get From 54365b73a5dab604ec40928d0090cce457df4cbc Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 7 Feb 2018 13:29:13 +0100 Subject: [PATCH 029/133] Replace properties AdapterID, AdapterName and AdapterDescription with NetworkInterface property. --- ...lphaFS_Host.EnumerateNetworkConnections.cs | 2 + .../AlphaFS_Host.EnumerateNetworks.cs | 4 + AlphaFS/Network/NetworkConnectionInfo.cs | 92 ++++++------------- 3 files changed, 35 insertions(+), 63 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs index 3c23d6862..ad0c299ee 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs @@ -45,6 +45,8 @@ public void AlphaFS_Host_EnumerateNetworkConnections_Local_Success() UnitTestConstants.Dump(networkConnection.NetworkInfo, -21, true); + UnitTestConstants.Dump(networkConnection.NetworkInterface, -20, true); + Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs index 2b64d9d49..55b07812c 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs @@ -47,7 +47,11 @@ public void AlphaFS_Host_EnumerateNetworks_Local_Success() if (null != network.Connections) { foreach (var connection in network.Connections) + { UnitTestConstants.Dump(connection, -21, true); + + UnitTestConstants.Dump(connection.NetworkInterface, -20, true); + } } diff --git a/AlphaFS/Network/NetworkConnectionInfo.cs b/AlphaFS/Network/NetworkConnectionInfo.cs index 00d2aa014..abbf8af24 100644 --- a/AlphaFS/Network/NetworkConnectionInfo.cs +++ b/AlphaFS/Network/NetworkConnectionInfo.cs @@ -33,7 +33,6 @@ public class NetworkConnectionInfo #region Private Fields private readonly INetworkConnection _networkConnection; - private string _adapterDescription = string.Empty; #endregion // Private Fields @@ -49,68 +48,6 @@ internal NetworkConnectionInfo(INetworkConnection networkConnection) #region Properties - - /// Gets the adapter identifier for this connection. This value of this property is not cached. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] - public Guid AdapterID - { - get { return _networkConnection.GetAdapterId(); } - } - - - /// Gets the name of the adapter that points to. This value of this property is not cached. - public string AdapterName - { - get - { - var nicName = string.Empty; - Guid guid; - - var adapterID = AdapterID; - - 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)) - { - nicName = nic.Name; - - _adapterDescription = nic.Description; - - break; - } - } - - return nicName; - } - } - - - /// Gets the description of the adapter that points to. This value of this property is not cached. - [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "unused")] - public string AdapterDescription - { - get - { - if (Utils.IsNullOrWhiteSpace(_adapterDescription)) - { - var unused = AdapterName; - } - - return _adapterDescription; - } - - - set { _adapterDescription = value; } - } - /// Gets the unique identifier for this connection. This value of this property is not cached. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] @@ -155,6 +92,35 @@ public NetworkInfo NetworkInfo get { return new NetworkInfo(_networkConnection.GetNetwork()); } } + + /// Gets the network interface for this connection. This value of this property is not cached. + 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 (adapterID.Equals(guid)) + return nic; + } + + + return null; + } + } + #endregion // Properties } } From bcc103f700ff68fa960ed00de51c5c3c1257b246 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 9 Feb 2018 11:23:35 +0100 Subject: [PATCH 030/133] NetStatistics --- AlphaFS/AlphaFS.csproj | 6 +- .../Host Class/Host.SMB.GetNetStatistics.cs | 57 +++++++ AlphaFS/Network/Native Other/STAT_SERVER_0.cs | 92 ++++++++++ .../Native Other/STAT_WORKSTATION_0.cs | 160 ++++++++++++++++++ AlphaFS/Network/OpenConnectionInfo.cs | 4 +- AlphaFS/Network/ServerStatisticsInfo.cs | 123 ++++++++++++++ 6 files changed, 439 insertions(+), 3 deletions(-) create mode 100644 AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs create mode 100644 AlphaFS/Network/Native Other/STAT_SERVER_0.cs create mode 100644 AlphaFS/Network/Native Other/STAT_WORKSTATION_0.cs create mode 100644 AlphaFS/Network/ServerStatisticsInfo.cs diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 0df6034de..dc1c42df4 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -492,6 +492,7 @@ + @@ -508,7 +509,10 @@ + + + @@ -598,7 +602,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs new file mode 100644 index 000000000..319ce90f2 --- /dev/null +++ b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs @@ -0,0 +1,57 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + partial class Host + { + [SecurityCritical] + public static ServerStatisticsInfo GetServerNetStatistics(string hostName) + { + return GetNetStatisticsCore(true, hostName); + } + + + [SecurityCritical] + public static ServerStatisticsInfo GetWorkstationNetStatistics(string hostName) + { + return GetNetStatisticsCore(false, hostName); + } + + + + [SecurityCritical] + internal static ServerStatisticsInfo GetNetStatisticsCore(bool isServer, string hostName) + { + if (Utils.IsNullOrWhiteSpace(hostName)) + throw new ArgumentNullException("hostName"); + + + return null; + } + } +} diff --git a/AlphaFS/Network/Native Other/STAT_SERVER_0.cs b/AlphaFS/Network/Native Other/STAT_SERVER_0.cs new file mode 100644 index 000000000..075fbaf92 --- /dev/null +++ b/AlphaFS/Network/Native Other/STAT_SERVER_0.cs @@ -0,0 +1,92 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Contains statistical information about the server. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct STAT_SERVER_0 + { + /// + /// Specifies a DWORD value that indicates the time when statistics collection started (or when the statistics were last cleared). + /// The value is stored as the number of seconds that have elapsed since 00:00:00, January 1, 1970, GMT. To calculate the length of time that statistics have been collected, + /// subtract the value of this member from the present time. + /// + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_start; + + /// 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. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_fopens; + + /// Specifies a DWORD value that indicates the number of times a server device is opened. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_devopens; + + /// Specifies a DWORD value that indicates the number of server print jobs spooled. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_jobsqueued; + + /// Specifies a DWORD value that indicates the number of times the server session started. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_sopens; + + /// Specifies a DWORD value that indicates the number of times the server session automatically disconnected. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_stimedout; + + /// Specifies a DWORD value that indicates the number of times the server sessions failed with an error. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_serrorout; + + /// Specifies a DWORD value that indicates the number of server password violations. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_pwerrors; + + /// Specifies a DWORD value that indicates the number of server access permission errors. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_permerrors; + + /// Specifies a DWORD value that indicates the number of server system errors. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_syserrors; + + /// Specifies the low-order DWORD of the number of server bytes sent to the network. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_bytessent_low; + + /// Specifies the high-order DWORD of the number of server bytes sent to the network. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_bytessent_high; + + /// Specifies the low-order DWORD of the number of server bytes received from the network. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_bytesrcvd_low; + + /// Specifies the high-order DWORD of the number of server bytes received from the network. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_bytesrcvd_high; + + /// Specifies a DWORD value that indicates the average server response time (in milliseconds). + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_avresponse; + + /// 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. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_reqbufneed; + + /// 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. + [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_bigbufneed; + } + } +} diff --git a/AlphaFS/Network/Native Other/STAT_WORKSTATION_0.cs b/AlphaFS/Network/Native Other/STAT_WORKSTATION_0.cs new file mode 100644 index 000000000..eca9fc315 --- /dev/null +++ b/AlphaFS/Network/Native Other/STAT_WORKSTATION_0.cs @@ -0,0 +1,160 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Contains statistical information about the specified workstation. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct STAT_WORKSTATION_0 + { + /// + /// Specifies the time statistics collection started. This member also indicates when statistics for the workstations were last cleared. + /// The value is stored as the number of seconds elapsed since 00:00:00, January 1, 1970. + /// + [MarshalAs(UnmanagedType.U8)] public readonly long StatisticsStartTime; + + /// Specifies the total number of bytes received by the workstation. + [MarshalAs(UnmanagedType.U8)] public readonly long BytesReceived; + + /// Specifies the total number of server message blocks (SMBs) received by the workstation. + [MarshalAs(UnmanagedType.U8)] public readonly long SmbsReceived; + + /// Specifies the total number of bytes that have been read by paging I/O requests. + [MarshalAs(UnmanagedType.U8)] public readonly long PagingReadBytesRequested; + + /// Specifies the total number of bytes that have been read by non-paging I/O requests. + [MarshalAs(UnmanagedType.U8)] public readonly long NonPagingReadBytesRequested; + + /// Specifies the total number of bytes that have been read by cache I/O requests. + [MarshalAs(UnmanagedType.U8)] public readonly long CacheReadBytesRequested; + + /// Specifies the total amount of bytes that have been read by disk I/O requests. + [MarshalAs(UnmanagedType.U8)] public readonly long NetworkReadBytesRequested; + + /// Specifies the total number of bytes transmitted by the workstation. + [MarshalAs(UnmanagedType.U8)] public readonly long BytesTransmitted; + + /// Specifies the total number of SMBs transmitted by the workstation. + [MarshalAs(UnmanagedType.U8)] public readonly long SmbsTransmitted; + + /// Specifies the total number of bytes that have been written by paging I/O requests. + [MarshalAs(UnmanagedType.U8)] public readonly long PagingWriteBytesRequested; + + /// Specifies the total number of bytes that have been written by non-paging I/O requests. + [MarshalAs(UnmanagedType.U8)] public readonly long NonPagingWriteBytesRequested; + + /// Specifies the total number of bytes that have been written by cache I/O requests. + [MarshalAs(UnmanagedType.U8)] public readonly long CacheWriteBytesRequested; + + /// Specifies the total number of bytes that have been written by disk I/O requests. + [MarshalAs(UnmanagedType.U8)] public readonly long NetworkWriteBytesRequested; + + /// Specifies the total number of network operations that failed to begin. + [MarshalAs(UnmanagedType.U4)] public readonly uint InitiallyFailedOperations; + + /// Specifies the total number of network operations that failed to complete. + [MarshalAs(UnmanagedType.U4)] public readonly uint FailedCompletionOperations; + + /// Specifies the total number of read operations initiated by the workstation. + [MarshalAs(UnmanagedType.U4)] public readonly uint ReadOperations; + + /// Specifies the total number of random access reads initiated by the workstation. + [MarshalAs(UnmanagedType.U4)] public readonly uint RandomReadOperations; + + /// Specifies the total number of read requests the workstation has sent to servers. + [MarshalAs(UnmanagedType.U4)] public readonly uint ReadSmbs; + + /// 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. + [MarshalAs(UnmanagedType.U4)] public readonly uint LargeReadSmbs; + + /// 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. + [MarshalAs(UnmanagedType.U4)] public readonly uint SmallReadSmbs; + + /// Specifies the total number of write operations initiated by the workstation. + [MarshalAs(UnmanagedType.U4)] public readonly uint WriteOperations; + + /// Specifies the total number of random access writes initiated by the workstation. + [MarshalAs(UnmanagedType.U4)] public readonly uint RandomWriteOperations; + + /// Specifies the total number of write requests the workstation has sent to servers. + [MarshalAs(UnmanagedType.U4)] public readonly uint WriteSmbs; + + /// 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. + [MarshalAs(UnmanagedType.U4)] public readonly uint LargeWriteSmbs; + + /// 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. + [MarshalAs(UnmanagedType.U4)] public readonly uint SmallWriteSmbs; + + /// Specifies the total number of raw read requests made by the workstation that have been denied. + [MarshalAs(UnmanagedType.U4)] public readonly uint RawReadsDenied; + + /// Specifies the total number of raw write requests made by the workstation that have been denied. + [MarshalAs(UnmanagedType.U4)] public readonly uint RawWritesDenied; + + /// Specifies the total number of network errors received by the workstation. + [MarshalAs(UnmanagedType.U4)] public readonly uint NetworkErrors; + + /// Specifies the total number of workstation sessions that were established. + [MarshalAs(UnmanagedType.U4)] public readonly uint Sessions; + + /// Specifies the number of times the workstation attempted to create a session but failed. + [MarshalAs(UnmanagedType.U4)] public readonly uint FailedSessions; + + /// Specifies the total number of connections that have failed. + [MarshalAs(UnmanagedType.U4)] public readonly uint Reconnects; + + /// Specifies the total number of connections to servers supporting the PCNET dialect that have succeeded. + [MarshalAs(UnmanagedType.U4)] public readonly uint CoreConnects; + + /// Specifies the total number of connections to servers supporting the LanManager 2.0 dialect that have succeeded. + [MarshalAs(UnmanagedType.U4)] public readonly uint Lanman20Connects; + + /// Specifies the total number of connections to servers supporting the LanManager 2.1 dialect that have succeeded. + [MarshalAs(UnmanagedType.U4)] public readonly uint Lanman21Connects; + + /// Specifies the total number of connections to servers supporting the NTLM dialect that have succeeded. + [MarshalAs(UnmanagedType.U4)] public readonly uint LanmanNtConnects; + + /// Specifies the number of times the workstation was disconnected by a network server. + [MarshalAs(UnmanagedType.U4)] public readonly uint ServerDisconnects; + + /// Specifies the total number of sessions that have expired on the workstation. + [MarshalAs(UnmanagedType.U4)] public readonly uint HungSessions; + + /// Specifies the total number of network connections established by the workstation. + [MarshalAs(UnmanagedType.U4)] public readonly uint UseCount; + + /// Specifies the total number of failed network connections for the workstation. + [MarshalAs(UnmanagedType.U4)] public readonly uint FailedUseCount; + + /// Specifies the number of current requests that have not been completed. + [MarshalAs(UnmanagedType.U4)] public readonly uint CurrentCommands; + } + } +} diff --git a/AlphaFS/Network/OpenConnectionInfo.cs b/AlphaFS/Network/OpenConnectionInfo.cs index d6b552bd4..df3863e7b 100644 --- a/AlphaFS/Network/OpenConnectionInfo.cs +++ b/AlphaFS/Network/OpenConnectionInfo.cs @@ -26,12 +26,12 @@ namespace Alphaleonis.Win32.Network { /// Contains the identification number of a connection, number of open files, connection time, number of users on the connection, and the type of connection. - [SerializableAttribute] + [Serializable] public sealed class OpenConnectionInfo { #region Constructor - /// Create a OpenConnectionInfo instance. + /// Create an OpenConnectionInfo instance. internal OpenConnectionInfo(string host, NativeMethods.CONNECTION_INFO_1 connectionInfo) { Host = host; diff --git a/AlphaFS/Network/ServerStatisticsInfo.cs b/AlphaFS/Network/ServerStatisticsInfo.cs new file mode 100644 index 000000000..138196d14 --- /dev/null +++ b/AlphaFS/Network/ServerStatisticsInfo.cs @@ -0,0 +1,123 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 Alphaleonis.Win32.Filesystem; + +namespace Alphaleonis.Win32.Network +{ + /// Contains the identification number of a connection, number of open files, connection time, number of users on the connection, and the type of connection. + [Serializable] + public sealed class ServerStatisticsInfo + { + #region Constructor + + /// Create a OpenConnectionInfo instance. + internal ServerStatisticsInfo(string hostName, NativeMethods.STAT_SERVER_0 serverStat) + { + var ts = TimeSpan.FromSeconds(serverStat.sts0_start); + + //StartTime = DateTime.Now. + //.DateAdd("s", NumberOfSeconds, "1/1/1970") + + + AverageResponseTime = TimeSpan.FromMilliseconds(serverStat.sts0_avresponse); + } + + #endregion // Constructor + + + #region Properties + + /// The local time when statistics collection started (or when the statistics were last cleared). + public DateTime StartTime + { + get { return StartTime.ToLocalTime(); } + } + + /// The time when statistics collection started (or when the statistics were last cleared). + public DateTime StartTimeUtc { get; set; } + + + /// The number of times a file is opened on a server. This includes the number of times named pipes are opened. + public int sts0_fopens { get; set; } + + /// The number of times a server device is opened. + public int sts0_devopens { get; set; } + + /// The number of server print jobs spooled. + public int JobsQueued { get; set; } + + /// The number of times the server session started. + public int sts0_sopens { get; set; } + + /// The number of times the server session automatically disconnected. + public int sts0_stimedout { get; set; } + + /// The number of times the server sessions failed with an error. + public int sts0_serrorout { get; set; } + + /// The number of server password violations. + public int sts0_pwerrors { get; set; } + + /// The number of server access permission errors. + public int sts0_permerrors { get; set; } + + /// The number of server system errors. + public int sts0_syserrors { get; set; } + + /// The number of server bytes sent to the network. + public int sts0_bytessent_low { get; set; } + + /// The number of server bytes sent to the network. + public int sts0_bytessent_high { get; set; } + + /// The number of server bytes received from the network. + public int sts0_bytesrcvd_low { get; set; } + + /// The number of server bytes received from the network. + public long sts0_bytesrcvd_high { get; set; } + + /// The average server response time. + public TimeSpan AverageResponseTime { get; set; } + + /// 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. + public int BufferAllocationFail { get; set; } + + /// 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. + public int BigBufferNeeded { get; set; } + + #endregion // Properties + + + //#region Methods + + ///// Returns the full path to the share. + ///// A string that represents this instance. + //public override string ToString() + //{ + // return Id.ToString(CultureInfo.InvariantCulture); + //} + + //#endregion // Methods + } +} From faae479644cd09e057bacf9375a03e58d4d17922 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 9 Feb 2018 11:52:01 +0100 Subject: [PATCH 031/133] -Fixed compile error; -Correct ID casing; --- .../AlphaFS_DeviceInfo_InitializeInstance.cs | 61 ------------------- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 - .../Directory Class/DirectoryTest.cs | 2 - AlphaFS/AlphaFS.csproj | 9 +-- .../Device/Volume/Volume.QueryDosDevice.cs | 1 - AlphaFS/Filesystem/FindFileSystemEntryInfo.cs | 3 + .../Path Class/Path.ValidationAndChecks.cs | 1 - .../DirectoryEnumerationFilters.cs | 3 + AlphaFS/Network/Host Class/Host.cs | 2 + AlphaFS/Network/NetworkConnectionInfo.cs | 8 +-- AlphaFS/Network/NetworkInfo.cs | 2 +- 11 files changed, 13 insertions(+), 80 deletions(-) delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo_InitializeInstance.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo_InitializeInstance.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo_InitializeInstance.cs deleted file mode 100644 index 7222d21af..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceInfo_InitializeInstance.cs +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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_DeviceTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_DeviceInfo_InitializeInstance_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"); - - DeviceInfo_InitializeInstance(false); - //DeviceInfo_InitializeInstance(true); - } - - - - - private void DeviceInfo_InitializeInstance(bool isNetwork) - { - UnitTestConstants.PrintUnitTestHeader(isNetwork); - - var deviceInfo = new Alphaleonis.Win32.Filesystem.DeviceInfo(isNetwork ? UnitTestConstants.LocalHost : string.Empty); - - UnitTestConstants.Dump(deviceInfo, -24); - - Assert.AreEqual(deviceInfo.HostName, UnitTestConstants.LocalHost); - Assert.AreEqual(deviceInfo.Class, null); - Assert.AreEqual(deviceInfo.ClassGuid, new Guid()); - - - Console.WriteLine(); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index b189905c4..b4fb0d731 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -164,7 +164,6 @@ - diff --git a/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs b/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs index 5222de733..a67526202 100644 --- a/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs +++ b/AlphaFS.UnitTest/Directory Class/DirectoryTest.cs @@ -26,9 +26,7 @@ using System.Linq; using System.Reflection; using System.Security.Principal; -using Alphaleonis; using Directory = Alphaleonis.Win32.Filesystem.Directory; -using DriveInfo = Alphaleonis.Win32.Filesystem.DriveInfo; using File = Alphaleonis.Win32.Filesystem.File; using Path = Alphaleonis.Win32.Filesystem.Path; diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 9b71e6444..ca289b752 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -485,14 +485,7 @@ - - - - - - - @@ -619,7 +612,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs b/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs index d9427f015..40c28ef84 100644 --- a/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs +++ b/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs @@ -21,7 +21,6 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Runtime.InteropServices; diff --git a/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs b/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs index 2d2cfe1c8..f3abec54f 100644 --- a/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs +++ b/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs @@ -28,7 +28,10 @@ using System.Runtime.InteropServices; using System.Security; using System.Text.RegularExpressions; + +#if !NET35 using System.Threading; +#endif namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs b/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs index 3e63610e0..228018ed9 100644 --- a/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs +++ b/AlphaFS/Filesystem/Path Class/Path.ValidationAndChecks.cs @@ -23,7 +23,6 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; -using System.Linq; using System.Security; using System.Text; diff --git a/AlphaFS/Filesystem/Structures And Enumerations/DirectoryEnumerationFilters.cs b/AlphaFS/Filesystem/Structures And Enumerations/DirectoryEnumerationFilters.cs index 20dcac3b6..532d4fd88 100644 --- a/AlphaFS/Filesystem/Structures And Enumerations/DirectoryEnumerationFilters.cs +++ b/AlphaFS/Filesystem/Structures And Enumerations/DirectoryEnumerationFilters.cs @@ -20,7 +20,10 @@ */ using System; + +#if !NET35 using System.Threading; +#endif namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Network/Host Class/Host.cs b/AlphaFS/Network/Host Class/Host.cs index 082d935fa..5f308af22 100644 --- a/AlphaFS/Network/Host Class/Host.cs +++ b/AlphaFS/Network/Host Class/Host.cs @@ -37,6 +37,8 @@ namespace Alphaleonis.Win32.Network /// Provides static methods to retrieve network resource information from a local- or remote host. public static partial class Host { + private static readonly NetworkListManager Manager = new 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); diff --git a/AlphaFS/Network/NetworkConnectionInfo.cs b/AlphaFS/Network/NetworkConnectionInfo.cs index abbf8af24..93cd53c5e 100644 --- a/AlphaFS/Network/NetworkConnectionInfo.cs +++ b/AlphaFS/Network/NetworkConnectionInfo.cs @@ -21,9 +21,7 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Net.NetworkInformation; -using System.Runtime.Remoting.Messaging; namespace Alphaleonis.Win32.Network { @@ -51,7 +49,7 @@ internal NetworkConnectionInfo(INetworkConnection networkConnection) /// Gets the unique identifier for this connection. This value of this property is not cached. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] - public Guid ConnectionID + public Guid ConnectionId { get { return _networkConnection.GetConnectionId(); } } @@ -99,7 +97,7 @@ public NetworkInterface NetworkInterface get { Guid guid; - var adapterID = _networkConnection.GetAdapterId(); + var adapterId = _networkConnection.GetAdapterId(); foreach (var nic in NetworkInterface.GetAllNetworkInterfaces()) @@ -112,7 +110,7 @@ public NetworkInterface NetworkInterface continue; #endif - if (adapterID.Equals(guid)) + if (adapterId.Equals(guid)) return nic; } diff --git a/AlphaFS/Network/NetworkInfo.cs b/AlphaFS/Network/NetworkInfo.cs index 936759f9b..a6308a372 100644 --- a/AlphaFS/Network/NetworkInfo.cs +++ b/AlphaFS/Network/NetworkInfo.cs @@ -175,7 +175,7 @@ public string Name /// Gets a unique identifier for the network. This value of this property is not cached. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] - public Guid NetworkID + public Guid NetworkId { get { return _network.GetNetworkId(); } } From 31348cd3cc94e4b8b513dd4c8355151f2f17529a Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 9 Feb 2018 15:12:48 +0100 Subject: [PATCH 032/133] Implemented ServerStatisticsInfo. --- .../AlphaFS.Host.GetServerNetStatistics.cs | 43 +++++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 + .../Host Class/Host.SMB.GetNetStatistics.cs | 54 +++++- AlphaFS/Network/Native Other/STAT_SERVER_0.cs | 7 +- AlphaFS/Network/ServerStatisticsInfo.cs | 177 +++++++++++++----- 5 files changed, 223 insertions(+), 59 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host.GetServerNetStatistics.cs diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host.GetServerNetStatistics.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host.GetServerNetStatistics.cs new file mode 100644 index 000000000..28a442d93 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host.GetServerNetStatistics.cs @@ -0,0 +1,43 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_HostTest + { + [TestMethod] + public void AlphaFS_Host_GetServerNetStatistics_Local_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + if (!UnitTestConstants.IsAdmin()) + Assert.Inconclusive(); + + + var serverStatistics = Alphaleonis.Win32.Network.Host.GetServerNetStatistics(); + + UnitTestConstants.Dump(serverStatistics, -22); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 35c538a17..7d16421e0 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -166,6 +166,7 @@ + diff --git a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs index 319ce90f2..6d60255c3 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs @@ -20,15 +20,28 @@ */ using System; -using System.Globalization; -using System.Net.NetworkInformation; using System.Security; -using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network { partial class Host { + /// + /// + /// + /// + [SecurityCritical] + public static ServerStatisticsInfo GetServerNetStatistics() + { + return GetNetStatisticsCore(true, Environment.MachineName); + } + + + /// + /// + /// + /// + /// [SecurityCritical] public static ServerStatisticsInfo GetServerNetStatistics(string hostName) { @@ -36,6 +49,11 @@ public static ServerStatisticsInfo GetServerNetStatistics(string hostName) } + /// + /// + /// + /// + /// [SecurityCritical] public static ServerStatisticsInfo GetWorkstationNetStatistics(string hostName) { @@ -43,7 +61,14 @@ public static ServerStatisticsInfo GetWorkstationNetStatistics(string hostName) } - + + + /// + /// + /// + /// + /// + /// [SecurityCritical] internal static ServerStatisticsInfo GetNetStatisticsCore(bool isServer, string hostName) { @@ -51,7 +76,26 @@ internal static ServerStatisticsInfo GetNetStatisticsCore(bool isServer, string throw new ArgumentNullException("hostName"); - return null; + return new ServerStatisticsInfo(hostName, GetNetStatisticsNative(isServer, hostName)); + } + + + [SecurityCritical] + internal static NativeMethods.STAT_SERVER_0 GetNetStatisticsNative(bool isServer, string hostName) + { + SafeGlobalMemoryBufferHandle safeBuffer; + + var lastError = NativeMethods.NetStatisticsGet(hostName, isServer ? "LanmanServer" : "LanmanWorkstation", 0, 0, out safeBuffer); + + + using (safeBuffer) + { + if (lastError != Win32Errors.NERR_Success) + NativeError.ThrowException(lastError, hostName); + + + return safeBuffer.PtrToStructure(0); + } } } } diff --git a/AlphaFS/Network/Native Other/STAT_SERVER_0.cs b/AlphaFS/Network/Native Other/STAT_SERVER_0.cs index 075fbaf92..1513f0ed2 100644 --- a/AlphaFS/Network/Native Other/STAT_SERVER_0.cs +++ b/AlphaFS/Network/Native Other/STAT_SERVER_0.cs @@ -34,9 +34,10 @@ internal static partial class NativeMethods internal struct STAT_SERVER_0 { /// - /// Specifies a DWORD value that indicates the time when statistics collection started (or when the statistics were last cleared). - /// The value is stored as the number of seconds that have elapsed since 00:00:00, January 1, 1970, GMT. To calculate the length of time that statistics have been collected, - /// subtract the value of this member from the present time. + /// Specifies a DWORD value that indicates the time when statistics collection started (or when the statistics were last cleared). + /// The value is stored as the number of seconds that have elapsed since 00:00:00, January 1, 1970, GMT. + /// To calculate the length of time that statistics have been collected, + /// subtract the value of this member from the present time. /// [MarshalAs(UnmanagedType.U4)] public readonly uint sts0_start; diff --git a/AlphaFS/Network/ServerStatisticsInfo.cs b/AlphaFS/Network/ServerStatisticsInfo.cs index 138196d14..22610e7b9 100644 --- a/AlphaFS/Network/ServerStatisticsInfo.cs +++ b/AlphaFS/Network/ServerStatisticsInfo.cs @@ -21,7 +21,6 @@ using System; using System.Globalization; -using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network { @@ -29,95 +28,171 @@ namespace Alphaleonis.Win32.Network [Serializable] public sealed class ServerStatisticsInfo { - #region Constructor + [NonSerialized] private readonly DateTime _dateTimeNow; + [NonSerialized] private NativeMethods.STAT_SERVER_0 _serverStat; + - /// Create a OpenConnectionInfo instance. + /// Create a ServerStatisticsInfo instance. internal ServerStatisticsInfo(string hostName, NativeMethods.STAT_SERVER_0 serverStat) { - var ts = TimeSpan.FromSeconds(serverStat.sts0_start); + _dateTimeNow = DateTime.UtcNow; - //StartTime = DateTime.Now. - //.DateAdd("s", NumberOfSeconds, "1/1/1970") + HostName = hostName; + _serverStat = serverStat; + } + + + #region Properties - AverageResponseTime = TimeSpan.FromMilliseconds(serverStat.sts0_avresponse); + /// The number of server access permission errors. + public int AccessPermissionErrors + { + get { return (int) _serverStat.sts0_permerrors; } } - #endregion // Constructor + /// The average server response time. + public TimeSpan AverageResponseTime + { + get { return TimeSpan.FromMilliseconds(_serverStat.sts0_avresponse); } + } - #region Properties - /// The local time when statistics collection started (or when the statistics were last cleared). - public DateTime StartTime + /// 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. + public int BufferAllocationFailed { - get { return StartTime.ToLocalTime(); } + get { return (int) _serverStat.sts0_bigbufneed; } } - /// The time when statistics collection started (or when the statistics were last cleared). - public DateTime StartTimeUtc { get; set; } + /// 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. + public int BufferRequestFailed + { + get { return (int) _serverStat.sts0_reqbufneed; } + } + + + /// The number of server bytes received from the network. + public long BytesReceived + { + get { return Filesystem.NativeMethods.ToLong(_serverStat.sts0_bytesrcvd_high, _serverStat.sts0_bytesrcvd_low); } + } + + + /// The number of server bytes received from the network, formatted as a unit size. + public string BytesReceivedUnitSize + { + get { return Utils.UnitSizeToText(BytesReceived); } + } + + + /// The number of server bytes sent to the network. + public long BytesSent + { + get { return Filesystem.NativeMethods.ToLong(_serverStat.sts0_bytessent_high, _serverStat.sts0_bytessent_low); } + } + + + /// The number of server bytes sent to the network, formatted as a unit size. + public string BytesSentUnitSize + { + get { return Utils.UnitSizeToText(BytesSent); } + } - /// The number of times a file is opened on a server. This includes the number of times named pipes are opened. - public int sts0_fopens { get; set; } /// The number of times a server device is opened. - public int sts0_devopens { get; set; } + public int DevicesOpened + { + get { return (int) _serverStat.sts0_devopens; } + } + + + /// The number of times a file is opened on a server. This includes the number of times named pipes are opened. + public int FilesOpened + { + get { return (int) _serverStat.sts0_fopens; } + } + + + /// The host name from where the statistics are gathered. + public string HostName { get; set; } + /// The number of server print jobs spooled. - public int JobsQueued { get; set; } + public int JobsQueued + { + get { return (int) _serverStat.sts0_jobsqueued; } + } - /// The number of times the server session started. - public int sts0_sopens { get; set; } - /// The number of times the server session automatically disconnected. - public int sts0_stimedout { get; set; } + /// The number of server password violations. + public int PasswordViolations + { + get { return (int) _serverStat.sts0_pwerrors; } + } + /// The number of times the server sessions failed with an error. - public int sts0_serrorout { get; set; } + public int SessionsFailed + { + get { return (int) _serverStat.sts0_serrorout; } + } - /// The number of server password violations. - public int sts0_pwerrors { get; set; } - /// The number of server access permission errors. - public int sts0_permerrors { get; set; } + /// The number of times the server session started. + public int SessionsStarted + { + get { return (int) _serverStat.sts0_sopens; } + } - /// The number of server system errors. - public int sts0_syserrors { get; set; } - /// The number of server bytes sent to the network. - public int sts0_bytessent_low { get; set; } + /// The number of times the server session automatically disconnected. + public int SessionsTimedOut + { + get { return (int) _serverStat.sts0_stimedout; } + } - /// The number of server bytes sent to the network. - public int sts0_bytessent_high { get; set; } - /// The number of server bytes received from the network. - public int sts0_bytesrcvd_low { get; set; } + /// The local time when statistics collection started or when the statistics were last cleared. + public DateTime StartTime + { + get { return StartTimeUtc.ToLocalTime(); } + } - /// The number of server bytes received from the network. - public long sts0_bytesrcvd_high { get; set; } - /// The average server response time. - public TimeSpan AverageResponseTime { get; set; } + /// The time when statistics collection started or when the statistics were last cleared. + public DateTime StartTimeUtc + { + get { return new DateTime((_dateTimeNow - new DateTime(_serverStat.sts0_start, DateTimeKind.Utc)).Ticks, DateTimeKind.Utc); } + } - /// 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. - public int BufferAllocationFail { get; set; } - /// 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. - public int BigBufferNeeded { get; set; } + /// The number of server system errors. + public int SystemErrors + { + get { return (int) _serverStat.sts0_syserrors; } + } #endregion // Properties - //#region Methods + #region Methods + + /// Refreshes the state of the object. + public void Refresh() + { + _serverStat = Host.GetNetStatisticsNative(true, HostName); + } + - ///// Returns the full path to the share. - ///// A string that represents this instance. - //public override string ToString() - //{ - // return Id.ToString(CultureInfo.InvariantCulture); - //} + /// Returns the local time when statistics collection started or when the statistics were last cleared. + /// A string that represents this instance. + public override string ToString() + { + return StartTime.ToString(CultureInfo.CurrentCulture); + } - //#endregion // Methods + #endregion // Methods } } From cc73f0a5b569d3d9f3e2f6c1202766aa48ec4e6f Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 10 Feb 2018 10:21:59 +0100 Subject: [PATCH 033/133] Code improvement, work in progress. --- ...=> AlphaFS.Host_GetServerNetStatistics.cs} | 0 AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 2 +- .../Host Class/Host.SMB.GetNetStatistics.cs | 12 +- AlphaFS/Network/ServerStatisticsInfo.cs | 107 ++++++++++++++---- 4 files changed, 90 insertions(+), 31 deletions(-) rename AlphaFS.UnitTest/AlphaFS Host Class/{AlphaFS.Host.GetServerNetStatistics.cs => AlphaFS.Host_GetServerNetStatistics.cs} (100%) diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host.GetServerNetStatistics.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetServerNetStatistics.cs similarity index 100% rename from AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host.GetServerNetStatistics.cs rename to AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetServerNetStatistics.cs diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 7d16421e0..43b6e02bb 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -166,7 +166,7 @@ - + diff --git a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs index 6d60255c3..58edbd8ec 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs @@ -20,6 +20,7 @@ */ using System; +using System.Net.NetworkInformation; using System.Security; namespace Alphaleonis.Win32.Network @@ -72,11 +73,7 @@ public static ServerStatisticsInfo GetWorkstationNetStatistics(string hostName) [SecurityCritical] internal static ServerStatisticsInfo GetNetStatisticsCore(bool isServer, string hostName) { - if (Utils.IsNullOrWhiteSpace(hostName)) - throw new ArgumentNullException("hostName"); - - - return new ServerStatisticsInfo(hostName, GetNetStatisticsNative(isServer, hostName)); + return new ServerStatisticsInfo(hostName, false, GetNetStatisticsNative(isServer, hostName)); } @@ -85,13 +82,16 @@ internal static NativeMethods.STAT_SERVER_0 GetNetStatisticsNative(bool isServer { SafeGlobalMemoryBufferHandle safeBuffer; + + // hostName is allowed to be null. + var lastError = NativeMethods.NetStatisticsGet(hostName, isServer ? "LanmanServer" : "LanmanWorkstation", 0, 0, out safeBuffer); using (safeBuffer) { if (lastError != Win32Errors.NERR_Success) - NativeError.ThrowException(lastError, hostName); + throw new NetworkInformationException((int) lastError); return safeBuffer.PtrToStructure(0); diff --git a/AlphaFS/Network/ServerStatisticsInfo.cs b/AlphaFS/Network/ServerStatisticsInfo.cs index 22610e7b9..09fd7514a 100644 --- a/AlphaFS/Network/ServerStatisticsInfo.cs +++ b/AlphaFS/Network/ServerStatisticsInfo.cs @@ -20,7 +20,6 @@ */ using System; -using System.Globalization; namespace Alphaleonis.Win32.Network { @@ -28,18 +27,34 @@ namespace Alphaleonis.Win32.Network [Serializable] public sealed class ServerStatisticsInfo { - [NonSerialized] private readonly DateTime _dateTimeNow; + [NonSerialized] private DateTime _dateTimeNow; [NonSerialized] private NativeMethods.STAT_SERVER_0 _serverStat; - - /// Create a ServerStatisticsInfo instance. - internal ServerStatisticsInfo(string hostName, NativeMethods.STAT_SERVER_0 serverStat) + + /// Create a ServerStatisticsInfo instance from the local host. + public ServerStatisticsInfo() : this(Environment.MachineName, true, null) + { + } + + + /// Create a ServerStatisticsInfo instance from the specified host name. + public ServerStatisticsInfo(string hostName) : this(hostName, true, null) + { + } + + + /// Create a ServerStatisticsInfo instance from the specified host name. + internal ServerStatisticsInfo(string hostName, bool refresh, NativeMethods.STAT_SERVER_0? serverStat) { + HostName = !Utils.IsNullOrWhiteSpace(hostName) ? hostName : Environment.MachineName; + _dateTimeNow = DateTime.UtcNow; - HostName = hostName; + if (serverStat.HasValue) + _serverStat = (NativeMethods.STAT_SERVER_0) serverStat; - _serverStat = serverStat; + else if (refresh) + Refresh(); } @@ -101,6 +116,20 @@ public string BytesSentUnitSize } + /// The local time when statistics collection started or when the statistics were last cleared. + public DateTime CollectedTime + { + get { return CollectedTimeUtc.ToLocalTime(); } + } + + + /// The time when statistics collection started or when the statistics were last cleared. + public DateTime CollectedTimeUtc + { + get { return new DateTime((_dateTimeNow - new DateTime(_serverStat.sts0_start, DateTimeKind.Utc)).Ticks, DateTimeKind.Utc); } + } + + /// The number of times a server device is opened. public int DevicesOpened { @@ -116,7 +145,7 @@ public int FilesOpened /// The host name from where the statistics are gathered. - public string HostName { get; set; } + public string HostName { get; } /// The number of server print jobs spooled. @@ -152,21 +181,7 @@ public int SessionsTimedOut { get { return (int) _serverStat.sts0_stimedout; } } - - - /// The local time when statistics collection started or when the statistics were last cleared. - public DateTime StartTime - { - get { return StartTimeUtc.ToLocalTime(); } - } - - - /// The time when statistics collection started or when the statistics were last cleared. - public DateTime StartTimeUtc - { - get { return new DateTime((_dateTimeNow - new DateTime(_serverStat.sts0_start, DateTimeKind.Utc)).Ticks, DateTimeKind.Utc); } - } - + /// The number of server system errors. public int SystemErrors @@ -182,6 +197,8 @@ public int SystemErrors /// Refreshes the state of the object. public void Refresh() { + _dateTimeNow = DateTime.UtcNow; + _serverStat = Host.GetNetStatisticsNative(true, HostName); } @@ -190,7 +207,49 @@ public void Refresh() /// A string that represents this instance. public override string ToString() { - return StartTime.ToString(CultureInfo.CurrentCulture); + return HostName; + } + + + /// Determines whether the specified Object is equal to the current Object. + /// Another object to compare to. + /// if the specified Object is equal to the current Object; otherwise, . + public override bool Equals(object obj) + { + if (null == obj || GetType() != obj.GetType()) + return false; + + var other = obj as ServerStatisticsInfo; + + return null != other && null != other.HostName && other.HostName.Equals(HostName, StringComparison.OrdinalIgnoreCase) && other.CollectedTimeUtc.Equals(CollectedTimeUtc); + } + + + /// Serves as a hash function for a particular type. + /// A hash code for the current Object. + public override int GetHashCode() + { + return null != HostName ? HostName.GetHashCode() : 0; + } + + + /// Implements the operator == + /// A. + /// B. + /// The result of the operator. + public static bool operator ==(ServerStatisticsInfo left, ServerStatisticsInfo right) + { + return left is null && right is null || !(left is null) && !(right is null) && left.Equals(right); + } + + + /// Implements the operator != + /// A. + /// B. + /// The result of the operator. + public static bool operator !=(ServerStatisticsInfo left, ServerStatisticsInfo right) + { + return !(left == right); } #endregion // Methods From b21b28870a2b6f31b5bd73d02c33e5f5fa5e5f26 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 10 Feb 2018 14:24:33 +0100 Subject: [PATCH 034/133] Added class WorkstationStatisticsInfo. --- ...cs => AlphaFS.Host_GetServerStatistics.cs} | 4 +- .../AlphaFS.Host_GetWorkstationStatistics.cs | 42 ++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 3 +- AlphaFS/AlphaFS.csproj | 3 +- .../Host Class/Host.SMB.GetNetStatistics.cs | 74 +-- .../Native Other/STAT_WORKSTATION_0.cs | 5 +- AlphaFS/Network/ServerStatisticsInfo.cs | 56 +- AlphaFS/Network/WorkstationStatisticsInfo.cs | 483 ++++++++++++++++++ 8 files changed, 606 insertions(+), 64 deletions(-) rename AlphaFS.UnitTest/AlphaFS Host Class/{AlphaFS.Host_GetServerNetStatistics.cs => AlphaFS.Host_GetServerStatistics.cs} (94%) create mode 100644 AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetWorkstationStatistics.cs create mode 100644 AlphaFS/Network/WorkstationStatisticsInfo.cs diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetServerNetStatistics.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetServerStatistics.cs similarity index 94% rename from AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetServerNetStatistics.cs rename to AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetServerStatistics.cs index 28a442d93..b74de97df 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetServerNetStatistics.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetServerStatistics.cs @@ -27,7 +27,7 @@ namespace AlphaFS.UnitTest public partial class AlphaFS_HostTest { [TestMethod] - public void AlphaFS_Host_GetServerNetStatistics_Local_Success() + public void AlphaFS_Host_GetServerStatistics_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -35,7 +35,7 @@ public void AlphaFS_Host_GetServerNetStatistics_Local_Success() Assert.Inconclusive(); - var serverStatistics = Alphaleonis.Win32.Network.Host.GetServerNetStatistics(); + var serverStatistics = Alphaleonis.Win32.Network.Host.GetServerStatistics(); UnitTestConstants.Dump(serverStatistics, -22); } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetWorkstationStatistics.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetWorkstationStatistics.cs new file mode 100644 index 000000000..752a63695 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetWorkstationStatistics.cs @@ -0,0 +1,42 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace AlphaFS.UnitTest +{ + public partial class AlphaFS_HostTest + { + [TestMethod] + public void AlphaFS_Host_GetWorkstationStatistics_Local_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + if (!UnitTestConstants.IsAdmin()) + Assert.Inconclusive(); + + + var workstationStat = Alphaleonis.Win32.Network.Host.GetWorkstationStatistics(); + + UnitTestConstants.Dump(workstationStat, -36); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 43b6e02bb..13a692806 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -165,8 +165,9 @@ + - + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index dc1c42df4..622df134d 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -512,6 +512,7 @@ + @@ -602,7 +603,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs index 58edbd8ec..7867d79ff 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs @@ -27,58 +27,70 @@ namespace Alphaleonis.Win32.Network { partial class Host { - /// - /// - /// - /// + /// [AlphaFS] Retrieves operating statistics for the Server service from the local host. + /// A instance. + /// [SecurityCritical] - public static ServerStatisticsInfo GetServerNetStatistics() + public static ServerStatisticsInfo GetServerStatistics() { - return GetNetStatisticsCore(true, Environment.MachineName); + return (ServerStatisticsInfo) GetNetStatisticsCore(true, Environment.MachineName); } - /// - /// - /// - /// - /// + /// [AlphaFS] Retrieves operating statistics for the Server service from the specified host. + /// A instance. + /// + /// The name of the local or remote host to retrieve statistics from. [SecurityCritical] - public static ServerStatisticsInfo GetServerNetStatistics(string hostName) + public static ServerStatisticsInfo GetServerStatistics(string hostName) { - return GetNetStatisticsCore(true, hostName); + return (ServerStatisticsInfo) GetNetStatisticsCore(true, hostName); } - /// - /// - /// - /// - /// + + + /// [AlphaFS] Retrieves operating statistics for the Workstation service from the local host. + /// A instance. + /// + [SecurityCritical] + public static WorkstationStatisticsInfo GetWorkstationStatistics() + { + return (WorkstationStatisticsInfo) GetNetStatisticsCore(false, Environment.MachineName); + } + + + /// [AlphaFS] Retrieves operating statistics for the Workstation service from the specified host. + /// A instance. + /// + /// The name of the local or remote host to retrieve statistics from. [SecurityCritical] - public static ServerStatisticsInfo GetWorkstationNetStatistics(string hostName) + public static WorkstationStatisticsInfo GetWorkstationStatistics(string hostName) { - return GetNetStatisticsCore(false, hostName); + return (WorkstationStatisticsInfo) GetNetStatisticsCore(false, hostName); } - /// - /// - /// - /// - /// - /// + /// [AlphaFS] Retrieves or operating statistics for the Server- or Workstation service from the specified host. + /// A or instance, depending on the value. + /// + /// true returns information, false . + /// The name of the local or remote host to retrieve statistics from. [SecurityCritical] - internal static ServerStatisticsInfo GetNetStatisticsCore(bool isServer, string hostName) + internal static object GetNetStatisticsCore(bool isServer, string hostName) { - return new ServerStatisticsInfo(hostName, false, GetNetStatisticsNative(isServer, hostName)); + return isServer + + ? (object) new ServerStatisticsInfo(hostName, null) + + : new WorkstationStatisticsInfo(hostName, null); } - + [SecurityCritical] - internal static NativeMethods.STAT_SERVER_0 GetNetStatisticsNative(bool isServer, string hostName) + internal static T GetNetStatisticsNative(bool isServer, string hostName) { SafeGlobalMemoryBufferHandle safeBuffer; @@ -94,7 +106,7 @@ internal static NativeMethods.STAT_SERVER_0 GetNetStatisticsNative(bool isServer throw new NetworkInformationException((int) lastError); - return safeBuffer.PtrToStructure(0); + return safeBuffer.PtrToStructure(0); } } } diff --git a/AlphaFS/Network/Native Other/STAT_WORKSTATION_0.cs b/AlphaFS/Network/Native Other/STAT_WORKSTATION_0.cs index eca9fc315..3c6961a2c 100644 --- a/AlphaFS/Network/Native Other/STAT_WORKSTATION_0.cs +++ b/AlphaFS/Network/Native Other/STAT_WORKSTATION_0.cs @@ -34,11 +34,12 @@ internal static partial class NativeMethods internal struct STAT_WORKSTATION_0 { /// - /// Specifies the time statistics collection started. This member also indicates when statistics for the workstations were last cleared. - /// The value is stored as the number of seconds elapsed since 00:00:00, January 1, 1970. + /// Specifies the time statistics collection started. This member also indicates when statistics for the workstations were last cleared. + /// The value is stored as the number of seconds elapsed since 00:00:00, January 1, 1970. /// [MarshalAs(UnmanagedType.U8)] public readonly long StatisticsStartTime; + /// Specifies the total number of bytes received by the workstation. [MarshalAs(UnmanagedType.U8)] public readonly long BytesReceived; diff --git a/AlphaFS/Network/ServerStatisticsInfo.cs b/AlphaFS/Network/ServerStatisticsInfo.cs index 09fd7514a..1c685ea0b 100644 --- a/AlphaFS/Network/ServerStatisticsInfo.cs +++ b/AlphaFS/Network/ServerStatisticsInfo.cs @@ -23,37 +23,39 @@ namespace Alphaleonis.Win32.Network { - /// Contains the identification number of a connection, number of open files, connection time, number of users on the connection, and the type of connection. + /// Contains operating statistics for the Server service. [Serializable] public sealed class ServerStatisticsInfo { - [NonSerialized] private DateTime _dateTimeNow; + [NonSerialized] private DateTime _dateTimeNowUtc; [NonSerialized] private NativeMethods.STAT_SERVER_0 _serverStat; /// Create a ServerStatisticsInfo instance from the local host. - public ServerStatisticsInfo() : this(Environment.MachineName, true, null) + public ServerStatisticsInfo() : this(Environment.MachineName, null) { } /// Create a ServerStatisticsInfo instance from the specified host name. - public ServerStatisticsInfo(string hostName) : this(hostName, true, null) + public ServerStatisticsInfo(string hostName) : this(hostName, null) { } /// Create a ServerStatisticsInfo instance from the specified host name. - internal ServerStatisticsInfo(string hostName, bool refresh, NativeMethods.STAT_SERVER_0? serverStat) + internal ServerStatisticsInfo(string hostName, NativeMethods.STAT_SERVER_0? serverStat) { HostName = !Utils.IsNullOrWhiteSpace(hostName) ? hostName : Environment.MachineName; - _dateTimeNow = DateTime.UtcNow; - if (serverStat.HasValue) + { + _dateTimeNowUtc = DateTime.UtcNow; + _serverStat = (NativeMethods.STAT_SERVER_0) serverStat; + } - else if (refresh) + else Refresh(); } @@ -114,21 +116,7 @@ public string BytesSentUnitSize { get { return Utils.UnitSizeToText(BytesSent); } } - - - /// The local time when statistics collection started or when the statistics were last cleared. - public DateTime CollectedTime - { - get { return CollectedTimeUtc.ToLocalTime(); } - } - - - /// The time when statistics collection started or when the statistics were last cleared. - public DateTime CollectedTimeUtc - { - get { return new DateTime((_dateTimeNow - new DateTime(_serverStat.sts0_start, DateTimeKind.Utc)).Ticks, DateTimeKind.Utc); } - } - + /// The number of times a server device is opened. public int DevicesOpened @@ -181,7 +169,21 @@ public int SessionsTimedOut { get { return (int) _serverStat.sts0_stimedout; } } - + + + /// The local time when statistics collection started or when the statistics were last cleared. + public DateTime StatisticsStartTime + { + get { return StatisticsStartTimeUtc.ToLocalTime(); } + } + + + /// The time when statistics collection started or when the statistics were last cleared. + public DateTime StatisticsStartTimeUtc + { + get { return new DateTime((_dateTimeNowUtc - new DateTime(_serverStat.sts0_start, DateTimeKind.Utc)).Ticks, DateTimeKind.Utc); } + } + /// The number of server system errors. public int SystemErrors @@ -197,9 +199,9 @@ public int SystemErrors /// Refreshes the state of the object. public void Refresh() { - _dateTimeNow = DateTime.UtcNow; + _dateTimeNowUtc = DateTime.UtcNow; - _serverStat = Host.GetNetStatisticsNative(true, HostName); + _serverStat = Host.GetNetStatisticsNative(true, HostName); } @@ -221,7 +223,7 @@ public override bool Equals(object obj) var other = obj as ServerStatisticsInfo; - return null != other && null != other.HostName && other.HostName.Equals(HostName, StringComparison.OrdinalIgnoreCase) && other.CollectedTimeUtc.Equals(CollectedTimeUtc); + return null != other && null != other.HostName && other.HostName.Equals(HostName, StringComparison.OrdinalIgnoreCase) && other.StatisticsStartTimeUtc.Equals(StatisticsStartTimeUtc); } diff --git a/AlphaFS/Network/WorkstationStatisticsInfo.cs b/AlphaFS/Network/WorkstationStatisticsInfo.cs new file mode 100644 index 000000000..3a334c869 --- /dev/null +++ b/AlphaFS/Network/WorkstationStatisticsInfo.cs @@ -0,0 +1,483 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Contains operating statistics for the Workstation service. + [Serializable] + public sealed class WorkstationStatisticsInfo + { + [NonSerialized] private NativeMethods.STAT_WORKSTATION_0 _workstationStat; + + + /// Create a WorkstationStatisticsInfo instance from the local host. + public WorkstationStatisticsInfo() : this(Environment.MachineName, null) + { + } + + + /// Create a WorkstationStatisticsInfo instance from the specified host name. + public WorkstationStatisticsInfo(string hostName) : this(hostName, null) + { + } + + + /// Create a ServerStatisticsInfo instance from the specified host name. + 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(); + } + + + #region Properties + + /// The total number of bytes received by the workstation. + public long BytesReceived + { + get { return _workstationStat.BytesReceived; } + } + + + /// The total number of bytes received by the workstation, formatted as a unit size. + public string BytesReceivedUnitSize + { + get { return Utils.UnitSizeToText(BytesReceived); } + } + + + /// The total number of bytes transmitted by the workstation. + public long BytesTransmitted + { + get { return _workstationStat.BytesTransmitted; } + } + + + /// The total number of bytes transmitted by the workstation, formatted as a unit size. + public string BytesTransmittedUnitSize + { + get { return Utils.UnitSizeToText(BytesTransmitted); } + } + + + /// The total number of bytes that have been read by cache I/O requests. + public long CacheReadBytesRequested + { + get { return _workstationStat.CacheReadBytesRequested; } + } + + + /// The total number of bytes that have been read by cache I/O requests, formatted as a unit size. + public string CacheReadBytesRequestedUnitSize + { + get { return Utils.UnitSizeToText(CacheReadBytesRequested); } + } + + + /// The total number of bytes that have been written by cache I/O requests. + public long CacheWriteBytesRequested + { + get { return _workstationStat.CacheWriteBytesRequested; } + } + + + /// The total number of bytes that have been written by cache I/O requests, formatted as a unit size. + public string CacheWriteBytesRequestedUnitSize + { + get { return Utils.UnitSizeToText(CacheWriteBytesRequested); } + } + + + /// The total number of connections to servers supporting the PCNET dialect that have succeeded. + public int CoreConnects + { + get { return (int) _workstationStat.CoreConnects; } + } + + + /// The number of current requests that have not been completed. + public int CurrentCommands + { + get { return (int) _workstationStat.CurrentCommands; } + } + + + /// The total number of network operations that failed to complete. + public int FailedCompletionOperations + { + get { return (int) _workstationStat.FailedCompletionOperations; } + } + + + /// The number of times the workstation attempted to create a session but failed. + public int FailedSessions + { + get { return (int) _workstationStat.FailedSessions; } + } + + + /// The total number of failed network connections for the workstation. + public int FailedUseCount + { + get { return (int) _workstationStat.FailedUseCount; } + } + + + /// The host name from where the statistics are gathered. + public string HostName { get; } + + + /// The total number of network operations that failed to begin. + public int InitiallyFailedOperations + { + get { return (int) _workstationStat.InitiallyFailedOperations; } + } + + + /// The total number of sessions that have expired on the workstation. + public int HungSessions + { + get { return (int) _workstationStat.HungSessions; } + } + + + /// The total number of connections to servers supporting the LanManager 2.0 dialect that have succeeded. + public int Lanman20Connects + { + get { return (int) _workstationStat.Lanman20Connects; } + } + + + /// The total number of connections to servers supporting the LanManager 2.1 dialect that have succeeded. + public int Lanman21Connects + { + get { return (int) _workstationStat.Lanman21Connects; } + } + + + /// The total number of connections to servers supporting the NTLM dialect that have succeeded. + public int LanmanNtConnects + { + get { return (int) _workstationStat.LanmanNtConnects; } + } + + + /// 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. + public int LargeReadSmbs + { + get { return (int) _workstationStat.LargeReadSmbs; } + } + + + /// 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. + public int LargeWriteSmbs + { + get { return (int) _workstationStat.LargeWriteSmbs; } + } + + + /// The total number of network errors received by the workstation. + public int NetworkErrors + { + get { return (int) _workstationStat.NetworkErrors; } + } + + + /// The total amount of bytes that have been read by disk I/O requests. + public long NetworkReadBytesRequested + { + get { return _workstationStat.NetworkReadBytesRequested; } + } + + + /// The total amount of bytes that have been read by disk I/O requests, formatted as a unit size. + public string NetworkReadBytesRequestedUnitSize + { + get { return Utils.UnitSizeToText(NetworkReadBytesRequested); } + } + + + /// The total number of bytes that have been written by disk I/O requests. + public long NetworkWriteBytesRequested + { + get { return _workstationStat.NetworkWriteBytesRequested; } + } + + + /// The total number of bytes that have been written by disk I/O requests, formatted as a unit size. + public string NetworkWriteBytesRequestedUnitSize + { + get { return Utils.UnitSizeToText(NetworkWriteBytesRequested); } + } + + + /// The total number of bytes that have been read by non-paging I/O requests. + public long NonPagingReadBytesRequested + { + get { return _workstationStat.NonPagingReadBytesRequested; } + } + + + /// The total number of bytes that have been read by non-paging I/O requests, formatted as a unit size. + public string NonPagingReadBytesRequestedUnitSize + { + get { return Utils.UnitSizeToText(NonPagingReadBytesRequested); } + } + + + /// The total number of bytes that have been written by non-paging I/O requests. + public long NonPagingWriteBytesRequested + { + get { return _workstationStat.NonPagingWriteBytesRequested; } + } + + + /// The total number of bytes that have been written by non-paging I/O requests, formatted as a unit size. + public string NonPagingWriteBytesRequestedUnitSize + { + get { return Utils.UnitSizeToText(NonPagingWriteBytesRequested); } + } + + + /// The total number of bytes that have been read by paging I/O requests. + public long PagingReadBytesRequested + { + get { return _workstationStat.PagingReadBytesRequested; } + } + + + /// The total number of bytes that have been read by paging I/O requests, formatted as a unit size. + public string PagingReadBytesRequestedUnitSize + { + get { return Utils.UnitSizeToText(PagingReadBytesRequested); } + } + + + /// The total number of bytes that have been written by paging I/O requests. + public long PagingWriteBytesRequested + { + get { return _workstationStat.PagingWriteBytesRequested; } + } + + + /// The total number of bytes that have been written by paging I/O requests, formatted as a unit size. + public string PagingWriteBytesRequestedUnitSize + { + get { return Utils.UnitSizeToText(PagingWriteBytesRequested); } + } + + + /// The total number of random access reads initiated by the workstation. + public int RandomReadOperations + { + get { return (int) _workstationStat.RandomReadOperations; } + } + + + /// The total number of random access writes initiated by the workstation. + public int RandomWriteOperations + { + get { return (int) _workstationStat.RandomWriteOperations; } + } + + + /// The total number of raw read requests made by the workstation that have been denied. + public int RawReadsDenied + { + get { return (int) _workstationStat.RawReadsDenied; } + } + + + /// The total number of raw write requests made by the workstation that have been denied. + public int RawWritesDenied + { + get { return (int) _workstationStat.RawWritesDenied; } + } + + + /// The total number of read operations initiated by the workstation. + public int ReadOperations + { + get { return (int) _workstationStat.ReadOperations; } + } + + + /// The total number of read requests the workstation has sent to servers. + public int ReadSmbs + { + get { return (int) _workstationStat.ReadSmbs; } + } + + + /// The total number of connections that have failed. + public int Reconnects + { + get { return (int) _workstationStat.Reconnects; } + } + + + /// The number of times the workstation was disconnected by a network server. + public int ServerDisconnects + { + get { return (int) _workstationStat.ServerDisconnects; } + } + + + /// The total number of workstation sessions that were established. + public int Sessions + { + get { return (int) _workstationStat.Sessions; } + } + + + /// 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. + public int SmallReadSmbs + { + get { return (int) _workstationStat.SmallReadSmbs; } + } + + + /// 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. + public int SmallWriteSmbs + { + get { return (int) _workstationStat.SmallWriteSmbs; } + } + + + /// The local time statistics collection started. This member also indicates when statistics for the workstations were last cleared. + public DateTime StatisticsStartTime + { + get { return StatisticsStartTimeUtc.ToLocalTime(); } + } + + + /// The time statistics collection started. This member also indicates when statistics for the workstations were last cleared. + public DateTime StatisticsStartTimeUtc + { + get { return DateTime.FromFileTimeUtc(_workstationStat.StatisticsStartTime); } + } + + + /// The total number of server message blocks (SMBs) received by the workstation. + public long SmbsReceived + { + get { return _workstationStat.SmbsReceived; } + } + + + /// The total number of SMBs transmitted by the workstation. + public long SmbsTransmitted + { + get { return _workstationStat.SmbsTransmitted; } + } + + + /// The total number of network connections established by the workstation. + public int UseCount + { + get { return (int) _workstationStat.UseCount; } + } + + + /// The total number of write operations initiated by the workstation. + public int WriteOperations + { + get { return (int) _workstationStat.WriteOperations; } + } + + + /// The total number of write requests the workstation has sent to servers. + public int WriteSmbs + { + get { return (int) _workstationStat.WriteSmbs; } + } + + #endregion // Properties + + + #region Methods + + /// Refreshes the state of the object. + public void Refresh() + { + _workstationStat = Host.GetNetStatisticsNative(false, HostName); + } + + + /// Returns the local time when statistics collection started or when the statistics were last cleared. + /// A string that represents this instance. + public override string ToString() + { + return HostName; + } + + + /// Determines whether the specified Object is equal to the current Object. + /// Another object to compare to. + /// if the specified Object is equal to the current Object; otherwise, . + public override bool Equals(object obj) + { + if (null == obj || GetType() != obj.GetType()) + return false; + + var other = obj as WorkstationStatisticsInfo; + + return null != other && null != other.HostName && other.HostName.Equals(HostName, StringComparison.OrdinalIgnoreCase) && other.StatisticsStartTimeUtc.Equals(StatisticsStartTimeUtc); + } + + + /// Serves as a hash function for a particular type. + /// A hash code for the current Object. + public override int GetHashCode() + { + return null != HostName ? HostName.GetHashCode() : 0; + } + + + /// Implements the operator == + /// A. + /// B. + /// The result of the operator. + public static bool operator ==(WorkstationStatisticsInfo left, WorkstationStatisticsInfo right) + { + return left is null && right is null || !(left is null) && !(right is null) && left.Equals(right); + } + + + /// Implements the operator != + /// A. + /// B. + /// The result of the operator. + public static bool operator !=(WorkstationStatisticsInfo left, WorkstationStatisticsInfo right) + { + return !(left == right); + } + + #endregion // Methods + } +} From 86543f38446ede8ee0b8d32a85df2f3dec07227b Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 10 Feb 2018 14:36:41 +0100 Subject: [PATCH 035/133] Fixed project file. --- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index cd802e65e..3aa78fca3 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -165,12 +165,10 @@ - - - + From f7255b53ccc7851ac274278700094725e499605b Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 10 Feb 2018 18:02:06 +0100 Subject: [PATCH 036/133] Initial commit, work in progress. --- .../AlphaFS_Host.EnumerateSessions.cs | 69 +++++++++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 + AlphaFS/AlphaFS.csproj | 10 +- .../Network/Enumerations/SessionInfoLevel.cs | 42 +++++ .../Host Class/Host.SMB.EnumerateSessions.cs | 144 ++++++++++++++++++ .../Host Class/Host.SMB.GetNetStatistics.cs | 6 +- .../NativeMethods.NetworkShareManagement.cs | 20 ++- .../Network/Native Other/SESSION_INFO_0.cs | 40 +++++ .../Network/Native Other/SESSION_INFO_1.cs | 59 +++++++ .../Network/Native Other/SESSION_INFO_10.cs | 49 ++++++ .../Network/Native Other/SESSION_INFO_2.cs | 70 +++++++++ .../Network/Native Other/SESSION_INFO_502.cs | 73 +++++++++ AlphaFS/Network/SessionInfo.cs | 135 ++++++++++++++++ 13 files changed, 713 insertions(+), 5 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs create mode 100644 AlphaFS/Network/Enumerations/SessionInfoLevel.cs create mode 100644 AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs create mode 100644 AlphaFS/Network/Native Other/SESSION_INFO_0.cs create mode 100644 AlphaFS/Network/Native Other/SESSION_INFO_1.cs create mode 100644 AlphaFS/Network/Native Other/SESSION_INFO_10.cs create mode 100644 AlphaFS/Network/Native Other/SESSION_INFO_2.cs create mode 100644 AlphaFS/Network/Native Other/SESSION_INFO_502.cs create mode 100644 AlphaFS/Network/SessionInfo.cs diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs new file mode 100644 index 000000000..06554d4e3 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs @@ -0,0 +1,69 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_HostTest + { + // Pattern: ___ + + [TestMethod] + public void AlphaFS_Host_EnumerateSessions_Local_Success() + { + var host = UnitTestConstants.LocalHost; + + EnumerateSessions(host, true); + } + + + + + private void EnumerateSessions(string host, bool isNetwork) + { + UnitTestConstants.PrintUnitTestHeader(isNetwork); + + Console.WriteLine("\nInput Host: [{0}]", host); + + + var sessionCount = 0; + + foreach (var sessionsInfo in Alphaleonis.Win32.Network.Host.EnumerateSessions(host)) + { + //Console.WriteLine("\n\t#{0:000}\tShare: [{1}]", ++cnt, shareInfo); + + if (UnitTestConstants.Dump(sessionsInfo, -18)) + sessionCount++; + + Console.WriteLine(); + } + + + if (sessionCount == 0) + Assert.Inconclusive("No sessions enumerated, but it is expected. Try another server name if applicable."); + + + Console.WriteLine(); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 3aa78fca3..15d840d1c 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -169,6 +169,7 @@ + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index e8a9fa0f5..2809cec4f 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -470,6 +470,7 @@ + @@ -494,6 +495,7 @@ + @@ -516,6 +518,11 @@ + + + + + @@ -526,6 +533,7 @@ + @@ -617,7 +625,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Network/Enumerations/SessionInfoLevel.cs b/AlphaFS/Network/Enumerations/SessionInfoLevel.cs new file mode 100644 index 000000000..9f4daef6d --- /dev/null +++ b/AlphaFS/Network/Enumerations/SessionInfoLevel.cs @@ -0,0 +1,42 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// The information level. + public enum SessionInfoLevel + { + /// Contains the name of the computer that established the session. + Info0 = 0, + + /// Contains information about the session, including name of the computer; name of the user; and open files, pipes, and devices on the computer. + Info1 = 1, + + /// 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. + Info2 = 2, + + /// Contains information about the session, including name of the computer; name of the user; and active and idle times for the session. + Info10 = 10, + + /// 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. + Info502 = 502 + } +} diff --git a/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs b/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs new file mode 100644 index 000000000..3892d40e1 --- /dev/null +++ b/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs @@ -0,0 +1,144 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + partial class Host + { + /// [AlphaFS] Enumerates sessions established on the local host. + /// An collection from the local host. + [SecurityCritical] + public static IEnumerable EnumerateSessions() + { + return EnumerateSessionsCore(Environment.MachineName); + } + + + /// [AlphaFS] Enumerates sessions established on the specified . + /// An collection from the specified . + /// The DNS or NetBIOS name of the specified host. + [SecurityCritical] + public static IEnumerable EnumerateSessions(string hostName) + { + return EnumerateSessionsCore(hostName); + } + + + /// [AlphaFS] Enumerates sessions established on the specified . + /// An collection from the specified . + /// + /// The DNS or NetBIOS name of the specified host. + [SecurityCritical] + internal static IEnumerable EnumerateSessionsCore(string hostName) + { + var fd = new FunctionData(); + var hasItems = false; + + // 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(hostName) ? Environment.MachineName : Path.GetRegularPathCore(hostName, GetFullPathOptions.CheckInvalidPathChars, false).Replace(Path.UncPrefix, string.Empty); + + + // Try SESSION_INFO_502 structure. + + foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_502 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info502, structure), + + (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => + + NativeMethods.NetSessionEnum(stripUnc, null, null, 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(hostName, SessionInfoLevel.Info2, structure), + + (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => + + NativeMethods.NetSessionEnum(stripUnc, null, null, 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(hostName, SessionInfoLevel.Info1, structure), + + (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => + + NativeMethods.NetSessionEnum(stripUnc, null, null, 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(hostName, SessionInfoLevel.Info10, structure), + + (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => + + NativeMethods.NetSessionEnum(stripUnc, null, null, 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(hostName, SessionInfoLevel.Info0, structure), + + (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => + + NativeMethods.NetSessionEnum(stripUnc, null, null, SessionInfoLevel.Info0, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true)) + { + yield return sessionInfo; + } + } + } +} diff --git a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs index 7867d79ff..4b2d1c413 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs @@ -40,7 +40,7 @@ public static ServerStatisticsInfo GetServerStatistics() /// [AlphaFS] Retrieves operating statistics for the Server service from the specified host. /// A instance. /// - /// The name of the local or remote host to retrieve statistics from. + /// The DNS or NetBIOS name of the local or remote host to retrieve statistics from. [SecurityCritical] public static ServerStatisticsInfo GetServerStatistics(string hostName) { @@ -63,7 +63,7 @@ public static WorkstationStatisticsInfo GetWorkstationStatistics() /// [AlphaFS] Retrieves operating statistics for the Workstation service from the specified host. /// A instance. /// - /// The name of the local or remote host to retrieve statistics from. + /// The DNS or NetBIOS name of the local or remote host to retrieve statistics from. [SecurityCritical] public static WorkstationStatisticsInfo GetWorkstationStatistics(string hostName) { @@ -77,7 +77,7 @@ public static WorkstationStatisticsInfo GetWorkstationStatistics(string hostName /// A or instance, depending on the value. /// /// true returns information, false . - /// The name of the local or remote host to retrieve statistics from. + /// The DNS or NetBIOS name of the local or remote host to retrieve statistics from. [SecurityCritical] internal static object GetNetStatisticsCore(bool isServer, string hostName) { diff --git a/AlphaFS/Network/Native Methods/NativeMethods.NetworkShareManagement.cs b/AlphaFS/Network/Native Methods/NativeMethods.NetworkShareManagement.cs index c3fad230b..c098a5706 100644 --- a/AlphaFS/Network/Native Methods/NativeMethods.NetworkShareManagement.cs +++ b/AlphaFS/Network/Native Methods/NativeMethods.NetworkShareManagement.cs @@ -77,6 +77,23 @@ internal partial class NativeMethods internal static extern uint NetFileEnum([MarshalAs(UnmanagedType.LPWStr)] string serverName, [MarshalAs(UnmanagedType.LPWStr)] string basepath, [MarshalAs(UnmanagedType.LPWStr)] string username, [MarshalAs(UnmanagedType.U4)] uint level, out SafeGlobalMemoryBufferHandle buffer, [MarshalAs(UnmanagedType.I4)] int prefmaxlen, [MarshalAs(UnmanagedType.U4)] out uint entriesRead, [MarshalAs(UnmanagedType.U4)] out uint totalentries, [MarshalAs(UnmanagedType.U4)] out uint resumeHandle); + /// Provides information about sessions established on a server. + /// + /// If the function succeeds, the return value is NERR_Success. + /// If the function fails, the return value is a system error code. + /// + /// + /// Only members of the Administrators or Server Operators local group can successfully execute the NetSessionEnum function at level 1 or level 2. + /// No special group membership is required for level 0 or level 10 calls. + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [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 NetSessionEnum([MarshalAs(UnmanagedType.LPWStr)] string serverName, [MarshalAs(UnmanagedType.LPWStr)] string uncClientName, [MarshalAs(UnmanagedType.LPWStr)] string userName, [MarshalAs(UnmanagedType.U4)] SessionInfoLevel level, out SafeGlobalMemoryBufferHandle bufPtr, [MarshalAs(UnmanagedType.I4)] int prefMaxLen, [MarshalAs(UnmanagedType.U4)] out uint entriesRead, [MarshalAs(UnmanagedType.U4)] out uint totalEntries, [MarshalAs(UnmanagedType.U4)] out uint resumeHandle); + + /// Retrieves information about each (hidden) Server Message Block (SMB) resource/share on a server. /// /// If the function succeeds, the return value is NERR_Success. @@ -84,7 +101,8 @@ internal partial class NativeMethods /// /// /// For interactive users (users who are logged on locally to the machine), no special group membership is required to execute the NetShareEnum function. - /// For non-interactive users, Administrator, Power User, Print Operator, or Server Operator group membership is required to successfully execute the NetShareEnum function at levels 2, 502, and 503. No special group membership is required for level 0 or level 1 calls. + /// For non-interactive users, Administrator, Power User, Print Operator, or Server Operator group membership is required + /// to successfully execute the NetShareEnum function at levels 2, 502, and 503. No special group membership is required for level 0 or level 1 calls. /// This function applies only to Server Message Block (SMB) shares. /// Windows Server 2003 and Windows XP: For all users, Administrator, Power User, Print Operator, or Server Operator group membership is required to successfully execute the NetShareEnum function at levels 2 and 502. /// Minimum supported client: Windows XP [desktop apps only] diff --git a/AlphaFS/Network/Native Other/SESSION_INFO_0.cs b/AlphaFS/Network/Native Other/SESSION_INFO_0.cs new file mode 100644 index 000000000..9c07dd82a --- /dev/null +++ b/AlphaFS/Network/Native Other/SESSION_INFO_0.cs @@ -0,0 +1,40 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Contains the name of the computer that established the session. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct SESSION_INFO_0 + { + /// Pointer to a Unicode string that contains the name of the computer that established the session. This string cannot contain a backslash (\). + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi0_cname; + } + } +} diff --git a/AlphaFS/Network/Native Other/SESSION_INFO_1.cs b/AlphaFS/Network/Native Other/SESSION_INFO_1.cs new file mode 100644 index 000000000..9ca50b025 --- /dev/null +++ b/AlphaFS/Network/Native Other/SESSION_INFO_1.cs @@ -0,0 +1,59 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Contains information about the session, including name of the computer; name of the user; and open files, pipes, and devices on the computer. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct SESSION_INFO_1 + { + /// Pointer to a Unicode string specifying the name of the computer that established the session. This string cannot contain a backslash (\). + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi1_cname; + + /// Pointer to a Unicode string specifying the name of the user who established the session. + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi1_username; + + /// Specifies a DWORD value that contains the number of files, devices, and pipes opened during the session. + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi1_num_opens; + + /// Specifies a DWORD value that contains the number of seconds the session has been active. + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi1_time; + + /// Specifies a DWORD value that contains the number of seconds the session has been idle. + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi1_idle_time; + + /// + /// Specifies a DWORD value that describes how the user established the session. This member can be one of the following values: + /// SESS_GUEST: The user specified by the member established the session using a guest account. + /// SESS_NOENCRYPTION: The user specified by the member established the session without using password encryption. + /// + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi1_user_flags; + } + } +} diff --git a/AlphaFS/Network/Native Other/SESSION_INFO_10.cs b/AlphaFS/Network/Native Other/SESSION_INFO_10.cs new file mode 100644 index 000000000..5731ee586 --- /dev/null +++ b/AlphaFS/Network/Native Other/SESSION_INFO_10.cs @@ -0,0 +1,49 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Contains information about the session, including name of the computer; name of the user; and active and idle times for the session. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct SESSION_INFO_10 + { + /// Pointer to a Unicode string specifying the name of the computer that established the session. This string cannot contain a backslash (\). + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi10_cname; + + /// Pointer to a Unicode string specifying the name of the user who established the session. + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi10_username; + + /// Specifies the number of seconds the session has been active. + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi10_time; + + /// Specifies the number of seconds the session has been idle. + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi10_idle_time; + } + } +} diff --git a/AlphaFS/Network/Native Other/SESSION_INFO_2.cs b/AlphaFS/Network/Native Other/SESSION_INFO_2.cs new file mode 100644 index 000000000..8ce824dc7 --- /dev/null +++ b/AlphaFS/Network/Native Other/SESSION_INFO_2.cs @@ -0,0 +1,70 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// 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. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct SESSION_INFO_2 + { + /// Pointer to a Unicode string specifying the name of the computer that established the session. This string cannot contain a backslash (\). + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi2_cname; + + /// Pointer to a Unicode string specifying the name of the user who established the session. + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi2_username; + + /// Specifies a DWORD value that contains the number of files, devices, and pipes opened during the session. + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi2_num_opens; + + /// Specifies a DWORD value that contains the number of seconds the session has been active. + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi2_time; + + /// Specifies a DWORD value that contains the number of seconds the session has been idle. + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi2_idle_time; + + /// + /// Specifies a DWORD value that describes how the user established the session. This member can be one of the following values: + /// SESS_GUEST: The user specified by the member established the session using a guest account. + /// SESS_NOENCRYPTION: The user specified by the member established the session without using password encryption. + /// + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi2_user_flags; + + + /// + /// Pointer to a Unicode string that specifies the type of client that established the session. Following are the defined types for LAN Manager servers: + /// DOS LM 1.0: LAN Manager for MS-DOS 1.0 clients + /// DOS LM 2.0: LAN Manager for MS-DOS 2.0 clients + /// OS/2 LM 1.0: LAN Manager for MS-OS/2 1.0 clients + /// OS/2 LM 2.0: LAN Manager for MS-OS/2 2.0 clients + /// Sessions from LAN Manager servers running UNIX also will appear as LAN Manager 2.0. + /// + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi2_cltype_name; + } + } +} diff --git a/AlphaFS/Network/Native Other/SESSION_INFO_502.cs b/AlphaFS/Network/Native Other/SESSION_INFO_502.cs new file mode 100644 index 000000000..6e02fe29b --- /dev/null +++ b/AlphaFS/Network/Native Other/SESSION_INFO_502.cs @@ -0,0 +1,73 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// 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. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct SESSION_INFO_502 + { + /// Pointer to a Unicode string specifying the name of the computer that established the session. This string cannot contain a backslash (\). + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi502_cname; + + /// Pointer to a Unicode string specifying the name of the user who established the session. + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi502_username; + + /// Specifies the number of files, devices, and pipes opened during the session. + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi502_num_opens; + + /// Specifies the number of seconds the session has been active. + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi502_time; + + /// Specifies the number of seconds the session has been idle. + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi502_idle_time; + + /// + /// Specifies a value that describes how the user established the session. This member can be one of the following values: + /// SESS_GUEST: The user specified by the member established the session using a guest account. + /// SESS_NOENCRYPTION: The user specified by the member established the session without using password encryption. + /// + [MarshalAs(UnmanagedType.U4)] public readonly uint sesi502_user_flags; + + /// + /// Pointer to a Unicode string that specifies the type of client that established the session. Following are the defined types for LAN Manager servers: + /// DOS LM 1.0: LAN Manager for MS-DOS 1.0 clients + /// DOS LM 2.0: LAN Manager for MS-DOS 2.0 clients + /// OS/2 LM 1.0: LAN Manager for MS-OS/2 1.0 clients + /// OS/2 LM 2.0: LAN Manager for MS-OS/2 2.0 clients + /// Sessions from LAN Manager servers running UNIX also will appear as LAN Manager 2.0. + /// + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi502_cltype_name; + + + /// Specifies the name of the transport that the client is using to communicate with the server. + [MarshalAs(UnmanagedType.LPWStr)] public readonly string sesi502_transport; + } + } +} diff --git a/AlphaFS/Network/SessionInfo.cs b/AlphaFS/Network/SessionInfo.cs new file mode 100644 index 000000000..404fd7e65 --- /dev/null +++ b/AlphaFS/Network/SessionInfo.cs @@ -0,0 +1,135 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Contains information about Server Message Block (SMB) shares. This class cannot be inherited. + [Serializable] + public sealed class SessionInfo + { + #region Constructor + + /// Creates a instance. + /// The DNS or NetBIOS name of the specified host. + /// One of the options. + /// A , , , or instance. + internal SessionInfo(string hostName, SessionInfoLevel sessionInfoLevel, object sessionInfo) + { + hostName = hostName ?? Environment.MachineName; + + + switch (sessionInfoLevel) + { + case SessionInfoLevel.Info502: + var sesi502 = (NativeMethods.SESSION_INFO_502) sessionInfo; + HostName = sesi502.sesi502_cname; + break; + + case SessionInfoLevel.Info2: + var sesi2 = (NativeMethods.SESSION_INFO_2) sessionInfo; + HostName = sesi2.sesi2_cname; + break; + + case SessionInfoLevel.Info1: + var sesi1 = (NativeMethods.SESSION_INFO_1) sessionInfo; + HostName = sesi1.sesi1_cname; + break; + + case SessionInfoLevel.Info10: + var sesi10 = (NativeMethods.SESSION_INFO_10) sessionInfo; + HostName = sesi10.sesi10_cname; + break; + + case SessionInfoLevel.Info0: + var sesi0 = (NativeMethods.SESSION_INFO_0) sessionInfo; + HostName = sesi0.sesi0_cname; + break; + } + + + SessionInfoLevel = sessionInfoLevel; + } + + #endregion // Constructor + + + #region Methods + + /// Returns the host name of this session information. + /// A string that represents this instance. + public override string ToString() + { + return HostName; + } + + #endregion // Methods + + + #region Properties + + /// The number of current connections to the resource. + public long CurrentUses { get; private set; } + + + /// The maximum number of concurrent connections that the shared resource can accommodate. + /// The number of connections is unlimited if the value specified in this member is –1. + public long MaxUses { get; private set; } + + + /// The name of a shared resource. + public string NetName { get; private set; } + + + /// The share's password (when the server is running with share-level security). + public string Password { get; private set; } + + + /// The local path for the shared resource. + /// For disks, this member is the path being shared. For print queues, this member is the name of the print queue being shared. + public string Path { get; private set; } + + + /// The shared resource's permissions for servers running with share-level security. + /// Note that Windows does not support share-level security. This member is ignored on a server running user-level security. + public AccessPermissions Permissions { get; private set; } + + + /// An optional comment about the shared resource. + public string Remark { get; private set; } + + + /// Specifies the SECURITY_DESCRIPTOR associated with this share. + public IntPtr SecurityDescriptor { get; private set; } + + + /// A pointer to a string that specifies the DNS or NetBIOS name of the remote server on which the shared resource resides. + /// A value of "*" indicates no configured server name. + public string HostName { get; private set; } + + + /// The structure level for the SessionInfo instance. + public SessionInfoLevel SessionInfoLevel { get; private set; } + + #endregion // Properties + } +} From e07bd9b9aedb63842803341fcaaa6c7d2ffde93d Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 11 Feb 2018 12:23:35 +0100 Subject: [PATCH 037/133] Code improvement, work in progress. --- .../Host Class/Host.SMB.EnumerateSessions.cs | 41 +++++----- .../Host Class/Host.SMB.GetNetStatistics.cs | 5 +- AlphaFS/Network/SessionInfo.cs | 81 ++++++++++++------- AlphaFS/Network/WorkstationStatisticsInfo.cs | 14 ++++ 4 files changed, 91 insertions(+), 50 deletions(-) diff --git a/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs b/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs index 3892d40e1..4753c0059 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs @@ -34,44 +34,45 @@ partial class Host [SecurityCritical] public static IEnumerable EnumerateSessions() { - return EnumerateSessionsCore(Environment.MachineName); + return EnumerateSessionsCore(Environment.MachineName, null, null); } /// [AlphaFS] Enumerates sessions established on the specified . /// An collection from the specified . - /// The DNS or NetBIOS name of the specified host. + /// The DNS or NetBIOS name of the specified host. If this parameter is NULL, the local Computer is used. [SecurityCritical] public static IEnumerable EnumerateSessions(string hostName) { - return EnumerateSessionsCore(hostName); + return EnumerateSessionsCore(hostName, null, null); } /// [AlphaFS] Enumerates sessions established on the specified . /// An collection from the specified . /// - /// The DNS or NetBIOS name of the specified host. + /// The DNS or NetBIOS name of the specified host. If this parameter is NULL, the local Computer is used. + /// The name of the Computer session for which information is to be returned. If this parameter is NULL, NetSessionEnum returns information for all Computer sessions on the server. + /// The name of the user for which information is to be returned. If this parameter is NULL, NetSessionEnum returns information for all users. [SecurityCritical] - internal static IEnumerable EnumerateSessionsCore(string hostName) + internal static IEnumerable EnumerateSessionsCore(string hostName, string clientName, string userName) { var fd = new FunctionData(); var hasItems = false; - // 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(hostName) ? Environment.MachineName : Path.GetRegularPathCore(hostName, GetFullPathOptions.CheckInvalidPathChars, false).Replace(Path.UncPrefix, string.Empty); + + // hostName is allowed to be null. + + var stripUnc = !Utils.IsNullOrWhiteSpace(hostName) ? Path.GetRegularPathCore(hostName, GetFullPathOptions.CheckInvalidPathChars, false).Replace(Path.UncPrefix, string.Empty) : null; // Try SESSION_INFO_502 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_502 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info502, structure), + foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_502 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(SessionInfoLevel.Info502, structure), (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => - NativeMethods.NetSessionEnum(stripUnc, null, null, SessionInfoLevel.Info502, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true)) + NativeMethods.NetSessionEnum(stripUnc, clientName, userName, SessionInfoLevel.Info502, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true)) { yield return sessionInfo; hasItems = true; @@ -83,11 +84,11 @@ internal static IEnumerable EnumerateSessionsCore(string hostName) // Fallback on SESSION_INFO_2 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_2 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info2, structure), + foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_2 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(SessionInfoLevel.Info2, structure), (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => - NativeMethods.NetSessionEnum(stripUnc, null, null, SessionInfoLevel.Info2, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true)) + NativeMethods.NetSessionEnum(stripUnc, clientName, userName, SessionInfoLevel.Info2, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true)) { yield return sessionInfo; hasItems = true; @@ -99,11 +100,11 @@ internal static IEnumerable EnumerateSessionsCore(string hostName) // Fallback on SHARE_INFO_1 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_1 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info1, structure), + foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_1 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(SessionInfoLevel.Info1, structure), (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => - NativeMethods.NetSessionEnum(stripUnc, null, null, SessionInfoLevel.Info1, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true)) + NativeMethods.NetSessionEnum(stripUnc, clientName, userName, SessionInfoLevel.Info1, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true)) { yield return sessionInfo; hasItems = true; @@ -115,11 +116,11 @@ internal static IEnumerable EnumerateSessionsCore(string hostName) // Fallback on SESSION_INFO_10 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_10 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info10, structure), + foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_10 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(SessionInfoLevel.Info10, structure), (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => - NativeMethods.NetSessionEnum(stripUnc, null, null, SessionInfoLevel.Info10, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true)) + NativeMethods.NetSessionEnum(stripUnc, clientName, userName, SessionInfoLevel.Info10, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true)) { yield return sessionInfo; hasItems = true; @@ -131,11 +132,11 @@ internal static IEnumerable EnumerateSessionsCore(string hostName) // Fallback on SESSION_INFO_0 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_0 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info0, structure), + foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_0 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(SessionInfoLevel.Info0, structure), (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => - NativeMethods.NetSessionEnum(stripUnc, null, null, SessionInfoLevel.Info0, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true)) + NativeMethods.NetSessionEnum(stripUnc, clientName, userName, SessionInfoLevel.Info0, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), true)) { yield return sessionInfo; } diff --git a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs index 4b2d1c413..9325a025f 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs @@ -22,6 +22,7 @@ using System; using System.Net.NetworkInformation; using System.Security; +using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network { @@ -97,7 +98,9 @@ internal static T GetNetStatisticsNative(bool isServer, string hostName) // hostName is allowed to be null. - var lastError = NativeMethods.NetStatisticsGet(hostName, isServer ? "LanmanServer" : "LanmanWorkstation", 0, 0, out safeBuffer); + 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) diff --git a/AlphaFS/Network/SessionInfo.cs b/AlphaFS/Network/SessionInfo.cs index 404fd7e65..0bfed723d 100644 --- a/AlphaFS/Network/SessionInfo.cs +++ b/AlphaFS/Network/SessionInfo.cs @@ -30,12 +30,11 @@ public sealed class SessionInfo #region Constructor /// Creates a instance. - /// The DNS or NetBIOS name of the specified host. /// One of the options. /// A , , , or instance. - internal SessionInfo(string hostName, SessionInfoLevel sessionInfoLevel, object sessionInfo) + internal SessionInfo(SessionInfoLevel sessionInfoLevel, object sessionInfo) { - hostName = hostName ?? Environment.MachineName; + SessionInfoLevel = sessionInfoLevel; switch (sessionInfoLevel) @@ -43,31 +42,53 @@ internal SessionInfo(string hostName, SessionInfoLevel sessionInfoLevel, object case SessionInfoLevel.Info502: var sesi502 = (NativeMethods.SESSION_INFO_502) sessionInfo; HostName = sesi502.sesi502_cname; + UserName = sesi502.sesi502_username; + OpenedResources = (int) sesi502.sesi502_num_opens; + ActiveTime = (int) sesi502.sesi502_time; + IdleTime = (int) sesi502.sesi502_idle_time; + //Flags = (int) sesi502.sesi502_user_flags; + ClientType = sesi502.sesi502_cltype_name; + TransportType = sesi502.sesi502_transport; break; + case SessionInfoLevel.Info2: var sesi2 = (NativeMethods.SESSION_INFO_2) sessionInfo; HostName = sesi2.sesi2_cname; + UserName = sesi2.sesi2_username; + OpenedResources = (int) sesi2.sesi2_num_opens; + ActiveTime = (int) sesi2.sesi2_time; + IdleTime = (int) sesi2.sesi2_idle_time; + //Flags = (int) sesi2.sesi2_user_flags; + ClientType = sesi2.sesi2_cltype_name; break; + case SessionInfoLevel.Info1: var sesi1 = (NativeMethods.SESSION_INFO_1) sessionInfo; HostName = sesi1.sesi1_cname; + UserName = sesi1.sesi1_username; + OpenedResources = (int) sesi1.sesi1_num_opens; + ActiveTime = (int) sesi1.sesi1_time; + IdleTime = (int) sesi1.sesi1_idle_time; + //Flags = (int) sesi1.sesi1_user_flags; break; + case SessionInfoLevel.Info10: var sesi10 = (NativeMethods.SESSION_INFO_10) sessionInfo; HostName = sesi10.sesi10_cname; + UserName = sesi10.sesi10_username; + ActiveTime = (int) sesi10.sesi10_time; + IdleTime = (int) sesi10.sesi10_idle_time; break; + case SessionInfoLevel.Info0: var sesi0 = (NativeMethods.SESSION_INFO_0) sessionInfo; HostName = sesi0.sesi0_cname; break; } - - - SessionInfoLevel = sessionInfoLevel; } #endregion // Constructor @@ -87,47 +108,49 @@ public override string ToString() #region Properties - /// The number of current connections to the resource. - public long CurrentUses { get; private set; } + /// The name of the Computer that established the session.. + public string HostName { get; private set; } - /// The maximum number of concurrent connections that the shared resource can accommodate. - /// The number of connections is unlimited if the value specified in this member is –1. - public long MaxUses { get; private set; } + /// The name of the User who established the session. + public string UserName { get; private set; } - /// The name of a shared resource. - public string NetName { get; private set; } + /// The number of files, devices, and pipes opened during the session. + public int OpenedResources { get; private set; } - /// The share's password (when the server is running with share-level security). - public string Password { get; private set; } + /// The number of seconds the session has been active. + public int ActiveTime { get; private set; } - /// The local path for the shared resource. - /// For disks, this member is the path being shared. For print queues, this member is the name of the print queue being shared. - public string Path { get; private set; } + /// The number of seconds the session has been idle. + public int IdleTime { get; private set; } - /// The shared resource's permissions for servers running with share-level security. - /// Note that Windows does not support share-level security. This member is ignored on a server running user-level security. - public AccessPermissions Permissions { get; private set; } + ///// + ///// Specifies a value that describes how the user established the session. This member can be one of the following values: + ///// SESS_GUEST: The user specified by the member established the session using a guest account. + ///// SESS_NOENCRYPTION: The user specified by the member established the session without using password encryption. + ///// + ////public int Flags { get; private set; } + /// A value that describes how the User established the session. + public bool IsGuest { get; private set; } - /// An optional comment about the shared resource. - public string Remark { get; private set; } + /// A value that describes how the User established the session. + public bool IsEncrypted { get; private set; } - /// Specifies the SECURITY_DESCRIPTOR associated with this share. - public IntPtr SecurityDescriptor { get; private set; } + /// The type of client that established the session. Sessions from LAN Manager servers running UNIX also will appear as LAN Manager 2.0. + public string ClientType { get; private set; } - /// A pointer to a string that specifies the DNS or NetBIOS name of the remote server on which the shared resource resides. - /// A value of "*" indicates no configured server name. - public string HostName { get; private set; } + /// The name of the transport that the client is using to communicate with the server. + public string TransportType { get; private set; } - /// The structure level for the SessionInfo instance. + /// The structure level for the instance. public SessionInfoLevel SessionInfoLevel { get; private set; } #endregion // Properties diff --git a/AlphaFS/Network/WorkstationStatisticsInfo.cs b/AlphaFS/Network/WorkstationStatisticsInfo.cs index 3a334c869..89c1a6355 100644 --- a/AlphaFS/Network/WorkstationStatisticsInfo.cs +++ b/AlphaFS/Network/WorkstationStatisticsInfo.cs @@ -20,6 +20,7 @@ */ using System; +using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Network { @@ -167,6 +168,7 @@ public int HungSessions /// The total number of connections to servers supporting the LanManager 2.0 dialect that have succeeded. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lanman")] public int Lanman20Connects { get { return (int) _workstationStat.Lanman20Connects; } @@ -174,6 +176,7 @@ public int Lanman20Connects /// The total number of connections to servers supporting the LanManager 2.1 dialect that have succeeded. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lanman")] public int Lanman21Connects { get { return (int) _workstationStat.Lanman21Connects; } @@ -181,6 +184,9 @@ public int Lanman21Connects /// The total number of connections to servers supporting the NTLM dialect that have succeeded. + [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; } @@ -188,6 +194,7 @@ public int LanmanNtConnects /// 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. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")] public int LargeReadSmbs { get { return (int) _workstationStat.LargeReadSmbs; } @@ -195,6 +202,7 @@ public int LargeReadSmbs /// 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. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")] public int LargeWriteSmbs { get { return (int) _workstationStat.LargeWriteSmbs; } @@ -328,6 +336,7 @@ public int ReadOperations /// The total number of read requests the workstation has sent to servers. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")] public int ReadSmbs { get { return (int) _workstationStat.ReadSmbs; } @@ -356,6 +365,7 @@ public int Sessions /// 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. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")] public int SmallReadSmbs { get { return (int) _workstationStat.SmallReadSmbs; } @@ -363,6 +373,7 @@ public int SmallReadSmbs /// 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. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")] public int SmallWriteSmbs { get { return (int) _workstationStat.SmallWriteSmbs; } @@ -384,6 +395,7 @@ public DateTime StatisticsStartTimeUtc /// The total number of server message blocks (SMBs) received by the workstation. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")] public long SmbsReceived { get { return _workstationStat.SmbsReceived; } @@ -391,6 +403,7 @@ public long SmbsReceived /// The total number of SMBs transmitted by the workstation. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")] public long SmbsTransmitted { get { return _workstationStat.SmbsTransmitted; } @@ -412,6 +425,7 @@ public int WriteOperations /// The total number of write requests the workstation has sent to servers. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")] public int WriteSmbs { get { return (int) _workstationStat.WriteSmbs; } From 0b290171534fd8ad4b61b2076cf7406f37afe158 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 11 Feb 2018 17:33:35 +0100 Subject: [PATCH 038/133] Code improvement. --- .../AlphaFS_Host.EnumerateSessions.cs | 10 +- .../AlphaFS_Host_EnumerateOpenConnections.cs | 12 +-- .../AlphaFS_Host_EnumerateOpenResources.cs | 18 +--- .../AlphaFS_Host_EnumerateShares.cs | 8 +- .../AlphaFS_Host_GetUncName.cs | 2 +- .../Host Class/Host.SMB.EnumerateSessions.cs | 47 +++++++-- AlphaFS/Network/OpenConnectionInfo.cs | 36 +++++-- AlphaFS/Network/OpenResourceInfo.cs | 22 +++-- AlphaFS/Network/ServerStatisticsInfo.cs | 4 +- AlphaFS/Network/SessionInfo.cs | 95 +++++++++++++------ AlphaFS/Network/ShareInfo.cs | 2 +- AlphaFS/Network/WorkstationStatisticsInfo.cs | 4 +- AlphaFS/Win32Errors.cs | 4 +- 13 files changed, 175 insertions(+), 89 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs index 06554d4e3..ff1590995 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs @@ -32,16 +32,16 @@ public partial class AlphaFS_HostTest public void AlphaFS_Host_EnumerateSessions_Local_Success() { var host = UnitTestConstants.LocalHost; - - EnumerateSessions(host, true); + + EnumerateSessions(host); } - private void EnumerateSessions(string host, bool isNetwork) + private void EnumerateSessions(string host) { - UnitTestConstants.PrintUnitTestHeader(isNetwork); + UnitTestConstants.PrintUnitTestHeader(false); Console.WriteLine("\nInput Host: [{0}]", host); @@ -52,7 +52,7 @@ private void EnumerateSessions(string host, bool isNetwork) { //Console.WriteLine("\n\t#{0:000}\tShare: [{1}]", ++cnt, shareInfo); - if (UnitTestConstants.Dump(sessionsInfo, -18)) + if (UnitTestConstants.Dump(sessionsInfo, -16)) sessionCount++; Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateOpenConnections.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateOpenConnections.cs index 13a54ec0e..aadde9eb8 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateOpenConnections.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateOpenConnections.cs @@ -29,16 +29,16 @@ public partial class AlphaFS_HostTest // Pattern: ___ [TestMethod] - public void AlphaFS_Host_EnumerateOpenConnections_Network_Success() + public void AlphaFS_Host_EnumerateOpenConnections_Local_Success() { - var host = "localhost"; //UnitTestConstants.LocalHost; + var host = UnitTestConstants.LocalHost; var share = UnitTestConstants.SysDrive[0] + Alphaleonis.Win32.Filesystem.Path.NetworkDriveSeparator; // Create an active connection to the "remote" host. var currentDir = System.IO.Directory.GetCurrentDirectory(); - System.IO.Directory.SetCurrentDirectory(@"\\" + host + @"\" + share); + System.IO.Directory.SetCurrentDirectory(Alphaleonis.Win32.Filesystem.Path.UncPrefix + host + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator + share); - EnumerateOpenConnections(host, share, true); + EnumerateOpenConnections(host, share); System.IO.Directory.SetCurrentDirectory(currentDir); } @@ -46,9 +46,9 @@ public void AlphaFS_Host_EnumerateOpenConnections_Network_Success() - private void EnumerateOpenConnections(string host, string share, bool isNetwork) + private void EnumerateOpenConnections(string host, string share) { - UnitTestConstants.PrintUnitTestHeader(isNetwork); + UnitTestConstants.PrintUnitTestHeader(false); if (!UnitTestConstants.IsAdmin()) Assert.Inconclusive(); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateOpenResources.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateOpenResources.cs index bb3c79e2f..93641be60 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateOpenResources.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateOpenResources.cs @@ -29,27 +29,19 @@ public partial class AlphaFS_HostTest // Pattern: ___ [TestMethod] - public void AlphaFS_Host_EnumerateOpenResources_Network_Success() + public void AlphaFS_Host_EnumerateOpenResources_Local_Success() { - var host = "localhost"; //UnitTestConstants.LocalHost; - var share = UnitTestConstants.SysDrive[0] + Alphaleonis.Win32.Filesystem.Path.NetworkDriveSeparator; + var host = UnitTestConstants.LocalHost; - // Create an active connection to the "remote" host. - var currentDir = System.IO.Directory.GetCurrentDirectory(); - System.IO.Directory.SetCurrentDirectory(@"\\" + host + @"\" + share); - - //EnumerateOpenResources(UnitTestConstants.LocalHost, true); - EnumerateOpenResources(host, true); - - System.IO.Directory.SetCurrentDirectory(currentDir); + EnumerateOpenResources(host); } - private void EnumerateOpenResources(string host, bool isNetwork) + private void EnumerateOpenResources(string host) { - UnitTestConstants.PrintUnitTestHeader(isNetwork); + UnitTestConstants.PrintUnitTestHeader(false); if (!UnitTestConstants.IsAdmin()) Assert.Inconclusive(); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateShares.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateShares.cs index d476d3b0a..7d074a1ea 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateShares.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_EnumerateShares.cs @@ -29,19 +29,19 @@ public partial class AlphaFS_HostTest // Pattern: ___ [TestMethod] - public void AlphaFS_Host_EnumerateShares_Network_Success() + public void AlphaFS_Host_EnumerateShares_Local_Success() { var host = UnitTestConstants.LocalHost; - EnumerateShares(host, true); + EnumerateShares(host); } - private void EnumerateShares(string host, bool isNetwork) + private void EnumerateShares(string host) { - UnitTestConstants.PrintUnitTestHeader(isNetwork); + UnitTestConstants.PrintUnitTestHeader(false); Console.WriteLine("\nInput Host: [{0}]", host); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_GetUncName.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_GetUncName.cs index 39580b5c1..d70bbf9bd 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_GetUncName.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host_GetUncName.cs @@ -37,7 +37,7 @@ public void AlphaFS_Host_GetUncName_Network_Success() Console.WriteLine("Host.GetUncName(): [{0}]", hostUncName); - Assert.IsTrue(hostUncName.StartsWith(@"\\")); + Assert.IsTrue(hostUncName.StartsWith(Alphaleonis.Win32.Filesystem.Path.UncPrefix)); Assert.AreEqual(Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName, hostUncName); } diff --git a/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs b/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs index 4753c0059..e930a10fa 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs @@ -40,7 +40,7 @@ public static IEnumerable EnumerateSessions() /// [AlphaFS] Enumerates sessions established on the specified . /// An collection from the specified . - /// The DNS or NetBIOS name of the specified host. If this parameter is NULL, the local Computer is used. + /// The DNS or NetBIOS name of the specified host. If this parameter is null, the local Computer is used. [SecurityCritical] public static IEnumerable EnumerateSessions(string hostName) { @@ -48,12 +48,37 @@ public static IEnumerable EnumerateSessions(string hostName) } + /// [AlphaFS] Enumerates sessions established on the specified . + /// An collection from the specified . + /// The DNS or NetBIOS name of the specified host. If this parameter is null, the local Computer is used. + /// The name of the Computer session for which information is to be returned. If this parameter is null, information for all Computer sessions on the server is returned. + [SecurityCritical] + public static IEnumerable EnumerateSessions(string hostName, string clientName) + { + return EnumerateSessionsCore(hostName, clientName, null); + } + + + /// [AlphaFS] Enumerates sessions established on the specified . + /// An collection from the specified . + /// The DNS or NetBIOS name of the specified host. If this parameter is null, the local Computer is used. + /// The name of the Computer session for which information is to be returned. If this parameter is null, information for all Computer sessions on the server is returned. + /// The name of the user for which information is to be returned. If this parameter is null, information for all users is returned. + [SecurityCritical] + public static IEnumerable EnumerateSessions(string hostName, string clientName, string userName) + { + return EnumerateSessionsCore(hostName, clientName, userName); + } + + + + /// [AlphaFS] Enumerates sessions established on the specified . /// An collection from the specified . /// - /// The DNS or NetBIOS name of the specified host. If this parameter is NULL, the local Computer is used. - /// The name of the Computer session for which information is to be returned. If this parameter is NULL, NetSessionEnum returns information for all Computer sessions on the server. - /// The name of the user for which information is to be returned. If this parameter is NULL, NetSessionEnum returns information for all users. + /// The DNS or NetBIOS name of the specified host. If this parameter is null, the local Computer is used. + /// The name of the Computer session for which information is to be returned. If this parameter is null, information for all Computer sessions on the server is returned. + /// The name of the user for which information is to be returned. If this parameter is null, information for all users is returned. [SecurityCritical] internal static IEnumerable EnumerateSessionsCore(string hostName, string clientName, string userName) { @@ -62,13 +87,15 @@ internal static IEnumerable EnumerateSessionsCore(string hostName, // 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; - // Try SESSION_INFO_502 structure. + // Start with SESSION_INFO_502 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_502 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(SessionInfoLevel.Info502, structure), + foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_502 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info502, structure), (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => @@ -84,7 +111,7 @@ internal static IEnumerable EnumerateSessionsCore(string hostName, // Fallback on SESSION_INFO_2 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_2 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(SessionInfoLevel.Info2, structure), + foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_2 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info2, structure), (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => @@ -100,7 +127,7 @@ internal static IEnumerable EnumerateSessionsCore(string hostName, // Fallback on SHARE_INFO_1 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_1 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(SessionInfoLevel.Info1, structure), + foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_1 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info1, structure), (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => @@ -116,7 +143,7 @@ internal static IEnumerable EnumerateSessionsCore(string hostName, // Fallback on SESSION_INFO_10 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_10 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(SessionInfoLevel.Info10, structure), + foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_10 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info10, structure), (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => @@ -132,7 +159,7 @@ internal static IEnumerable EnumerateSessionsCore(string hostName, // Fallback on SESSION_INFO_0 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_0 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(SessionInfoLevel.Info0, structure), + foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_0 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info0, structure), (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => diff --git a/AlphaFS/Network/OpenConnectionInfo.cs b/AlphaFS/Network/OpenConnectionInfo.cs index df3863e7b..53279d90d 100644 --- a/AlphaFS/Network/OpenConnectionInfo.cs +++ b/AlphaFS/Network/OpenConnectionInfo.cs @@ -29,23 +29,33 @@ namespace Alphaleonis.Win32.Network [Serializable] public sealed class OpenConnectionInfo { + #region Private Fields + + private string _netName; + + #endregion // Private Fields + + #region Constructor /// Create an OpenConnectionInfo instance. - internal OpenConnectionInfo(string host, NativeMethods.CONNECTION_INFO_1 connectionInfo) + internal OpenConnectionInfo(string hostName, NativeMethods.CONNECTION_INFO_1 connectionInfo) { - Host = host; + Host = hostName; + HostName = hostName; Id = connectionInfo.coni1_id; ShareType = connectionInfo.coni1_type; TotalOpenFiles = connectionInfo.coni1_num_opens; TotalUsers = connectionInfo.coni1_num_users; ConnectedSeconds = connectionInfo.coni1_time; + ConnectedTime = TimeSpan.FromSeconds(connectionInfo.coni1_time); UserName = connectionInfo.coni1_username; - NetName = connectionInfo.oni1_netname.Replace(Path.LongPathUncPrefix, string.Empty).Replace(Path.UncPrefix, string.Empty); + NetName = connectionInfo.oni1_netname; } #endregion // Constructor + #region Methods /// Returns the full path to the share. @@ -57,11 +67,16 @@ public override string ToString() #endregion // Methods + #region Properties /// The local or remote Host. + [Obsolete("Use HostName")] public string Host { get; private set; } + /// The host name of this connection information. + public string HostName { get; private set; } + /// Specifies a connection identification number. public long Id { get; private set; } @@ -75,13 +90,22 @@ public override string ToString() public long TotalUsers { get; private set; } /// Specifies the number of seconds that the connection has been established. + [Obsolete("Use ConnectedTime property.")] public long ConnectedSeconds { get; private set; } - /// If the server sharing the resource is running with user-level security, the UserName member describes which user made the connection. If the server is running with share-level security, coni1_username describes which computer (computername) made the connection. + /// Specifies duration that the connection has been established. + public TimeSpan ConnectedTime { get; private set; } + + /// If the server sharing the resource is running with user-level security, the UserName member describes which user made the connection. If the server is running with share-level security, UserName describes which Computer (Computer name) made the connection. public string UserName { get; private set; } + + /// Specifies either the server's shared resource name or the Computer name or IP address of the client. The value of this member depends on which name was specified as the qualifier parameter to the function. + public string NetName + { + get { return _netName; } - /// String that specifies either the share name of the server's shared resource or the computername of the client. The value of this member depends on which name was specified as the qualifier parameter to the NetConnectionEnum function. - public string NetName { get; private set; } + set { _netName = null != value ? value.Replace(Path.LongPathUncPrefix, string.Empty).Replace(Path.UncPrefix, string.Empty).Trim('[', ']') : null; } + } #endregion // Properties } diff --git a/AlphaFS/Network/OpenResourceInfo.cs b/AlphaFS/Network/OpenResourceInfo.cs index 106a13bcb..5e2398da6 100644 --- a/AlphaFS/Network/OpenResourceInfo.cs +++ b/AlphaFS/Network/OpenResourceInfo.cs @@ -21,6 +21,7 @@ using System; using System.Globalization; +using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network { @@ -30,28 +31,32 @@ public sealed class OpenResourceInfo { #region Constructor - /// Create a OpenResourceInfo instance. - internal OpenResourceInfo(string host, NativeMethods.FILE_INFO_3 fileInfo) + /// Create an OpenResourceInfo instance. + internal OpenResourceInfo(string hostName, NativeMethods.FILE_INFO_3 fileInfo) { - Host = host; + Host = hostName; + HostName = hostName; Id = fileInfo.fi3_id; Permissions = fileInfo.fi3_permissions; TotalLocks = fileInfo.fi3_num_locks; - PathName = fileInfo.fi3_pathname.Replace(@"\\", @"\"); + PathName = fileInfo.fi3_pathname.Replace(Path.UncPrefix, Path.DirectorySeparator); UserName = fileInfo.fi3_username; } #endregion // Constructor + #region Methods /// Forces the open resource to close. /// You should this method with caution because it does not write data cached on the client system to the file before closing the file. public void Close() { - uint lastError = NativeMethods.NetFileClose(Host, (uint) Id); + var lastError = NativeMethods.NetFileClose(HostName, (uint) Id); + if (lastError != Win32Errors.NERR_Success && lastError != Win32Errors.NERR_FileIdNotFound) - NativeError.ThrowException(lastError, Host, PathName); + + NativeError.ThrowException(lastError, HostName, PathName); } /// Returns the full path to the share. @@ -63,11 +68,16 @@ public override string ToString() #endregion // Methods + #region Properties /// The local or remote Host. + [Obsolete("Use HostName")] public string Host { get; private set; } + /// The host name of this resource information. + public string HostName { get; private set; } + /// The identification number assigned to the resource when it is opened. public long Id { get; private set; } diff --git a/AlphaFS/Network/ServerStatisticsInfo.cs b/AlphaFS/Network/ServerStatisticsInfo.cs index 1c685ea0b..e6155142a 100644 --- a/AlphaFS/Network/ServerStatisticsInfo.cs +++ b/AlphaFS/Network/ServerStatisticsInfo.cs @@ -133,7 +133,7 @@ public int FilesOpened /// The host name from where the statistics are gathered. - public string HostName { get; } + public string HostName { get; private set; } /// The number of server print jobs spooled. @@ -241,7 +241,7 @@ public override int GetHashCode() /// The result of the operator. public static bool operator ==(ServerStatisticsInfo left, ServerStatisticsInfo right) { - return left is null && right is null || !(left is null) && !(right is null) && left.Equals(right); + return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); } diff --git a/AlphaFS/Network/SessionInfo.cs b/AlphaFS/Network/SessionInfo.cs index 0bfed723d..aaa8f229f 100644 --- a/AlphaFS/Network/SessionInfo.cs +++ b/AlphaFS/Network/SessionInfo.cs @@ -20,6 +20,8 @@ */ using System; +using System.Net; +using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network { @@ -27,68 +29,90 @@ namespace Alphaleonis.Win32.Network [Serializable] public sealed class SessionInfo { + #region Private Fields + + private string _netName; + + #endregion // Private Fields + + #region Constructor /// Creates a instance. + /// The DNS or NetBIOS name of the specified host. /// One of the options. - /// A , , , or instance. - internal SessionInfo(SessionInfoLevel sessionInfoLevel, object sessionInfo) + /// + /// A , , + /// , or instance. + /// + internal SessionInfo(string hostName, SessionInfoLevel sessionInfoLevel, object structure) { - SessionInfoLevel = sessionInfoLevel; + var flags = 0; switch (sessionInfoLevel) { case SessionInfoLevel.Info502: - var sesi502 = (NativeMethods.SESSION_INFO_502) sessionInfo; - HostName = sesi502.sesi502_cname; + var sesi502 = (NativeMethods.SESSION_INFO_502) structure; + NetName = sesi502.sesi502_cname; UserName = sesi502.sesi502_username; OpenedResources = (int) sesi502.sesi502_num_opens; - ActiveTime = (int) sesi502.sesi502_time; - IdleTime = (int) sesi502.sesi502_idle_time; - //Flags = (int) sesi502.sesi502_user_flags; + 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) sessionInfo; - HostName = sesi2.sesi2_cname; + var sesi2 = (NativeMethods.SESSION_INFO_2) structure; + NetName = sesi2.sesi2_cname; UserName = sesi2.sesi2_username; OpenedResources = (int) sesi2.sesi2_num_opens; - ActiveTime = (int) sesi2.sesi2_time; - IdleTime = (int) sesi2.sesi2_idle_time; - //Flags = (int) sesi2.sesi2_user_flags; + 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) sessionInfo; - HostName = sesi1.sesi1_cname; + var sesi1 = (NativeMethods.SESSION_INFO_1) structure; + NetName = sesi1.sesi1_cname; UserName = sesi1.sesi1_username; OpenedResources = (int) sesi1.sesi1_num_opens; - ActiveTime = (int) sesi1.sesi1_time; - IdleTime = (int) sesi1.sesi1_idle_time; - //Flags = (int) sesi1.sesi1_user_flags; + 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) sessionInfo; - HostName = sesi10.sesi10_cname; + var sesi10 = (NativeMethods.SESSION_INFO_10) structure; + NetName = sesi10.sesi10_cname; UserName = sesi10.sesi10_username; - ActiveTime = (int) sesi10.sesi10_time; - IdleTime = (int) sesi10.sesi10_idle_time; + 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) sessionInfo; - HostName = sesi0.sesi0_cname; + var sesi0 = (NativeMethods.SESSION_INFO_0) structure; + NetName = sesi0.sesi0_cname; break; } + + + HostName = hostName; + + SessionInfoLevel = sessionInfoLevel; + + // SESS_GUEST = 1, + // SESS_NOENCRYPTION = 2 + + GuestSession = flags == 1; + + EncryptedSession = !GuestSession && flags != 2; } #endregion // Constructor @@ -108,10 +132,19 @@ public override string ToString() #region Properties - /// The name of the Computer that established the session.. + /// The host name of this session information. public string HostName { get; private set; } + /// The Computer name or IP address that established the session. + public string NetName + { + get { return _netName; } + + set { _netName = null != value ? value.Replace(Path.LongPathUncPrefix, string.Empty).Replace(Path.UncPrefix, string.Empty).Trim('[', ']') : null; } + } + + /// The name of the User who established the session. public string UserName { get; private set; } @@ -120,12 +153,12 @@ public override string ToString() public int OpenedResources { get; private set; } - /// The number of seconds the session has been active. - public int ActiveTime { get; private set; } + /// The session active duration. + public TimeSpan ActiveTime { get; private set; } - /// The number of seconds the session has been idle. - public int IdleTime { get; private set; } + /// The session idle duration. + public TimeSpan IdleTime { get; private set; } ///// @@ -136,10 +169,10 @@ public override string ToString() ////public int Flags { get; private set; } /// A value that describes how the User established the session. - public bool IsGuest { get; private set; } + public bool GuestSession { get; private set; } /// A value that describes how the User established the session. - public bool IsEncrypted { get; private set; } + public bool EncryptedSession { get; private set; } /// The type of client that established the session. Sessions from LAN Manager servers running UNIX also will appear as LAN Manager 2.0. diff --git a/AlphaFS/Network/ShareInfo.cs b/AlphaFS/Network/ShareInfo.cs index 67d3e48d1..32cb85bad 100644 --- a/AlphaFS/Network/ShareInfo.cs +++ b/AlphaFS/Network/ShareInfo.cs @@ -152,7 +152,7 @@ public DirectoryInfo DirectoryInfo public long MaxUses { get; private set; } - /// The name of a shared resource. + /// The name of the shared resource. public string NetName { get; private set; } diff --git a/AlphaFS/Network/WorkstationStatisticsInfo.cs b/AlphaFS/Network/WorkstationStatisticsInfo.cs index 89c1a6355..457aa483e 100644 --- a/AlphaFS/Network/WorkstationStatisticsInfo.cs +++ b/AlphaFS/Network/WorkstationStatisticsInfo.cs @@ -150,7 +150,7 @@ public int FailedUseCount /// The host name from where the statistics are gathered. - public string HostName { get; } + public string HostName { get; private set; } /// The total number of network operations that failed to begin. @@ -479,7 +479,7 @@ public override int GetHashCode() /// The result of the operator. public static bool operator ==(WorkstationStatisticsInfo left, WorkstationStatisticsInfo right) { - return left is null && right is null || !(left is null) && !(right is null) && left.Equals(right); + return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); } diff --git a/AlphaFS/Win32Errors.cs b/AlphaFS/Win32Errors.cs index bb525e86b..73c5118b3 100644 --- a/AlphaFS/Win32Errors.cs +++ b/AlphaFS/Win32Errors.cs @@ -3942,10 +3942,10 @@ public static int GetHrFromWin32Error(uint errorCode) ///// Cannot open image file on the Remoteboot server. //public const uint NERR_CantOpenImageFile = 2514; - ///// Connecting to the Remoteboot server... + ///// Connecting to the Remoteboot server. //public const uint NERR_CallingRplSrvr = 2515; - ///// Connecting to the Remoteboot server... + ///// Connecting to the Remoteboot server. //public const uint NERR_StartingRplBoot = 2516; ///// Remote boot service was stopped; check the error log for the cause of the problem. From 32c91799c874e4c928274a7141dcf760b1725348 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 11 Feb 2018 17:39:21 +0100 Subject: [PATCH 039/133] Fixed project missing file. --- AlphaFS/AlphaFS.csproj | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 8cd8b02ec..963f0c2c3 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -552,7 +552,6 @@ - @@ -654,7 +653,7 @@ --> - + \ No newline at end of file From 1d075500eb0c8235ece9f30cbe1927b28a62557c Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 11 Feb 2018 18:35:58 +0100 Subject: [PATCH 040/133] Renamed SessionInfoLevel to SessionLevel. --- .../Host Class/Host.SMB.EnumerateSessions.cs | 10 ++-- .../Host Class/Host.SMB.EnumerateShares.cs | 56 ++++++++++--------- AlphaFS/Network/SessionInfo.cs | 13 ++--- AlphaFS/Network/ShareInfo.cs | 2 +- 4 files changed, 42 insertions(+), 39 deletions(-) diff --git a/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs b/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs index e930a10fa..15ae3b82f 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs @@ -95,7 +95,7 @@ internal static IEnumerable EnumerateSessionsCore(string hostName, // Start with SESSION_INFO_502 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_502 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info502, 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) => @@ -111,7 +111,7 @@ internal static IEnumerable EnumerateSessionsCore(string hostName, // Fallback on SESSION_INFO_2 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_2 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info2, 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) => @@ -127,7 +127,7 @@ internal static IEnumerable EnumerateSessionsCore(string hostName, // Fallback on SHARE_INFO_1 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_1 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info1, 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) => @@ -143,7 +143,7 @@ internal static IEnumerable EnumerateSessionsCore(string hostName, // Fallback on SESSION_INFO_10 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_10 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info10, 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) => @@ -159,7 +159,7 @@ internal static IEnumerable EnumerateSessionsCore(string hostName, // Fallback on SESSION_INFO_0 structure. - foreach (var sessionInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SESSION_INFO_0 structure, SafeGlobalMemoryBufferHandle buffer) => new SessionInfo(hostName, SessionInfoLevel.Info0, 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) => diff --git a/AlphaFS/Network/Host Class/Host.SMB.EnumerateShares.cs b/AlphaFS/Network/Host Class/Host.SMB.EnumerateShares.cs index 21dd68783..bf38384d3 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.EnumerateShares.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.EnumerateShares.cs @@ -112,56 +112,60 @@ public static IEnumerable EnumerateShares(string host, ShareType shar [SecurityCritical] internal static IEnumerable 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); + - var fd = new FunctionData(); - var hasItems = false; - var yieldAll = shareType == ShareType.All; + // Start with SHARE_INFO_503 structure. - - // Try SHARE_INFO_503 structure. - foreach (var si in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_503 structure, SafeGlobalMemoryBufferHandle buffer) => new ShareInfo(stripUnc, ShareInfoLevel.Info503, 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 si; + yield return shareInfo; hasItems = true; } + if (hasItems) + yield break; - // SHARE_INFO_503 is requested, but not supported/possible. - // Retry with SHARE_INFO_2 structure. - if (!hasItems) - foreach (var si in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_2 structure, SafeGlobalMemoryBufferHandle buffer) => new ShareInfo(stripUnc, ShareInfoLevel.Info2, structure), + // Fallback on SHARE_INFO_2 structure. - (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => + foreach (var shareInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_2 structure, SafeGlobalMemoryBufferHandle buffer) => new ShareInfo(stripUnc, ShareInfoLevel.Info2, structure), - NativeMethods.NetShareEnum(stripUnc, 2, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), continueOnException).Where(si => yieldAll || si.ShareType == shareType)) - { - yield return si; - hasItems = true; - } + (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; - // SHARE_INFO_2 is requested, but not supported/possible. - // Retry with SHARE_INFO_1 structure. - if (!hasItems) - foreach (var si in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_1 structure, SafeGlobalMemoryBufferHandle buffer) => new ShareInfo(stripUnc, ShareInfoLevel.Info1, structure), + // Fallback on SHARE_INFO_1 structure. - (FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) => + foreach (var shareInfo in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_1 structure, SafeGlobalMemoryBufferHandle buffer) => new ShareInfo(stripUnc, ShareInfoLevel.Info1, structure), - NativeMethods.NetShareEnum(stripUnc, 1, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), continueOnException).Where(si => yieldAll || si.ShareType == shareType)) - { - yield return si; - } + (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; + } } } } diff --git a/AlphaFS/Network/SessionInfo.cs b/AlphaFS/Network/SessionInfo.cs index aaa8f229f..b1570271d 100644 --- a/AlphaFS/Network/SessionInfo.cs +++ b/AlphaFS/Network/SessionInfo.cs @@ -20,7 +20,6 @@ */ using System; -using System.Net; using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network @@ -40,17 +39,17 @@ public sealed class SessionInfo /// Creates a instance. /// The DNS or NetBIOS name of the specified host. - /// One of the options. + /// One of the options. /// /// A , , /// , or instance. /// - internal SessionInfo(string hostName, SessionInfoLevel sessionInfoLevel, object structure) + internal SessionInfo(string hostName, SessionInfoLevel sessionLevel, object structure) { var flags = 0; - switch (sessionInfoLevel) + switch (sessionLevel) { case SessionInfoLevel.Info502: var sesi502 = (NativeMethods.SESSION_INFO_502) structure; @@ -105,7 +104,7 @@ internal SessionInfo(string hostName, SessionInfoLevel sessionInfoLevel, object HostName = hostName; - SessionInfoLevel = sessionInfoLevel; + SessionLevel = sessionLevel; // SESS_GUEST = 1, // SESS_NOENCRYPTION = 2 @@ -183,8 +182,8 @@ public string NetName public string TransportType { get; private set; } - /// The structure level for the instance. - public SessionInfoLevel SessionInfoLevel { get; private set; } + /// The structure level for the instance. + public SessionInfoLevel SessionLevel { get; private set; } #endregion // Properties } diff --git a/AlphaFS/Network/ShareInfo.cs b/AlphaFS/Network/ShareInfo.cs index 32cb85bad..ae9383bd1 100644 --- a/AlphaFS/Network/ShareInfo.cs +++ b/AlphaFS/Network/ShareInfo.cs @@ -204,7 +204,7 @@ public ShareResourceTypes ResourceType } - /// The structure level for the ShareInfo instance. + /// The structure level for the instance. public ShareInfoLevel ShareLevel { get; private set; } #endregion // Properties From 49e80c2f0c1b7ccafa18ceaf6bcbaf0f91a7597e Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 12 Feb 2018 18:43:40 +0100 Subject: [PATCH 041/133] -Added PhysicalDriveInfo unit tests; -Code improvement, work in progress; --- .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 20 +-- ...ice.GetPhysicalDriveInfo_FromDevicePath.cs | 64 +++++++++ ....GetPhysicalDriveInfo_FromLogicalDrive.cs} | 33 +++-- ...Device.GetPhysicalDriveInfo_FromVolume.cs} | 34 +++-- .../AlphaFS_PhysicalDriveInfoTest.cs | 31 +++++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 8 +- .../DriveInfo Class/DriveInfo_GetDrives.cs | 2 +- AlphaFS.UnitTest/UnitTest Utility/Dump.cs | 36 +++-- AlphaFS/AlphaFS.csproj | 8 +- .../Device/Device.EnumerateLogicalDrives.cs | 96 ------------- .../Device/Device.EnumeratePhysicalDrives.cs | 96 ------------- AlphaFS/Device/Device.EnumerateVolumes.cs | 78 ----------- .../Device.EnumeratePhysicalDrives.cs | 89 ++++++++++++ .../Device.GetPhysicalDriveInfo.cs | 131 ++++++++++++------ .../PhysicalDriveInfo.cs | 128 ++++++++++++----- AlphaFS/Device/Volume/VolumeInfo.cs | 2 +- AlphaFS/Resources.Designer.cs | 18 +++ AlphaFS/Resources.resx | 6 + 18 files changed, 470 insertions(+), 410 deletions(-) rename AlphaFS.UnitTest/{AlphaFS Device Class => AlphaFS PhysicalDrive Class}/AlphaFS_Device.EnumeratePhysicalDrives.cs (78%) create mode 100644 AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs rename AlphaFS.UnitTest/{AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs => AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs} (65%) rename AlphaFS.UnitTest/{AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs => AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs} (64%) create mode 100644 AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_PhysicalDriveInfoTest.cs delete mode 100644 AlphaFS/Device/Device.EnumerateLogicalDrives.cs delete mode 100644 AlphaFS/Device/Device.EnumeratePhysicalDrives.cs delete mode 100644 AlphaFS/Device/Device.EnumerateVolumes.cs create mode 100644 AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs rename AlphaFS/Device/{ => PhysicalDriveInfo}/Device.GetPhysicalDriveInfo.cs (70%) rename AlphaFS/Device/{ => PhysicalDriveInfo}/PhysicalDriveInfo.cs (59%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs similarity index 78% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs index 1f03eb8cc..51b91e159 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -25,7 +25,7 @@ namespace AlphaFS.UnitTest { - public partial class AlphaFS_DeviceTest + public partial class AlphaFS_PhysicalDriveInfoTest { // Pattern: ___ @@ -33,28 +33,22 @@ public partial class AlphaFS_DeviceTest [TestMethod] public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() { - //if (!UnitTestConstants.IsAdmin()) - // Assert.Inconclusive(); - UnitTestConstants.PrintUnitTestHeader(false); - var driveCount = 0; - var drives = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDrives().ToArray(); + var pDriveCount = 0; + var pDrives = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDrives().ToArray(); - foreach (var drive in drives) + foreach (var pDrive in pDrives) { Console.WriteLine(); - Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]", ++driveCount, drive.DeviceNumber); + Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]", ++pDriveCount, pDrive.DeviceNumber); - UnitTestConstants.Dump(drive, -17); - - - Console.WriteLine(); + UnitTestConstants.Dump(pDrive, -17); } - Assert.IsTrue(drives.Length > 0); + Assert.IsTrue(pDrives.Length > 0, "No physical drives enumerated, but it is expected."); } } } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs new file mode 100644 index 000000000..e29636c47 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs @@ -0,0 +1,64 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDriveInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_GetPhysicalDriveInfo_FromDevicePath_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + + var deviceCount = 0; + + var sourceDrive = UnitTestConstants.SysDrive + @"\"; + var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); + var devicePath = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceDrive).DevicePath; + + var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(devicePath); + + + Console.WriteLine(); + Console.WriteLine("#{0:000}\tDevice Path: [{1}]", ++deviceCount, devicePath); + + UnitTestConstants.Dump(pDrive, -17); + + + Assert.IsNotNull(pDrive); + + + Assert.IsNotNull(pDrive.VolumeGuids); + Assert.IsTrue(pDrive.VolumeGuids.Contains(sourceVolume)); + + + Assert.IsNotNull(pDrive.LogicalDrives); + Assert.IsTrue(pDrive.LogicalDrives.Contains(sourceDrive)); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs similarity index 65% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs index 8b95dab87..7a07cf380 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateLogicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs @@ -20,41 +20,44 @@ */ using System; -using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest { - public partial class AlphaFS_DeviceTest + public partial class AlphaFS_PhysicalDriveInfoTest { // Pattern: ___ [TestMethod] - public void AlphaFS_Device_EnumerateLogicalDrives_Local_Success() + public void AlphaFS_Device_GetPhysicalDriveInfo_FromLogicalDrive_Success() { - //if (!UnitTestConstants.IsAdmin()) - // Assert.Inconclusive(); - UnitTestConstants.PrintUnitTestHeader(false); var driveCount = 0; - var drives = Alphaleonis.Win32.Filesystem.Device.EnumerateLogicalDrives().ToArray(); - foreach (var drive in drives) - foreach (var driveInfo in drive.DriveInfo) - { - Console.WriteLine(); - Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, driveInfo.Name); + var sourceDrive = UnitTestConstants.SysDrive + @"\"; + var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - UnitTestConstants.Dump(drive, -17); - } + + var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceDrive); Console.WriteLine(); + Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, sourceDrive); + + UnitTestConstants.Dump(pDrive, -17); + + + Assert.IsNotNull(pDrive); + + + Assert.IsNotNull(pDrive.LogicalDrives); + Assert.IsTrue(pDrive.LogicalDrives.Contains(sourceDrive)); - Assert.IsTrue(drives.Length > 0); + Assert.IsNotNull(pDrive.VolumeGuids); + Assert.IsTrue(pDrive.VolumeGuids.Contains(sourceVolume)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs similarity index 64% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs index b8a7b50ef..c44a7f12e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateVolumes.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs @@ -20,41 +20,45 @@ */ using System; -using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest { - public partial class AlphaFS_DeviceTest + public partial class AlphaFS_PhysicalDriveInfoTest { // Pattern: ___ [TestMethod] - public void AlphaFS_Device_EnumerateVolumes_Local_Success() + public void AlphaFS_Device_GetPhysicalDriveInfo_FromVolume_Success() { - //if (!UnitTestConstants.IsAdmin()) - // Assert.Inconclusive(); - UnitTestConstants.PrintUnitTestHeader(false); var volumeCount = 0; - var volumes = Alphaleonis.Win32.Filesystem.Device.EnumerateVolumes().ToArray(); - foreach (var drive in volumes) - { - Console.WriteLine(); - Console.WriteLine("#{0:000}\tVolume: [{1}]", ++volumeCount, drive.VolumeGuids[0]); + var sourceDrive = UnitTestConstants.SysDrive + @"\"; + var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); + + + var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceVolume); + + + Console.WriteLine(); + Console.WriteLine("#{0:000}\tVolume: [{1}]", ++volumeCount, sourceVolume); + + UnitTestConstants.Dump(pDrive, -17); - UnitTestConstants.Dump(drive, -17); + Assert.IsNotNull(pDrive); + - Console.WriteLine(); - } + Assert.IsNotNull(pDrive.VolumeGuids); + Assert.IsTrue(pDrive.VolumeGuids.Contains(sourceVolume)); - Assert.IsTrue(volumes.Length > 0); + Assert.IsNotNull(pDrive.LogicalDrives); + Assert.IsTrue(pDrive.LogicalDrives.Contains(sourceDrive)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_PhysicalDriveInfoTest.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_PhysicalDriveInfoTest.cs new file mode 100644 index 000000000..1d670d5cf --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_PhysicalDriveInfoTest.cs @@ -0,0 +1,31 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace AlphaFS.UnitTest +{ + /// This is a test class for PhysicalDriveInfo and is intended to contain all PhysicalDriveInfo Unit Tests. + [TestClass] + public partial class AlphaFS_PhysicalDriveInfoTest + { + } +} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index b1e68f907..75d027042 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -148,10 +148,12 @@ - - + + + + + - diff --git a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs index 888d5b072..f743bc0d1 100644 --- a/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs +++ b/AlphaFS.UnitTest/DriveInfo Class/DriveInfo_GetDrives.cs @@ -58,7 +58,7 @@ public void DriveInfo_GetDrives_Local_Success() } - Assert.IsTrue(drives.Count > 0); + Assert.IsTrue(drives.Count > 0, "No logical drives enumerated, but it is expected."); Assert.AreEqual(drives[0].Name[0], UnitTestConstants.SysDrive[0]); } diff --git a/AlphaFS.UnitTest/UnitTest Utility/Dump.cs b/AlphaFS.UnitTest/UnitTest Utility/Dump.cs index 97ae42d16..114ea2167 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/Dump.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/Dump.cs @@ -21,6 +21,7 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; @@ -64,16 +65,33 @@ public static bool Dump(object obj, int width = -35, bool indent = false) propValue = propObj.Elapsed.TotalMilliseconds.ToString(CultureInfo.InvariantCulture); } - //else if (propObjType.IsAssignableToAnyOf(typeof(List<>))) - //{ - //} + else if (propObjType.IsAssignableToAnyOf(typeof(Collection), typeof(List))) + { + var propObj = (Collection) value; + + if (null != propObj) + { + foreach (var itemValue in propObj) + propValue += itemValue + ", "; + + if (null != propValue) + propValue = propValue.TrimEnd(',', ' '); + } + } - //else if (propObjType == typeof(List<>)) - //{ - // var propObj = value as List; - // if (null != propObj) - // propValue = propObj.Count.ToString(CultureInfo.InvariantCulture); - //} + else if (propObjType.IsAssignableToAnyOf(typeof(Collection), typeof(List))) + { + var propObj = (Collection) value; + + if (null != propObj) + { + foreach (var itemValue in propObj) + propValue += itemValue + ", "; + + if (null != propValue) + propValue = propValue.TrimEnd(',', ' '); + } + } else propValue = value.ToString(); diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 963f0c2c3..e684aa504 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -198,14 +198,12 @@ - - - - + + - + diff --git a/AlphaFS/Device/Device.EnumerateLogicalDrives.cs b/AlphaFS/Device/Device.EnumerateLogicalDrives.cs deleted file mode 100644 index 21b1251b4..000000000 --- a/AlphaFS/Device/Device.EnumerateLogicalDrives.cs +++ /dev/null @@ -1,96 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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.Collections.ObjectModel; -using System.Linq; -using System.Security; - -namespace Alphaleonis.Win32.Filesystem -{ - public static partial class Device - { - /// [AlphaFS] Enumerates the logical drives and associated physical drives on the Computer. - /// An IEnumerable of type that represents the physical drives on the Computer. - [SecurityCritical] - public static IEnumerable EnumerateLogicalDrives() - { - //var pDrives = new Collection(); - - //var logicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName).ToArray(); - - - //foreach (var pDrive in EnumeratePhysicalDrives().Where(drive => null != drive.DriveInfo)) - //{ - // foreach (var driveInfo in pDrive.DriveInfo) - // { - // pDrives.Add(pDrive); - // } - //} - - - //return pDrives; - - - var physicalDrives = EnumeratePhysicalDrives().ToArray(); - - var logicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).OrderBy(driveName => driveName).ToArray(); - - - foreach (var drive in logicalDrives) - { - var pDriveInfo = GetPhysicalDriveInfoCore(drive, null, false); - - if (null == pDriveInfo) - continue; - - - foreach (var pDrive in physicalDrives.Where(pDrive => pDrive.DeviceNumber == pDriveInfo.DeviceNumber)) - { - CopyTo(pDrive, pDriveInfo); - - - // Get the first entry that starts with a logical drive path, such as: "C:", "D:". - - if (Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath)) - { - if (null == pDriveInfo.DriveInfo) - pDriveInfo.DriveInfo= new Collection(); - - - pDriveInfo.DriveInfo.Add(new DriveInfo(drive)); - - - var guid = Volume.GetVolumeGuid(drive); - - if (!Utils.IsNullOrWhiteSpace(guid)) - pDriveInfo.VolumeGuids = new[] {guid}; - } - - - yield return pDriveInfo; - - break; - } - } - } - } -} diff --git a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs deleted file mode 100644 index 8e649d111..000000000 --- a/AlphaFS/Device/Device.EnumeratePhysicalDrives.cs +++ /dev/null @@ -1,96 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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.Linq; -using System.Security; - -namespace Alphaleonis.Win32.Filesystem -{ - public static partial class Device - { - /// [AlphaFS] Enumerates the physical drives on the Computer. - /// An IEnumerable of type that represents the physical drives on the Computer. - [SecurityCritical] - public static IEnumerable EnumeratePhysicalDrives() - { - var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ToArray(); - - //var volumes = Volume.EnumerateVolumes().Select(volume => GetPhysicalDriveInfoCore(volume, null, false)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ThenBy(physicalDrive => physicalDrive.PartitionNumber).ToArray(); - - //var logicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(driveName, null, false)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ThenBy(physicalDrive => physicalDrive.PartitionNumber).ToArray(); - - - //var populatedPhysicalDrives = new Collection(); - - - //foreach (var volume in volumes) - //{ - // foreach (var pDrive in physicalDrives.Where(pDrive => pDrive.DeviceNumber == volume.DeviceNumber)) - // { - // CopyTo(pDrive, volume); - - - // foreach (var lDrive in Volume.EnumerateVolumePathNames(volume.DevicePath).Where(drive => !Utils.IsNullOrWhiteSpace(drive) && Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath))) - // { - // if (null == volume.DriveInfo) - // volume.DriveInfo = new Collection(); - - // volume.DriveInfo.Add(new DriveInfo(lDrive)); - // } - - - // volume.VolumeGuids = new[] {volume.DevicePath}; - - // populatedPhysicalDrives.Add(volume); - - // break; - // } - //} - - - //return populatedPhysicalDrives.OrderBy(pDriveInfo => pDriveInfo.DeviceNumber).ThenBy(pDriveInfo => pDriveInfo.PartitionNumber); - - return physicalDrives.OrderBy(pDriveInfo => pDriveInfo.DeviceNumber).ThenBy(pDriveInfo => pDriveInfo.PartitionNumber); - } - - - private static void CopyTo(T source, T destination) - { - // Properties listed here should not be overwritten by the physical drive template. - - var excludedProps = new[] {"PartitionNumber"}; - - - var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite && !excludedProps.Any(prop => prop.Equals(x.Name))).ToArray(); - - var dstProps = srcProps.ToArray(); - - - foreach (var srcProp in srcProps) - { - var dstProp = dstProps.First(x => x.Name.Equals(srcProp.Name)); - - dstProp.SetValue(destination, srcProp.GetValue(source, null), null); - } - } - } -} diff --git a/AlphaFS/Device/Device.EnumerateVolumes.cs b/AlphaFS/Device/Device.EnumerateVolumes.cs deleted file mode 100644 index 19db46c77..000000000 --- a/AlphaFS/Device/Device.EnumerateVolumes.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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.Collections.ObjectModel; -using System.Linq; -using System.Security; - -namespace Alphaleonis.Win32.Filesystem -{ - public static partial class Device - { - /// [AlphaFS] Enumerates the volumes and associated physical drives on the Computer. - /// An IEnumerable of type that represents the physical drives on the Computer. - [SecurityCritical] - public static IEnumerable EnumerateVolumes() - { - var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).Where(physicalDrive => null != physicalDrive).OrderBy(disk => disk.DeviceNumber).ToArray(); - - var volumeGuids = Volume.EnumerateVolumes().ToArray(); - - - var populatedPhysicalDrives = new Collection(); - - - foreach (var volume in volumeGuids) - { - var pDriveInfo = GetPhysicalDriveInfoCore(volume, null, false); - - if (null == pDriveInfo) - continue; - - - foreach (var pDrive in physicalDrives.Where(pDrive => pDrive.DeviceNumber == pDriveInfo.DeviceNumber)) - { - CopyTo(pDrive, pDriveInfo); - - - foreach (var lDrive in Volume.EnumerateVolumePathNames(volume).Where(drive => !Utils.IsNullOrWhiteSpace(drive) && Path.IsLogicalDriveCore(drive, PathFormat.LongFullPath))) - { - if (null == pDriveInfo.DriveInfo) - pDriveInfo.DriveInfo = new Collection(); - - pDriveInfo.DriveInfo.Add(new DriveInfo(lDrive)); - } - - - pDriveInfo.VolumeGuids = new[] {volume}; - - populatedPhysicalDrives.Add(pDriveInfo); - - break; - } - } - - - return populatedPhysicalDrives.OrderBy(pDriveInfo => pDriveInfo.DeviceNumber).ThenBy(pDriveInfo => pDriveInfo.PartitionNumber); - } - } -} diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs new file mode 100644 index 000000000..27e3d4f54 --- /dev/null +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs @@ -0,0 +1,89 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Collections.ObjectModel; +using System.Linq; +using System.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + /// [AlphaFS] Enumerates the physical drives on the Computer, populated with volume- and logical drive information. + /// An collection that represents the physical drives on the Computer. + [SecurityCritical] + public static IEnumerable EnumeratePhysicalDrives() + { + var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ToArray(); + + var pVolumes = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(volumeGuid, null, false)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ThenBy(physicalDrive => physicalDrive.PartitionNumber).ToArray(); + + var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(driveName, null, false)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ThenBy(physicalDrive => physicalDrive.PartitionNumber).ToArray(); + + + var populatedPhysicalDrives = new Collection(); + + + foreach (var pDrive in physicalDrives) + { + var pDriveInfo = new PhysicalDriveInfo(pDrive) + { + PartitionNumber = pDrive.PartitionNumber + }; + + + // Get volume from physical drive matching DeviceNumber. + + foreach (var pDriveVolume in pVolumes.Where(pDriveVolume => pDriveVolume.DeviceNumber == pDrive.DeviceNumber)) + { + if (null == pDriveInfo.PartitionNumbers) + pDriveInfo.PartitionNumbers = new Collection(); + + pDriveInfo.PartitionNumbers.Add(pDriveVolume.PartitionNumber); + + + if (null == pDriveInfo.VolumeGuids) + pDriveInfo.VolumeGuids = new Collection(); + + pDriveInfo.VolumeGuids.Add(pDriveVolume.DevicePath); + + + // Get logical drive from volume matching DeviceNumber and PartitionNumber. + + foreach (var pDriveLogical in pLogicalDrives.Where(pDriveLogical => pDriveLogical.DeviceNumber == pDriveVolume.DeviceNumber && pDriveLogical.PartitionNumber == pDriveVolume.PartitionNumber)) + { + if (null == pDriveInfo.LogicalDrives) + pDriveInfo.LogicalDrives = new Collection(); + + pDriveInfo.LogicalDrives.Add(pDriveLogical.DevicePath); + } + } + + + populatedPhysicalDrives.Add(pDriveInfo); + } + + + return populatedPhysicalDrives.OrderBy(pDriveInfo => pDriveInfo.DeviceNumber).ThenBy(pDriveInfo => pDriveInfo.PartitionNumber); + } + } +} diff --git a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs similarity index 70% rename from AlphaFS/Device/Device.GetPhysicalDriveInfo.cs rename to AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index bf54be1e9..8b9d7c0ca 100644 --- a/AlphaFS/Device/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -22,6 +22,7 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; @@ -30,38 +31,69 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// [AlphaFS] Gets the physical drive information such as the serial number and Product ID. - /// A instance that represents the physical drive on the Computer or null on error. - /// - /// - /// - /// + /// [AlphaFS] Retrieves the physical drive on the Computer that is related to the volume GUID, logical drive name or . + /// Do not call this method for every volume or logical drive on the system as each call queries all physical drives and associated volumes and logical drives. + /// Instead, use method and property or . + /// + /// A instance that represents the physical drive on the Computer. /// - /// A drive path such as: "C:", "D:\". - /// A volume path such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string (when is set to ). + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string (when is set to ). /// [SecurityCritical] public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) { - return GetPhysicalDriveInfoCore(devicePath, null); + bool isDrive; + bool isVolume; + bool isDeviceInfo; + + devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + + + var pDriveInfo = GetPhysicalDriveInfoCore(devicePath, null, false); + + if (null == pDriveInfo) + return null; + + + var partitionNumber = pDriveInfo.PartitionNumber; + + + pDriveInfo = isDeviceInfo + + ? EnumeratePhysicalDrives().FirstOrDefault(pDrive => pDrive.DeviceNumber == pDriveInfo.DeviceNumber && pDrive.PartitionNumber == partitionNumber) + + : isVolume + ? EnumeratePhysicalDrives().FirstOrDefault(pDrive => null != pDrive.VolumeGuids && pDrive.VolumeGuids.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) + + : isDrive + ? EnumeratePhysicalDrives().FirstOrDefault(pDrive => null != pDrive.LogicalDrives && pDrive.LogicalDrives.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) + : null; + + + if (null != pDriveInfo) + pDriveInfo.PartitionNumber = partitionNumber; + + + return pDriveInfo; } - /// [AlphaFS] Gets the physical drive information such as the serial number and Product ID. + /// [AlphaFS] Gets the physical drive information such as DeviceType, DeviceNumber, PartitionNumber and the serial number and Product ID. /// A instance that represents the physical drive on the Computer or null on error. /// /// /// /// /// - /// A drive path such as: "C:", "D:\". - /// A volume path such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// A string (when is set to ). /// - /// a instance. + /// A instance. /// /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] @@ -75,7 +107,14 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De string logicalDrive; - var storageDevice = GetStorageDevice(devicePath, out logicalDrive); + + var pathToDevice = ValidateAndGetPathToDevice(devicePath, out logicalDrive); + + if (Utils.IsNullOrWhiteSpace(pathToDevice)) + return null; + + + var storageDevice = GetStorageDevice(pathToDevice); if (null == storageDevice) return null; @@ -84,7 +123,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De var device = storageDevice.Value; var diskNumber = device.DeviceNumber; - var physicalDriveInfo = new PhysicalDriveInfo + var physicalDriveInfo = new PhysicalDriveInfo() { DevicePath = devicePath, DeviceNumber = diskNumber, @@ -101,6 +140,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De try { + // Requires elevation. SetStorageData(physicalDrive, physicalDriveInfo); } catch { } @@ -111,6 +151,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De { try { + // Requires elevation. GetVolumeDiskExtents(logicalDrive); } catch { } @@ -121,6 +162,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De } + /// Sets the physical drive properties such as FriendlyName, device size and serial number. Requires elevation. private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physicalDriveInfo) { // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes @@ -143,7 +185,7 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi }; - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, physicalDrive, NativeMethods.DefaultFileBufferSize / 4)) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, physicalDrive, NativeMethods.DefaultFileBufferSize / 2)) { var storageDescriptor = safeBuffer.PtrToStructure(0); @@ -156,12 +198,9 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi physicalDriveInfo.RemovableMedia = storageDescriptor.RemovableMedia; - if (Utils.IsNullOrWhiteSpace(physicalDriveInfo.Name)) - physicalDriveInfo.Name = safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductIdOffset).Trim(); - - + // Get the device hardware serial number. physicalDriveInfo.SerialNumber = safeBuffer.PtrToStringAnsi((int) storageDescriptor.SerialNumberOffset).Trim(); @@ -187,16 +226,9 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi } - private static NativeMethods.STORAGE_DEVICE_NUMBER? GetStorageDevice(string devicePath, out string logicalDrive) + /// Retrieves the storage DeviceType, DeviceNumber and PartitionNumber. No elevation needed. + private static NativeMethods.STORAGE_DEVICE_NUMBER? GetStorageDevice(string devicePath) { - logicalDrive = null; - - var pathToDevice = ValidateAndGetPathToDevice(devicePath, out logicalDrive); - - if (Utils.IsNullOrWhiteSpace(pathToDevice)) - return null; - - // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. @@ -210,42 +242,55 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi // No elevation needed. - using (var safeHandle = OpenPhysicalDrive(pathToDevice, desiredAccess)) + using (var safeHandle = OpenPhysicalDrive(devicePath, desiredAccess)) - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, pathToDevice)) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath)) return null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?) null; } private static string ValidateAndGetPathToDevice(string devicePath, out string logicalDrive) + { + bool isDrive; + bool isVolume; + bool isDeviceInfo; + + devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + + devicePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", isDrive ? Path.LogicalDrivePrefix : string.Empty, Path.RemoveTrailingDirectorySeparator(devicePath)); + + logicalDrive = isDrive ? devicePath : null; + + return devicePath; + } + + + private static string ValidateDevicePath(string devicePath, out bool isDrive, out bool isVolume, out bool isDeviceInfo) { if (Utils.IsNullOrWhiteSpace(devicePath)) throw new ArgumentNullException("devicePath"); - + // Resolve single drive letter or get root directory information. devicePath = devicePath.Length == 1 ? devicePath + Path.VolumeSeparatorChar : Path.GetPathRoot(devicePath, false); + var hasPath = !Utils.IsNullOrWhiteSpace(devicePath); - var isDrive = Path.IsLogicalDriveCore(devicePath, PathFormat.LongFullPath); - var isVolume = devicePath.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase); + isDrive = hasPath && Path.IsLogicalDriveCore(devicePath, PathFormat.FullPath); - var isDeviceInfo = !isDrive && !isVolume && devicePath.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal); + isVolume = hasPath && devicePath.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase); + isDeviceInfo = hasPath && !isDrive && !isVolume && devicePath.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal); - if (!isDrive && !isVolume && !isDeviceInfo) - throw new ArgumentException(Resources.Argument_must_be_DriveLetter_or_VolumeGuid_or_DevicePath, "devicePath"); - - devicePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", isDrive ? Path.LogicalDrivePrefix : string.Empty, Path.RemoveTrailingDirectorySeparator(devicePath)); - - logicalDrive = isDrive ? devicePath : null; + if (!hasPath || !isDrive && !isVolume && !isDeviceInfo) + throw new ArgumentException(Resources.Argument_must_be_DriveLetter_or_VolumeGuid_or_DevicePath, "devicePath"); - return devicePath; + return Path.AddTrailingDirectorySeparator(devicePath, false); } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs similarity index 59% rename from AlphaFS/Device/PhysicalDriveInfo.cs rename to AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs index 2c3c4805a..27b0cc504 100644 --- a/AlphaFS/Device/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs @@ -22,6 +22,7 @@ using System; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -40,40 +41,16 @@ public PhysicalDriveInfo() } - ///// Initializes a PhysicalDriveInfo instance. - ///// A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z'. - ///// This is a Lazyloading object; call to populate all properties first before accessing. - //[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] - //[SecurityCritical] - //public PhysicalDriveInfo(string driveName) : this() - //{ - // 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"); - - - // // 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. - // DevicePath = Path.AddTrailingDirectorySeparator(driveName, false); - //} + /// Initializes a PhysicalDriveInfo instance. + public PhysicalDriveInfo(PhysicalDriveInfo pDrive) : this() + { + CopyTo(pDrive, this); + } #endregion // Constructors - /// Returns the "FriendlyName" of the physical drive. - /// A string that represents this instance. - public override string ToString() - { - return Name; - } - + #region Properties /// The bus type of the physical drive. public StorageBusType BusType { get; internal set; } @@ -87,14 +64,14 @@ public override string ToString() /// A string that represents the path to the device. /// A drive path such as: "C:", "D:\", /// a volume path such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\" - /// or a string (when is set to ). + /// or a string. /// public string DevicePath { get; internal set; } /// The logical drives that are located on the physical drive. - public Collection DriveInfo { get; internal set; } - + public Collection LogicalDrives { get; internal set; } + /// Indicates if the physical drive supports multiple outstanding commands (SCSI tagged queuing or equivalent). When false the physical drive does not support SCSI-tagged queuing or the equivalent. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Queueing")] @@ -113,8 +90,12 @@ public override string ToString() public int PartitionNumber { get; internal set; } + /// Indicates the partition number of the device is returned in this member, if the device can be partitioned. Otherwise, -1 is returned. + public Collection PartitionNumbers { get; internal set; } + + /// The Partitions located on the physical drive. - public string[] Partitions { get; set; } + public string[] Partitions { get; internal set; } /// The product revision of the physical drive. public string ProductRevision { get; internal set; } @@ -136,6 +117,83 @@ public string TotalSizeUnitSize /// The volumes that are located on the physical drive. - public string[] VolumeGuids { get; set; } + public Collection VolumeGuids { get; internal set; } + + #endregion // Properties + + + #region Methods + + /// Returns the "FriendlyName" of the physical drive. + /// A string that represents this instance. + public override string ToString() + { + return Name; + } + + + /// Determines whether the specified Object is equal to the current Object. + /// Another object to compare to. + /// if the specified Object is equal to the current Object; otherwise, . + public override bool Equals(object obj) + { + if (null == obj || GetType() != obj.GetType()) + return false; + + var other = obj as PhysicalDriveInfo; + + return null != other && null != other.DevicePath && other.DevicePath.Equals(DevicePath, StringComparison.OrdinalIgnoreCase); + } + + + /// Serves as a hash function for a particular type. + /// A hash code for the current Object. + public override int GetHashCode() + { + return null != DevicePath ? DevicePath.GetHashCode() : 0; + } + + + /// Implements the operator == + /// A. + /// B. + /// The result of the operator. + public static bool operator ==(PhysicalDriveInfo left, PhysicalDriveInfo right) + { + return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); + } + + + /// Implements the operator != + /// A. + /// B. + /// The result of the operator. + public static bool operator !=(PhysicalDriveInfo left, PhysicalDriveInfo right) + { + return !(left == right); + } + + + private static void CopyTo(T source, T destination) + { + // Properties listed here should not be overwritten by the physical drive template. + + var excludedProps = new[] {"PartitionNumber"}; + + + var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite && !excludedProps.Any(prop => prop.Equals(x.Name))).ToArray(); + + var dstProps = srcProps.ToArray(); + + + foreach (var srcProp in srcProps) + { + var dstProp = dstProps.First(x => x.Name.Equals(srcProp.Name)); + + dstProp.SetValue(destination, srcProp.GetValue(source, null), null); + } + } + + #endregion // Methods } } diff --git a/AlphaFS/Device/Volume/VolumeInfo.cs b/AlphaFS/Device/Volume/VolumeInfo.cs index 1430e955c..94555094b 100644 --- a/AlphaFS/Device/Volume/VolumeInfo.cs +++ b/AlphaFS/Device/Volume/VolumeInfo.cs @@ -65,7 +65,7 @@ public VolumeInfo(string driveName) { driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); - if (!driveName.StartsWith(Path.GlobalRootPrefix, StringComparison.OrdinalIgnoreCase)) + if (null != driveName && !driveName.StartsWith(Path.GlobalRootPrefix, StringComparison.OrdinalIgnoreCase)) driveName = Path.GetPathRoot(driveName, false); } diff --git a/AlphaFS/Resources.Designer.cs b/AlphaFS/Resources.Designer.cs index 5ccea7015..6f979e275 100644 --- a/AlphaFS/Resources.Designer.cs +++ b/AlphaFS/Resources.Designer.cs @@ -250,6 +250,24 @@ internal static string InvalidDriveLetterArgument { } } + /// + /// Looks up a localized string similar to Argument must be a drive letter: "C" or RootDir: "C:\". + /// + internal static string InvalidLogicalDriveArgument { + get { + return ResourceManager.GetString("InvalidLogicalDriveArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Argument must be a drive letter: "C", "C:\" or Volume GUID.. + /// + internal static string InvalidLogicalDriveVolumeArgument { + get { + return ResourceManager.GetString("InvalidLogicalDriveVolumeArgument", resourceCulture); + } + } + /// /// Looks up a localized string similar to The target directory of the directory junction must be on the same local drive.. /// diff --git a/AlphaFS/Resources.resx b/AlphaFS/Resources.resx index d299cd670..49149f86a 100644 --- a/AlphaFS/Resources.resx +++ b/AlphaFS/Resources.resx @@ -252,6 +252,12 @@ Argument must be a drive letter: "C", RootDir: "C:\" or UNC path: "\\server\share" + + + Argument must be a drive letter: "C" or RootDir: "C:\" + + + Argument must be a drive letter: "C", "C:\" or Volume GUID. Cannot add and remove trailing DirectorySeparator simultaneously. From 27bae6c235ff1ceb2641acfe120a8e413e675ac7 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 13 Feb 2018 10:30:53 +0100 Subject: [PATCH 042/133] Code improvement, work in progress. --- AlphaFS/AlphaFS.csproj | 1 + AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 86 +++++++- .../Device.EnumeratePhysicalDrives.cs | 2 +- .../Device.GetPhysicalDriveInfo.cs | 24 +- .../PhysicalDriveInfo/PhysicalDriveInfo.cs | 12 +- .../DRIVE_LAYOUT_INFORMATION_EX.cs | 208 ++++++++++++++++++ .../Filesystem/Native Other/IoControlCode.cs | 15 +- .../Native Other/VOLUME_DISK_EXTENTS.cs | 4 +- 8 files changed, 314 insertions(+), 38 deletions(-) create mode 100644 AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index e684aa504..01d259389 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -321,6 +321,7 @@ + diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index 9fb912c0a..4ba55e681 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -19,6 +19,9 @@ * THE SOFTWARE. */ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; @@ -27,7 +30,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Device { [SecurityCritical] - public static void GetVolumeDiskExtents(string logicalDrive) + internal static NativeMethods.DISK_GEOMETRY? GetDiskGeometry(string logicalDrive) { // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. @@ -39,24 +42,83 @@ public static void GetVolumeDiskExtents(string logicalDrive) //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - - - //var volumeDiskExtents = new NativeMethods.VOLUME_DISK_EXTENTS(); - using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) - - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, logicalDrive)) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, logicalDrive)) { if (null != safeBuffer) { - var structure = safeBuffer.PtrToStructure(0); + var structure = safeBuffer.PtrToStructure(0); - for (var i = 0; i < structure.NumberOfDiskExtents; ++i) - { - var pDiskExtent = structure.Extents[i]; - } + return structure; } } + + + return null; + + + //var name = "\\\\.\\C:"; + //// var handle = DriveLayout.NativeMethods.CreateFile(name, DriveLayout.NativeMethods.AccessRights.GENERIC_READ | DriveLayout.NativeMethods.AccessRights.GENERIC_WRITE, FileShare.Read | FileShare.Write, IntPtr.Zero, DriveLayout.NativeMethods.FileCreationDisposition.OPEN_EXISTING, FileAttributes.Normal, IntPtr.Zero) + + //int geometrySize = Marshal.SizeOf(typeof(NativeMethods.DISK_GEOMETRY)); + ////Console.WriteLine("geometry size = {0}", geometrySize); + + //IntPtr geometryBlob = Marshal.AllocHGlobal(geometrySize); + //uint numBytesRead = 0; + + + //NativeMethods.DeviceIoControl(handle, NativeMethods.IoControlCode.IoCtlDiskGetDriveGeometry, IntPtr.Zero, 0, geometryBlob, (uint)geometrySize, ref numBytesRead, IntPtr.Zero); + + + //NativeMethods.DISK_GEOMETRY geometry = (NativeMethods.DISK_GEOMETRY)Marshal.PtrToStructure(geometryBlob, typeof(NativeMethods.DISK_GEOMETRY)); + + //Marshal.FreeHGlobal(geometryBlob); + + //Console.WriteLine("Cylinders: " + geometry.Cylinders); + //Console.WriteLine("SectorsPerTrack: " + geometry.SectorsPerTrack); + //Console.WriteLine("TracksPerCylinder: " + geometry.TracksPerCylinder); + //Console.WriteLine("BytesPerSector: " + geometry.BytesPerSector); + + //return geometry; } + + + //[SecurityCritical] + //internal static void GetVolumeDiskExtents(string logicalDrive) + //{ + // // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes + // // without accessing that file or device, even if GENERIC_READ access would have been denied. + // // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + // //const int desiredAccess = 0; + + // // Requires elevation. + // const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; + + // //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; + + + // using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) + // using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, logicalDrive)) + // { + // if (null != safeBuffer) + // { + // var structure = safeBuffer.PtrToStructure(0); + + // var numberOfDiskExtents = structure.NumberOfDiskExtents; + + // var objectSize = Marshal.SizeOf(typeof(NativeMethods.VOLUME_DISK_EXTENTS)); + + + // for (int i = 0, itemOffset = 0; i < numberOfDiskExtents; i++, itemOffset += objectSize) + // { + // structure = safeBuffer.PtrToStructure(itemOffset); + + // //var pDiskExtent = structure.Extents[i]; + + // //yield return structure; + // } + // } + // } + //} } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs index 27e3d4f54..2edf54b55 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs @@ -33,7 +33,7 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrives() { - var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ToArray(); + var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo, true)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ToArray(); var pVolumes = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(volumeGuid, null, false)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ThenBy(physicalDrive => physicalDrive.PartitionNumber).ToArray(); diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index 8b9d7c0ca..146a99c83 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -50,7 +50,6 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); - var pDriveInfo = GetPhysicalDriveInfoCore(devicePath, null, false); if (null == pDriveInfo) @@ -94,11 +93,11 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// A string (when is set to ). /// /// A instance. - /// + /// /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, DeviceInfo deviceInfo, bool getStorageData = true) + internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, DeviceInfo deviceInfo, bool getDeviceData) { var isDeviceInfo = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); @@ -114,7 +113,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De return null; - var storageDevice = GetStorageDevice(pathToDevice); + var storageDevice = GetDeviceNumberAndType(pathToDevice); if (null == storageDevice) return null; @@ -134,28 +133,29 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De }; - if (getStorageData) + if (getDeviceData) { var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, diskNumber.ToString(CultureInfo.InvariantCulture)); try { // Requires elevation. - SetStorageData(physicalDrive, physicalDriveInfo); + SetDeviceData(physicalDrive, physicalDriveInfo); } catch { } } - if (null != logicalDrive) - { + //if (null != logicalDrive) + //{ try { // Requires elevation. - GetVolumeDiskExtents(logicalDrive); + //GetVolumeDiskExtents(logicalDrive); + GetDiskGeometry(physicalDriveInfo.DevicePath); } catch { } - } + //} return physicalDriveInfo; @@ -163,7 +163,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De /// Sets the physical drive properties such as FriendlyName, device size and serial number. Requires elevation. - private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physicalDriveInfo) + private static void SetDeviceData(string physicalDrive, PhysicalDriveInfo physicalDriveInfo) { // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. @@ -227,7 +227,7 @@ private static void SetStorageData(string physicalDrive, PhysicalDriveInfo physi /// Retrieves the storage DeviceType, DeviceNumber and PartitionNumber. No elevation needed. - private static NativeMethods.STORAGE_DEVICE_NUMBER? GetStorageDevice(string devicePath) + private static NativeMethods.STORAGE_DEVICE_NUMBER? GetDeviceNumberAndType(string devicePath) { // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. diff --git a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs index 27b0cc504..f6f9fc8f2 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs @@ -42,9 +42,9 @@ public PhysicalDriveInfo() /// Initializes a PhysicalDriveInfo instance. - public PhysicalDriveInfo(PhysicalDriveInfo pDrive) : this() + public PhysicalDriveInfo(PhysicalDriveInfo pDriveInfo) : this() { - CopyTo(pDrive, this); + CopyTo(pDriveInfo, this); } #endregion // Constructors @@ -101,7 +101,7 @@ public PhysicalDriveInfo(PhysicalDriveInfo pDrive) : this() public string ProductRevision { get; internal set; } - /// Gets the serial number of the physical drive. If the physical drive has no serial number, this member is -1. + /// Gets the serial number of the physical drive. If the physical drive has no serial number or the session is not elevated, this member is -1. public string SerialNumber { get; internal set; } @@ -142,7 +142,11 @@ public override bool Equals(object obj) var other = obj as PhysicalDriveInfo; - return null != other && null != other.DevicePath && other.DevicePath.Equals(DevicePath, StringComparison.OrdinalIgnoreCase); + return null != other && null != other.DevicePath && + + other.DevicePath.Equals(DevicePath, StringComparison.OrdinalIgnoreCase) && + + other.DeviceNumber.Equals(DeviceNumber) && other.PartitionNumber.Equals(PartitionNumber); } diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs new file mode 100644 index 000000000..3c48ea7fb --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs @@ -0,0 +1,208 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace Alphaleonis.Win32.Filesystem +{ + // https://github.com/surgicalcoder/DriveExpander/blob/8cf9e8bdc17881f7bc8cfd1d4dc10493392f92b0/DiskExpander/Program.cs + + + internal static partial class NativeMethods + { + internal const int PartitionEntriesCount = 10; + + + /// Describes the geometry of disk devices and media. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct DISK_GEOMETRY + { + [MarshalAs(UnmanagedType.U8)] public long Cylinders; + [MarshalAs(UnmanagedType.U4)] public MEDIA_TYPE MediaType; + [MarshalAs(UnmanagedType.U4)] public uint TracksPerCylinder; + [MarshalAs(UnmanagedType.U4)] public uint SectorsPerTrack; + [MarshalAs(UnmanagedType.U4)] public uint BytesPerSector; + } + + + /// Represents the various forms of device media. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + internal enum MEDIA_TYPE + { + /// Format is unknown. + Unknown = 0, + + /// A 5.25" floppy, with 1.2MB and 512 bytes/sector. + F5_1Pt2_512 = 1, + + /// A 3.5" floppy, with 1.44MB and 512 bytes/sector. + F3_1Pt44_512 = 2, + + /// A 3.5" floppy, with 2.88MB and 512 bytes/sector. + F3_2Pt88_512 = 3, + + /// A 3.5" floppy, with 20.8MB and 512 bytes/sector. + F3_20Pt8_512 = 4, + + /// A 3.5" floppy, with 720KB and 512 bytes/sector. + F3_720_512 = 5, + + /// A 5.25" floppy, with 360KB and 512 bytes/sector. + F5_360_512 = 6, + + /// A 5.25" floppy, with 320KB and 512 bytes/sector. + F5_320_512 = 7, + + /// A 5.25" floppy, with 320KB and 1024 bytes/sector. + F5_320_1024 = 8, + + /// A 5.25" floppy, with 180KB and 512 bytes/sector. + F5_180_512 = 9, + + /// A 5.25" floppy, with 160KB and 512 bytes/sector. + F5_160_512 = 10, + + /// Removable media other than floppy. + RemovableMedia = 11, + + /// Fixed hard disk media. + FixedMedia = 12, + + /// A 3.5" floppy, with 120MB and 512 bytes/sector. + F3_120M_512 = 13, + + /// A 3.5" floppy, with 640KB and 512 bytes/sector. + F3_640_512 = 14, + + /// A 5.25" floppy, with 640KB and 512 bytes/sector. + F5_640_512 = 15, + + /// A 5.25" floppy, with 720KB and 512 bytes/sector. + F5_720_512 = 16, + + /// A 3.5" floppy, with 1.2MB and 512 bytes/sector. + F3_1Pt2_512 = 17, + + /// A 3.5" floppy, with 1.23MB and 1024 bytes/sector. + F3_1Pt23_1024 = 18, + + /// A 5.25" floppy, with 1.23MB and 1024 bytes/sector. + F5_1Pt23_1024 = 19, + + /// A 3.5" floppy, with 128MB and 512 bytes/sector. + F3_128Mb_512 = 20, + + /// A 3.5" floppy, with 230MB and 512 bytes/sector. + F3_230Mb_512 = 21, + + /// An 8" floppy, with 256KB and 128 bytes/sector. + F8_256_128 = 22, + + /// A 3.5" floppy, with 200MB and 512 bytes/sector. (HiFD). + F3_200Mb_512 = 23, + + /// A 3.5" floppy, with 240MB and 512 bytes/sector. (HiFD). + F3_240M_512 = 24, + + /// A 3.5" floppy, with 32MB and 512 bytes/sector. + F3_32M_512 = 25 + } + + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct DRIVE_LAYOUT_INFORMATION_EX + { + public PARTITION_STYLE PartitionStyle; + public Int32 PartitionCount; + public DriveLayoutInformationUnion DriveLayoutInformation; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = PartitionEntriesCount)] + public PARTITION_INFORMATION_EX[] PartitionEntry; + } + + + internal struct PARTITION_INFORMATION_EX + { + public PARTITION_STYLE PartitionStyle; + public Int64 StartingOffset; + public Int64 PartitionLength; + public UInt32 PartitionNumber; + [MarshalAs(UnmanagedType.Bool)] public bool RewritePartition; + public PartitionInformationUnion PartitionInformation; + } + + + internal enum PARTITION_STYLE : int + { + PARTITION_STYLE_MBR = 0, + PARTITION_STYLE_GPT = 1, + PARTITION_STYLE_RAW = 2 + } + + + [StructLayout(LayoutKind.Explicit)] + public struct DriveLayoutInformationUnion + { + [FieldOffset(0)] public DRIVE_LAYOUT_INFORMATION_MBR Mbr; + [FieldOffset(0)] public DRIVE_LAYOUT_INFORMATION_GPT Gpt; + } + + + [StructLayout(LayoutKind.Explicit)] + public struct PartitionInformationUnion + { + [FieldOffset(0)] public PARTITION_INFORMATION_MBR Mbr; + [FieldOffset(0)] public DRIVE_LAYOUT_INFORMATION_GPT Gpt; + } + + + public struct DRIVE_LAYOUT_INFORMATION_MBR + { + [MarshalAs(UnmanagedType.U8)] public ulong Signature; + } + + + public struct DRIVE_LAYOUT_INFORMATION_GPT + { + public Guid DiskId; + public Int64 StartingUsableOffset; + public Int64 UsableLength; + [MarshalAs(UnmanagedType.U4)] public uint MaxPartitionCount; + } + + + public struct PARTITION_INFORMATION_MBR + { + public byte PartitionType; + [MarshalAs(UnmanagedType.Bool)] public bool BootIndicator; + [MarshalAs(UnmanagedType.Bool)] public bool RecognizedPartition; + [MarshalAs(UnmanagedType.U4)] public uint HiddenSectors; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/IoControlCode.cs b/AlphaFS/Filesystem/Native Other/IoControlCode.cs index f220e9adb..ebb2fcaf3 100644 --- a/AlphaFS/Filesystem/Native Other/IoControlCode.cs +++ b/AlphaFS/Filesystem/Native Other/IoControlCode.cs @@ -141,15 +141,16 @@ internal enum IoControlCode : uint ///// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). + ///// MSDN: IOCTL_DISK_GET_DRIVE_GEOMETRY has been superseded by , which retrieves additional information. //IOCTL_DISK_GET_DRIVE_GEOMETRY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0000 << 2) | IoMethod.Buffered | (0 << 14), - ///// - ///// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). - ///// The difference between IOCTL_DISK_GET_DRIVE_GEOMETRY_EX and the older IOCTL_DISK_GET_DRIVE_GEOMETRY request is that - ///// IOCTL_DISK_GET_DRIVE_GEOMETRY_EX can retrieve information from both Master Boot Record (MBR) and GUID Partition Table (GPT)-type - ///// partitioned media, whereas IOCTL_DISK_GET_DRIVE_GEOMETRY can only read MBR-style media. - ///// - //IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0028 << 2) | IoMethod.Buffered | (0 << 14), + /// + /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). + /// The difference between IOCTL_DISK_GET_DRIVE_GEOMETRY_EX and the older IOCTL_DISK_GET_DRIVE_GEOMETRY request is that + /// IOCTL_DISK_GET_DRIVE_GEOMETRY_EX can retrieve information from both Master Boot Record (MBR) and GUID Partition Table (GPT)-type + /// partitioned media, whereas IOCTL_DISK_GET_DRIVE_GEOMETRY can only read MBR-style media. + /// + IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0028 << 2) | IoMethod.Buffered | (0 << 14), ///// Returns information about the type, size, and nature of a disk partition. (Floppy drivers need not handle this request.) diff --git a/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs b/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs index a38259ed4..a9e04d3c1 100644 --- a/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs +++ b/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs @@ -30,10 +30,10 @@ internal static partial class NativeMethods internal struct VOLUME_DISK_EXTENTS { /// The number of disks in the volume (a volume can span multiple disks). - public readonly uint NumberOfDiskExtents; + public uint NumberOfDiskExtents; /// An array of structures. - [MarshalAs(UnmanagedType.ByValArray)] public readonly DISK_EXTENT[] Extents; + [MarshalAs(UnmanagedType.ByValArray)] public DISK_EXTENT[] Extents; } } } From b495c2253a2b3e73c4e4e8216cd2a229bdbe951a Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 13 Feb 2018 14:33:29 +0100 Subject: [PATCH 043/133] Code improvement, work in progress. --- AlphaFS/AlphaFS.csproj | 13 +- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 76 ++++++-- .../Device.GetPhysicalDriveInfo.cs | 9 +- .../Filesystem/Native Other/DISK_GEOMETRY.cs | 52 ++++++ .../Native Other/DISK_GEOMETRY_EX.cs | 46 +++++ .../DRIVE_LAYOUT_INFORMATION_EX.cs | 173 ++---------------- .../DRIVE_LAYOUT_INFORMATION_GPT.cs | 49 +++++ .../DRIVE_LAYOUT_INFORMATION_MBR.cs | 39 ++++ .../Native Other/DiskPartitionTypes.cs | 72 ++++++++ .../Native Other/EFIPartitionAttributes.cs | 39 ++++ .../Filesystem/Native Other/IoControlCode.cs | 17 +- AlphaFS/Filesystem/Native Other/MEDIA_TYPE.cs | 112 ++++++++++++ .../Native Other/PARTITION_INFORMATION_EX.cs | 62 +++++++ .../Native Other/PARTITION_INFORMATION_GPT.cs | 51 ++++++ .../Native Other/PARTITION_INFORMATION_MBR.cs | 48 +++++ .../Native Other/PARTITION_STYLE.cs | 43 +++++ .../Native Other/STORAGE_DEVICE_DESCRIPTOR.cs | 4 +- .../Native Other/STORAGE_DEVICE_NUMBER.cs | 2 +- 18 files changed, 716 insertions(+), 191 deletions(-) create mode 100644 AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs create mode 100644 AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs create mode 100644 AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs create mode 100644 AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs create mode 100644 AlphaFS/Filesystem/Native Other/DiskPartitionTypes.cs create mode 100644 AlphaFS/Filesystem/Native Other/EFIPartitionAttributes.cs create mode 100644 AlphaFS/Filesystem/Native Other/MEDIA_TYPE.cs create mode 100644 AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs create mode 100644 AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs create mode 100644 AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs create mode 100644 AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 01d259389..ace755ba5 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -313,8 +313,18 @@ + + + + + + + + + + @@ -323,6 +333,7 @@ + @@ -652,7 +663,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index 4ba55e681..99a6d8506 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -21,6 +21,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; @@ -29,8 +30,10 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { + // https://github.com/t00/TestCrypt/blob/master/TestCrypt/PhysicalDrive.cs + [SecurityCritical] - internal static NativeMethods.DISK_GEOMETRY? GetDiskGeometry(string logicalDrive) + internal static NativeMethods.PARTITION_INFORMATION_EX? GetDiskPartitions(string logicalDrive) { // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. @@ -42,44 +45,80 @@ public static partial class Device //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; + using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, logicalDrive)) + + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_PARTITION_INFO_EX, logicalDrive)) { if (null != safeBuffer) { - var structure = safeBuffer.PtrToStructure(0); + var structure = safeBuffer.PtrToStructure(0); return structure; } } - return null; + } - //var name = "\\\\.\\C:"; - //// var handle = DriveLayout.NativeMethods.CreateFile(name, DriveLayout.NativeMethods.AccessRights.GENERIC_READ | DriveLayout.NativeMethods.AccessRights.GENERIC_WRITE, FileShare.Read | FileShare.Write, IntPtr.Zero, DriveLayout.NativeMethods.FileCreationDisposition.OPEN_EXISTING, FileAttributes.Normal, IntPtr.Zero) + [SecurityCritical] + internal static NativeMethods.DRIVE_LAYOUT_INFORMATION_EX? GetDiskLayout(string logicalDrive) + { + // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes + // without accessing that file or device, even if GENERIC_READ access would have been denied. + // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + //const int desiredAccess = 0; - //int geometrySize = Marshal.SizeOf(typeof(NativeMethods.DISK_GEOMETRY)); - ////Console.WriteLine("geometry size = {0}", geometrySize); + // Requires elevation. + const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; - //IntPtr geometryBlob = Marshal.AllocHGlobal(geometrySize); - //uint numBytesRead = 0; + //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - //NativeMethods.DeviceIoControl(handle, NativeMethods.IoControlCode.IoCtlDiskGetDriveGeometry, IntPtr.Zero, 0, geometryBlob, (uint)geometrySize, ref numBytesRead, IntPtr.Zero); + using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, logicalDrive)) + { + if (null != safeBuffer) + { + var structure = safeBuffer.PtrToStructure(0); - //NativeMethods.DISK_GEOMETRY geometry = (NativeMethods.DISK_GEOMETRY)Marshal.PtrToStructure(geometryBlob, typeof(NativeMethods.DISK_GEOMETRY)); + return structure; + } + } - //Marshal.FreeHGlobal(geometryBlob); + return null; + } - //Console.WriteLine("Cylinders: " + geometry.Cylinders); - //Console.WriteLine("SectorsPerTrack: " + geometry.SectorsPerTrack); - //Console.WriteLine("TracksPerCylinder: " + geometry.TracksPerCylinder); - //Console.WriteLine("BytesPerSector: " + geometry.BytesPerSector); - //return geometry; + [SecurityCritical] + internal static NativeMethods.DISK_GEOMETRY_EX? GetDiskGeometry(string logicalDrive) + { + // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes + // without accessing that file or device, even if GENERIC_READ access would have been denied. + // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + //const int desiredAccess = 0; + + // Requires elevation. + const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; + + //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; + + + using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) + + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, logicalDrive)) + { + if (null != safeBuffer) + { + var structure = safeBuffer.PtrToStructure(0); + + return structure; + } + } + + return null; } @@ -98,6 +137,7 @@ public static partial class Device // using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) + // // using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, logicalDrive)) // { // if (null != safeBuffer) diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index 146a99c83..a9b649e2c 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -122,7 +122,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De var device = storageDevice.Value; var diskNumber = device.DeviceNumber; - var physicalDriveInfo = new PhysicalDriveInfo() + var physicalDriveInfo = new PhysicalDriveInfo { DevicePath = devicePath, DeviceNumber = diskNumber, @@ -152,7 +152,12 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De { // Requires elevation. //GetVolumeDiskExtents(logicalDrive); - GetDiskGeometry(physicalDriveInfo.DevicePath); + + var pDrive = @"\\.\PhysicalDrive0"; + + GetDiskPartitions(pDrive); + GetDiskGeometry(pDrive); + GetDiskLayout(pDrive); } catch { } //} diff --git a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs new file mode 100644 index 000000000..b6707eef1 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs @@ -0,0 +1,52 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// Describes the geometry of disk devices and media. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct DISK_GEOMETRY + { + /// The number of cylinders. + [MarshalAs(UnmanagedType.U8)] public long Cylinders; + + /// The type of media. + [MarshalAs(UnmanagedType.U4)] public MEDIA_TYPE MediaType; + + /// The number of tracks per cylinder. + [MarshalAs(UnmanagedType.U4)] public uint TracksPerCylinder; + + /// The number of sectors per track. + [MarshalAs(UnmanagedType.U4)] public uint SectorsPerTrack; + + /// The number of bytes per sector. + [MarshalAs(UnmanagedType.U4)] public uint BytesPerSector; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs new file mode 100644 index 000000000..23ef6c2e7 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs @@ -0,0 +1,46 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// Describes the extended geometry of disk devices and media. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct DISK_GEOMETRY_EX + { + /// A structure. + public DISK_GEOMETRY Geometry; + + /// The disk size, in bytes. + [MarshalAs(UnmanagedType.U8)] public ulong DiskSize; + + /// Any additional data. + [MarshalAs(UnmanagedType.I1)] public byte Data; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs index 3c48ea7fb..285d32cc3 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs @@ -19,190 +19,41 @@ * THE SOFTWARE. */ -using System; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem { - // https://github.com/surgicalcoder/DriveExpander/blob/8cf9e8bdc17881f7bc8cfd1d4dc10493392f92b0/DiskExpander/Program.cs - - internal static partial class NativeMethods { - internal const int PartitionEntriesCount = 10; + public const int PartitionEntriesCount = 10; - /// Describes the geometry of disk devices and media. + /// Contains extended information about a drive's partitions. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct DISK_GEOMETRY - { - [MarshalAs(UnmanagedType.U8)] public long Cylinders; - [MarshalAs(UnmanagedType.U4)] public MEDIA_TYPE MediaType; - [MarshalAs(UnmanagedType.U4)] public uint TracksPerCylinder; - [MarshalAs(UnmanagedType.U4)] public uint SectorsPerTrack; - [MarshalAs(UnmanagedType.U4)] public uint BytesPerSector; - } - - - /// Represents the various forms of device media. - /// - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// - internal enum MEDIA_TYPE - { - /// Format is unknown. - Unknown = 0, - - /// A 5.25" floppy, with 1.2MB and 512 bytes/sector. - F5_1Pt2_512 = 1, - - /// A 3.5" floppy, with 1.44MB and 512 bytes/sector. - F3_1Pt44_512 = 2, - - /// A 3.5" floppy, with 2.88MB and 512 bytes/sector. - F3_2Pt88_512 = 3, - - /// A 3.5" floppy, with 20.8MB and 512 bytes/sector. - F3_20Pt8_512 = 4, - - /// A 3.5" floppy, with 720KB and 512 bytes/sector. - F3_720_512 = 5, - - /// A 5.25" floppy, with 360KB and 512 bytes/sector. - F5_360_512 = 6, - - /// A 5.25" floppy, with 320KB and 512 bytes/sector. - F5_320_512 = 7, - - /// A 5.25" floppy, with 320KB and 1024 bytes/sector. - F5_320_1024 = 8, - - /// A 5.25" floppy, with 180KB and 512 bytes/sector. - F5_180_512 = 9, - - /// A 5.25" floppy, with 160KB and 512 bytes/sector. - F5_160_512 = 10, - - /// Removable media other than floppy. - RemovableMedia = 11, - - /// Fixed hard disk media. - FixedMedia = 12, - - /// A 3.5" floppy, with 120MB and 512 bytes/sector. - F3_120M_512 = 13, - - /// A 3.5" floppy, with 640KB and 512 bytes/sector. - F3_640_512 = 14, - - /// A 5.25" floppy, with 640KB and 512 bytes/sector. - F5_640_512 = 15, - - /// A 5.25" floppy, with 720KB and 512 bytes/sector. - F5_720_512 = 16, - - /// A 3.5" floppy, with 1.2MB and 512 bytes/sector. - F3_1Pt2_512 = 17, - - /// A 3.5" floppy, with 1.23MB and 1024 bytes/sector. - F3_1Pt23_1024 = 18, - - /// A 5.25" floppy, with 1.23MB and 1024 bytes/sector. - F5_1Pt23_1024 = 19, - - /// A 3.5" floppy, with 128MB and 512 bytes/sector. - F3_128Mb_512 = 20, - - /// A 3.5" floppy, with 230MB and 512 bytes/sector. - F3_230Mb_512 = 21, - - /// An 8" floppy, with 256KB and 128 bytes/sector. - F8_256_128 = 22, - - /// A 3.5" floppy, with 200MB and 512 bytes/sector. (HiFD). - F3_200Mb_512 = 23, - - /// A 3.5" floppy, with 240MB and 512 bytes/sector. (HiFD). - F3_240M_512 = 24, - - /// A 3.5" floppy, with 32MB and 512 bytes/sector. - F3_32M_512 = 25 - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct DRIVE_LAYOUT_INFORMATION_EX { + /// The style of the partitions on the drive enumerated by the enumeration. public PARTITION_STYLE PartitionStyle; - public Int32 PartitionCount; - public DriveLayoutInformationUnion DriveLayoutInformation; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = PartitionEntriesCount)] - public PARTITION_INFORMATION_EX[] PartitionEntry; - } - - - internal struct PARTITION_INFORMATION_EX - { - public PARTITION_STYLE PartitionStyle; - public Int64 StartingOffset; - public Int64 PartitionLength; - public UInt32 PartitionNumber; - [MarshalAs(UnmanagedType.Bool)] public bool RewritePartition; - public PartitionInformationUnion PartitionInformation; - } - - - internal enum PARTITION_STYLE : int - { - PARTITION_STYLE_MBR = 0, - PARTITION_STYLE_GPT = 1, - PARTITION_STYLE_RAW = 2 - } - - [StructLayout(LayoutKind.Explicit)] - public struct DriveLayoutInformationUnion - { - [FieldOffset(0)] public DRIVE_LAYOUT_INFORMATION_MBR Mbr; - [FieldOffset(0)] public DRIVE_LAYOUT_INFORMATION_GPT Gpt; - } - - - [StructLayout(LayoutKind.Explicit)] - public struct PartitionInformationUnion - { - [FieldOffset(0)] public PARTITION_INFORMATION_MBR Mbr; - [FieldOffset(0)] public DRIVE_LAYOUT_INFORMATION_GPT Gpt; - } + /// The number of partitions on the drive. On hard disks with the MBR layout, this value will always be a multiple of 4. + [MarshalAs(UnmanagedType.U4)] public uint PartitionCount; + public DRIVE_LAYOUT_INFORMATION_UNION DriveLayoutInformation; - public struct DRIVE_LAYOUT_INFORMATION_MBR - { - [MarshalAs(UnmanagedType.U8)] public ulong Signature; - } - - - public struct DRIVE_LAYOUT_INFORMATION_GPT - { - public Guid DiskId; - public Int64 StartingUsableOffset; - public Int64 UsableLength; - [MarshalAs(UnmanagedType.U4)] public uint MaxPartitionCount; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = PartitionEntriesCount)] + public PARTITION_INFORMATION_EX[] PartitionEntry; } - public struct PARTITION_INFORMATION_MBR + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct DRIVE_LAYOUT_INFORMATION_UNION { - public byte PartitionType; - [MarshalAs(UnmanagedType.Bool)] public bool BootIndicator; - [MarshalAs(UnmanagedType.Bool)] public bool RecognizedPartition; - [MarshalAs(UnmanagedType.U4)] public uint HiddenSectors; + public DRIVE_LAYOUT_INFORMATION_MBR Mbr; + public DRIVE_LAYOUT_INFORMATION_GPT Gpt; } } } diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs new file mode 100644 index 000000000..c2a08e65e --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs @@ -0,0 +1,49 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace Alphaleonis.Win32.Filesystem +{ + internal static partial class NativeMethods + { + /// Contains information about a drive's GUID partition table (GPT) partitions. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + internal struct DRIVE_LAYOUT_INFORMATION_GPT + { + /// The GUID of the disk. + public Guid DiskId; + + /// The starting byte offset of the first usable block. + [MarshalAs(UnmanagedType.U8)] public ulong StartingUsableOffset; + + /// The size of the usable blocks on the disk, in bytes. + [MarshalAs(UnmanagedType.U8)] public ulong UsableLength; + + /// The maximum number of partitions that can be defined in the usable block. + [MarshalAs(UnmanagedType.U4)] public uint MaxPartitionCount; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs new file mode 100644 index 000000000..f15ad0491 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs @@ -0,0 +1,39 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// Provides information about a drive's master boot record (MBR) partitions. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + public struct DRIVE_LAYOUT_INFORMATION_MBR + { + /// The signature of the drive. + [MarshalAs(UnmanagedType.U8)] public ulong Signature; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/DiskPartitionTypes.cs b/AlphaFS/Filesystem/Native Other/DiskPartitionTypes.cs new file mode 100644 index 000000000..d99e3f8c9 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DiskPartitionTypes.cs @@ -0,0 +1,72 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// The following table identifies the valid partition types that are used by disk drivers. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + internal enum DiskPartitionTypes + { + /// An unused entry partition. + PARTITION_ENTRY_UNUSED = 0, + + /// A FAT12 file system partition. + PARTITION_FAT_12 = 1, + + PARTITION_XENIX_1 = 2, + PARTITION_XENIX_2 = 3, + + /// A FAT16 file system partition. + PARTITION_FAT_16 = 4, + + /// An extended partition. + PARTITION_EXTENDED = 5, + + PARTITION_HUGE = 6, + + /// An IFS partition. + PARTITION_IFS = 7, + + /// A FAT32 file system partition. + PARTITION_FAT32 = 11, + + PARTITION_FAT32_XINT13 = 12, + PARTITION_XINT13 = 14, + PARTITION_XINT13_EXTENDED = 15, + PARTITION_PREP = 65, + + /// A logical disk manager (LDM) partition. + PARTITION_LDM = 66, + + PARTITION_UNIX = 99, + + /// An NTFT partition. + PARTITION_NTFT = 128, + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/EFIPartitionAttributes.cs b/AlphaFS/Filesystem/Native Other/EFIPartitionAttributes.cs new file mode 100644 index 000000000..14729d911 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/EFIPartitionAttributes.cs @@ -0,0 +1,39 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + [Flags] + public enum EFIPartitionAttributes : ulong + { + GPT_ATTRIBUTE_PLATFORM_REQUIRED = 0x0000000000000001, + LegacyBIOSBootable = 0x0000000000000004, + GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER = 0x8000000000000000, + GPT_BASIC_DATA_ATTRIBUTE_HIDDEN = 0x4000000000000000, + GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY = 0x2000000000000000, + GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY = 0x1000000000000000 + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/IoControlCode.cs b/AlphaFS/Filesystem/Native Other/IoControlCode.cs index ebb2fcaf3..41ce7a0f7 100644 --- a/AlphaFS/Filesystem/Native Other/IoControlCode.cs +++ b/AlphaFS/Filesystem/Native Other/IoControlCode.cs @@ -31,8 +31,8 @@ internal static partial class NativeMethods [Flags] internal enum IoControlCode : uint { - /// Retrieves the physical location of a specified volume on one or more disks. - IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), + ///// Retrieves the physical location of a specified volume on one or more disks. + //IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), /// Return properties of a storage device or adapter. The request indicates the kind of information to retrieve, such as inquiry data for a device or capabilities and limitations of an adapter. @@ -139,9 +139,8 @@ internal enum IoControlCode : uint #region FILE_DEVICE_DISK - ///// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). - ///// MSDN: IOCTL_DISK_GET_DRIVE_GEOMETRY has been superseded by , which retrieves additional information. + //[Obsolete("MSDN: IOCTL_DISK_GET_DRIVE_GEOMETRY has been superseded by IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, which retrieves additional information.")] //IOCTL_DISK_GET_DRIVE_GEOMETRY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0000 << 2) | IoMethod.Buffered | (0 << 14), /// @@ -154,19 +153,25 @@ internal enum IoControlCode : uint ///// Returns information about the type, size, and nature of a disk partition. (Floppy drivers need not handle this request.) + //[Obsolete("IOCTL_DISK_GET_PARTITION_INFO is superseded by IOCTL_DISK_GET_PARTITION_INFO_EX, which retrieves partition information for AT and Extensible Firmware Interface (EFI) partitions.")] //IOCTL_DISK_GET_PARTITION_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0001 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + /////// Returns information about the type, size, and nature of a disk partition. (Floppy drivers need not handle this request.) + IOCTL_DISK_GET_PARTITION_INFO_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0012 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + + ///// Changes the partition type of the specified disk partition. (Floppy drivers need not handle this request.) //IOCTL_DISK_SET_PARTITION_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0002 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Returns information about the number of partitions, disk signature, and features of each partition on a disk. (Floppy drivers need not handle this request.) + //[Obsolete("IOCTL_DISK_GET_DRIVE_LAYOUT has been superseded by IOCTL_DISK_GET_DRIVE_LAYOUT_EX, which retrieves layout information for AT and EFI (Extensible Firmware Interface) partitions.")] //IOCTL_DISK_GET_DRIVE_LAYOUT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0003 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), - ///// Contains extended information about a drive's partitions. - //IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0014 << 2) | IoMethod.Buffered | (0 << 14), + /// Contains extended information about a drive's partitions. + IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0014 << 2) | IoMethod.Buffered | (0 << 14), ///// Repartitions a disk as specified. (Floppy drivers need not handle this request.) diff --git a/AlphaFS/Filesystem/Native Other/MEDIA_TYPE.cs b/AlphaFS/Filesystem/Native Other/MEDIA_TYPE.cs new file mode 100644 index 000000000..173f68a1d --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/MEDIA_TYPE.cs @@ -0,0 +1,112 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Represents the various forms of device media. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + internal enum MEDIA_TYPE + { + /// Format is unknown. + Unknown = 0, + + /// A 5.25" floppy, with 1.2MB and 512 bytes/sector. + F5_1Pt2_512 = 1, + + /// A 3.5" floppy, with 1.44MB and 512 bytes/sector. + F3_1Pt44_512 = 2, + + /// A 3.5" floppy, with 2.88MB and 512 bytes/sector. + F3_2Pt88_512 = 3, + + /// A 3.5" floppy, with 20.8MB and 512 bytes/sector. + F3_20Pt8_512 = 4, + + /// A 3.5" floppy, with 720KB and 512 bytes/sector. + F3_720_512 = 5, + + /// A 5.25" floppy, with 360KB and 512 bytes/sector. + F5_360_512 = 6, + + /// A 5.25" floppy, with 320KB and 512 bytes/sector. + F5_320_512 = 7, + + /// A 5.25" floppy, with 320KB and 1024 bytes/sector. + F5_320_1024 = 8, + + /// A 5.25" floppy, with 180KB and 512 bytes/sector. + F5_180_512 = 9, + + /// A 5.25" floppy, with 160KB and 512 bytes/sector. + F5_160_512 = 10, + + /// Removable media other than floppy. + RemovableMedia = 11, + + /// Fixed hard disk media. + FixedMedia = 12, + + /// A 3.5" floppy, with 120MB and 512 bytes/sector. + F3_120M_512 = 13, + + /// A 3.5" floppy, with 640KB and 512 bytes/sector. + F3_640_512 = 14, + + /// A 5.25" floppy, with 640KB and 512 bytes/sector. + F5_640_512 = 15, + + /// A 5.25" floppy, with 720KB and 512 bytes/sector. + F5_720_512 = 16, + + /// A 3.5" floppy, with 1.2MB and 512 bytes/sector. + F3_1Pt2_512 = 17, + + /// A 3.5" floppy, with 1.23MB and 1024 bytes/sector. + F3_1Pt23_1024 = 18, + + /// A 5.25" floppy, with 1.23MB and 1024 bytes/sector. + F5_1Pt23_1024 = 19, + + /// A 3.5" floppy, with 128MB and 512 bytes/sector. + F3_128Mb_512 = 20, + + /// A 3.5" floppy, with 230MB and 512 bytes/sector. + F3_230Mb_512 = 21, + + /// An 8" floppy, with 256KB and 128 bytes/sector. + F8_256_128 = 22, + + /// A 3.5" floppy, with 200MB and 512 bytes/sector. (HiFD). + F3_200Mb_512 = 23, + + /// A 3.5" floppy, with 240MB and 512 bytes/sector. (HiFD). + F3_240M_512 = 24, + + /// A 3.5" floppy, with 32MB and 512 bytes/sector. + F3_32M_512 = 25 + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs new file mode 100644 index 000000000..a68b4207c --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs @@ -0,0 +1,62 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// Contains partition information for standard AT-style master boot record (MBR) and Extensible Firmware Interface (EFI) disks. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential)] + internal struct PARTITION_INFORMATION_EX + { + /// The format of the partition. + public PARTITION_STYLE PartitionStyle; + + /// The starting offset of the partition. + [MarshalAs(UnmanagedType.U8)] public long StartingOffset; + + /// The size of the partition, in bytes. + [MarshalAs(UnmanagedType.U8)] public long PartitionLength; + + /// The number of the partition (1-based). + [MarshalAs(UnmanagedType.U4)] public uint PartitionNumber; + + /// If this member is TRUE, the partition is rewritable. The value of this parameter should be set to TRUE. + [MarshalAs(UnmanagedType.Bool)] public bool RewritePartition; + + //public PARTITION_INFORMATION_UNION PartitionInformation; + } + + + [StructLayout(LayoutKind.Explicit)] + public struct PARTITION_INFORMATION_UNION + { + [FieldOffset(0)] public PARTITION_INFORMATION_GPT Gpt; + [FieldOffset(0)] public PARTITION_INFORMATION_MBR Mbr; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs new file mode 100644 index 000000000..5280cacd4 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs @@ -0,0 +1,51 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace Alphaleonis.Win32.Filesystem +{ + internal static partial class NativeMethods + { + /// Contains GUID partition table (GPT) partition information. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct PARTITION_INFORMATION_GPT + { + /// A GUID that identifies the partition type. + public Guid PartitionType; + + /// The GUID of the partition. + public Guid PartitionId; + + /// The Extensible Firmware Interface (EFI) attributes of the partition. + [MarshalAs(UnmanagedType.U8)] public EFIPartitionAttributes Attributes; + + /// A wide-character string that describes the partition. + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] + public string Name; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs new file mode 100644 index 000000000..15f119e5d --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs @@ -0,0 +1,48 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// Contains partition information specific to master boot record (MBR) disks. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + public struct PARTITION_INFORMATION_MBR + { + /// The type of partition. + [MarshalAs(UnmanagedType.I1)] public DiskPartitionTypes PartitionType; + + /// If the member is TRUE, the partition is a boot partition. When this structure is used with the IOCTL_DISK_SET_PARTITION_INFO_EX control code, the value of this parameter is ignored. + [MarshalAs(UnmanagedType.Bool)] public bool BootIndicator; + + /// If this member is TRUE, the partition is of a recognized type. When this structure is used with the IOCTL_DISK_SET_PARTITION_INFO_EX control code, the value of this parameter is ignored. + [MarshalAs(UnmanagedType.Bool)] public bool RecognizedPartition; + + /// The number of hidden sectors to be allocated when the partition table is created. + [MarshalAs(UnmanagedType.U4)] public uint HiddenSectors; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs b/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs new file mode 100644 index 000000000..be61fad9a --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs @@ -0,0 +1,43 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Represents the format of a partition. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + internal enum PARTITION_STYLE + { + /// Master boot record (MBR) format. This corresponds to standard AT-style MBR partitions. + PARTITION_STYLE_MBR = 0, + + /// GUID Partition Table (GPT) format. + PARTITION_STYLE_GPT = 1, + + /// Partition not formatted in either of the recognized formats; MBR or GPT. + PARTITION_STYLE_RAW = 2 + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs index 1f7c9a2c9..a6811087c 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs @@ -42,10 +42,10 @@ internal struct STORAGE_DEVICE_DESCRIPTOR public readonly byte DeviceTypeModifier; /// Indicates when TRUE that the device's media (if any) is removable. If the device has no media, this member should be ignored. When FALSE the device's media is not removable. - [MarshalAs(UnmanagedType.U1)] public readonly bool RemovableMedia; + [MarshalAs(UnmanagedType.I1)] public readonly bool RemovableMedia; /// Indicates when TRUE that the device supports multiple outstanding commands (SCSI tagged queuing or equivalent). When FALSE, the device does not support SCSI-tagged queuing or the equivalent. - [MarshalAs(UnmanagedType.U1)] public readonly bool CommandQueueing; + [MarshalAs(UnmanagedType.I1)] public readonly bool CommandQueueing; /// Specifies the byte offset from the beginning of the structure to a null-terminated ASCII string that contains the device's vendor ID. If the device has no vendor ID, this member is zero. public readonly uint VendorIdOffset; diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs index 6fe47572b..5929b4789 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs @@ -33,7 +33,7 @@ internal static partial class NativeMethods internal struct STORAGE_DEVICE_NUMBER { /// Specifies one of the system-defined FILE_DEVICE_XXX constants indicating the type of device (such as FILE_DEVICE_DISK, FILE_DEVICE_KEYBOARD, and so forth) or a vendor-defined value for a new type of device. - internal readonly StorageDeviceType DeviceType; + [MarshalAs(UnmanagedType.U4)] internal readonly StorageDeviceType DeviceType; /// Indicates the number of this device. This value is set to 0xFFFFFFFF (-1) for the disks that represent the physical paths of an MPIO disk. [MarshalAs(UnmanagedType.U4)] internal readonly int DeviceNumber; From 1fed847045d76d8e15dcf63a831ce9fd441fc41b Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 14 Feb 2018 15:42:25 +0100 Subject: [PATCH 044/133] -Added class Filesystem.StorageDeviceInfo; -Added method Filesystem.Device.GetStorageTypeInfo; -Added method Filesystem.PhysicalDriveInfo.ContainsVolume; -Changed PhysicalDriveInfo.ToString to show DevicePath if Name is null; --- .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 8 +- ...ice.GetPhysicalDriveInfo_FromDevicePath.cs | 8 +- ...e.GetPhysicalDriveInfo_FromLogicalDrive.cs | 15 +- ..._Device.GetPhysicalDriveInfo_FromVolume.cs | 26 ++- .../AlphaFS_Device.GetStorageTypeInfo.cs | 69 +++++++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 + AlphaFS/AlphaFS.csproj | 6 +- AlphaFS/Device/Device.GetDevicePath.cs | 52 +++++ AlphaFS/Device/Device.OpenPhysicalDrive.cs | 8 +- AlphaFS/Device/Device.ValidateDevicePath.cs | 60 ++++++ .../Device.EnumeratePhysicalDrives.cs | 26 +-- .../Device.GetPhysicalDriveInfo.cs | 187 +++++------------- .../Device.GetStorageTypeInfo.cs | 114 +++++++++++ .../PhysicalDriveInfo/PhysicalDriveInfo.cs | 91 ++++++--- AlphaFS/Device/StorageDeviceInfo.cs | 126 ++++++++++++ AlphaFS/Device/Volume/VolumeInfo.cs | 1 + .../Filesystem/Native Other/IoControlCode.cs | 4 +- .../Path Class/Path.IsLogicalDrive.cs | 10 +- .../Structures, Enumerations/DeviceGuid.cs | 123 ++++++++---- .../SetupDiGetDeviceRegistryPropertyEnum.cs | 6 +- .../StorageBusType.cs | 2 +- .../StorageDeviceType.cs | 6 +- AlphaFS/Resources.Designer.cs | 2 +- AlphaFS/Resources.resx | 2 +- 24 files changed, 698 insertions(+), 255 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageTypeInfo.cs create mode 100644 AlphaFS/Device/Device.GetDevicePath.cs create mode 100644 AlphaFS/Device/Device.ValidateDevicePath.cs create mode 100644 AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageTypeInfo.cs create mode 100644 AlphaFS/Device/StorageDeviceInfo.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs index 51b91e159..dc8e10f09 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -37,14 +37,18 @@ public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() var pDriveCount = 0; - var pDrives = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDrives().ToArray(); + var pDrives = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDrives().OrderBy(pDriveInfo => pDriveInfo.StorageDeviceInfo.DeviceNumber).ThenBy(pDriveInfo => pDriveInfo.StorageDeviceInfo.PartitionNumber).ToArray(); foreach (var pDrive in pDrives) { Console.WriteLine(); - Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]", ++pDriveCount, pDrive.DeviceNumber); + Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]", ++pDriveCount, pDrive.StorageDeviceInfo.DeviceNumber); + UnitTestConstants.Dump(pDrive, -17); + + UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -15, true); + Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs index e29636c47..18803e1f7 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs @@ -37,7 +37,7 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromDevicePath_Success() var deviceCount = 0; - var sourceDrive = UnitTestConstants.SysDrive + @"\"; + var sourceDrive = UnitTestConstants.SysDrive; var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); var devicePath = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceDrive).DevicePath; @@ -47,8 +47,11 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromDevicePath_Success() Console.WriteLine(); Console.WriteLine("#{0:000}\tDevice Path: [{1}]", ++deviceCount, devicePath); + UnitTestConstants.Dump(pDrive, -17); + UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -15, true); + Assert.IsNotNull(pDrive); @@ -58,7 +61,10 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromDevicePath_Success() Assert.IsNotNull(pDrive.LogicalDrives); + Assert.IsTrue(pDrive.LogicalDrives.Contains(sourceDrive)); + + Assert.IsTrue(pDrive.ContainsVolume(sourceDrive[0].ToString())); } } } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs index 7a07cf380..e295e294c 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs @@ -37,27 +37,26 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromLogicalDrive_Success() var driveCount = 0; - var sourceDrive = UnitTestConstants.SysDrive + @"\"; - var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - + // Use lowercase drive letter because .Contains() is case sensitive by default. + var sourceDrive = UnitTestConstants.SysDrive.ToLowerInvariant() + System.IO.Path.DirectorySeparatorChar; var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceDrive); Console.WriteLine(); Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, sourceDrive); + UnitTestConstants.Dump(pDrive, -17); + UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -15, true); + Assert.IsNotNull(pDrive); Assert.IsNotNull(pDrive.LogicalDrives); - Assert.IsTrue(pDrive.LogicalDrives.Contains(sourceDrive)); - - - Assert.IsNotNull(pDrive.VolumeGuids); - Assert.IsTrue(pDrive.VolumeGuids.Contains(sourceVolume)); + //Assert.IsTrue(pDrive.LogicalDrives.Contains(sourceDrive)); + Assert.IsTrue(pDrive.ContainsVolume(sourceDrive)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs index c44a7f12e..e3ca8ea30 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs @@ -37,9 +37,19 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromVolume_Success() var volumeCount = 0; - var sourceDrive = UnitTestConstants.SysDrive + @"\"; - var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); + // Use lowercase drive letter because .Contains() is case sensitive by default. + var sourceDrive = UnitTestConstants.SysDrive.ToLowerInvariant(); + // Use uppercase volume guid because .Contains() is case sensitive by default. + var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive).ToUpperInvariant(); + + + //var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(@"t:\"); + + // \\?\Volume{db5044f9-bd1f-4243-ab97-4b985eb29e80}\, + // \\?\Volume{43dd0652-8ecf-4943-8275-016fc09f02c7}\, + // \\?\Volume{e32f9cf5-7978-4aaa-9525-86cf401487ad}\, + // \\?\Volume{50685374-f895-11e7-a43e-f49634afb3a5}\ var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceVolume); @@ -47,18 +57,18 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromVolume_Success() Console.WriteLine(); Console.WriteLine("#{0:000}\tVolume: [{1}]", ++volumeCount, sourceVolume); + UnitTestConstants.Dump(pDrive, -17); + UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -15, true); - Assert.IsNotNull(pDrive); - - Assert.IsNotNull(pDrive.VolumeGuids); - Assert.IsTrue(pDrive.VolumeGuids.Contains(sourceVolume)); + Assert.IsNotNull(pDrive); - Assert.IsNotNull(pDrive.LogicalDrives); - Assert.IsTrue(pDrive.LogicalDrives.Contains(sourceDrive)); + Assert.IsNotNull(pDrive.VolumeGuids); + //Assert.IsTrue(pDrive.VolumeGuids.Contains(sourceVolume)); + Assert.IsTrue(pDrive.ContainsVolume(sourceVolume)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageTypeInfo.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageTypeInfo.cs new file mode 100644 index 000000000..5716c3291 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageTypeInfo.cs @@ -0,0 +1,69 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDriveInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_GetStorageTypeInfo_FromLogicalDrive_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + var gotDisk = false; + var driveCount = 0; + + + foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) + { + Console.WriteLine(); + Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, drive.Name); + + var storageInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageTypeInfo(drive.Name, true); + + UnitTestConstants.Dump(storageInfo, -15); + + + Assert.IsNotNull(storageInfo); + + + if (drive.DriveType == System.IO.DriveType.Fixed) + { + gotDisk = true; + Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.Disk, storageInfo.DeviceType); + } + + + if (drive.DriveType == System.IO.DriveType.CDRom) + Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.CDRom, storageInfo.DeviceType); + } + + + Assert.IsTrue(gotDisk); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 75d027042..813d552fe 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -150,6 +150,7 @@ + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index ace755ba5..fb294f962 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -199,6 +199,10 @@ + + + + @@ -663,7 +667,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.GetDevicePath.cs b/AlphaFS/Device/Device.GetDevicePath.cs new file mode 100644 index 000000000..1b395b9d3 --- /dev/null +++ b/AlphaFS/Device/Device.GetDevicePath.cs @@ -0,0 +1,52 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + private static string GetDevicePath(string devicePath, out string logicalDrive) + { + bool isDrive; + bool isVolume; + bool isDeviceInfo; + + devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + + devicePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", isDrive ? Path.LogicalDrivePrefix : string.Empty, Path.RemoveTrailingDirectorySeparator(devicePath)); + + if (isDrive) + { + logicalDrive = Path.GetRegularPathCore(devicePath, GetFullPathOptions.RemoveTrailingDirectorySeparator, false); + + logicalDrive = devicePath.Substring(Path.LogicalDrivePrefix.Length); + } + + else + logicalDrive = null; + + + return devicePath; + } + } +} diff --git a/AlphaFS/Device/Device.OpenPhysicalDrive.cs b/AlphaFS/Device/Device.OpenPhysicalDrive.cs index 14f450415..d1bad5baf 100644 --- a/AlphaFS/Device/Device.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/Device.OpenPhysicalDrive.cs @@ -29,8 +29,7 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - - /// Opens a physical device, such as: "\\.\PhysicalDrive0" for access. + /// Opens a physical device, such as: "\\.\PhysicalDrive0" or "\\.\C:" for access. /// A instance. /// /// @@ -41,6 +40,11 @@ public static partial class Device [SecurityCritical] public static SafeFileHandle OpenPhysicalDrive(string path, FileSystemRights fileSystemRights) { + // fileSystemRights: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes + // without accessing that file or device, even if GENERIC_READ access would have been denied. + // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + + return File.CreateFileCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Open, fileSystemRights, FileShare.ReadWrite, false, false, PathFormat.LongFullPath); } } diff --git a/AlphaFS/Device/Device.ValidateDevicePath.cs b/AlphaFS/Device/Device.ValidateDevicePath.cs new file mode 100644 index 000000000..4c51c3910 --- /dev/null +++ b/AlphaFS/Device/Device.ValidateDevicePath.cs @@ -0,0 +1,60 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + public static partial class Device + { + internal static string ValidateDevicePath(string devicePath, out bool isDrive, out bool isVolume, out bool isDeviceInfo) + { + if (Utils.IsNullOrWhiteSpace(devicePath)) + throw new ArgumentNullException("devicePath"); + + + // Resolve single drive letter or get root directory information. + + devicePath = devicePath.Length == 1 ? devicePath + Path.VolumeSeparatorChar : Path.GetPathRoot(devicePath, false); + + var hasPath = !Utils.IsNullOrWhiteSpace(devicePath); + + //if (hasPath) + // devicePath = Path.AddTrailingDirectorySeparator(devicePath, false); + + + isVolume = hasPath && devicePath.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase); + + isDeviceInfo = hasPath && !isVolume && devicePath.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal); + + isDrive = hasPath && !isDeviceInfo && !isVolume && Path.IsLogicalDriveCore(devicePath, PathFormat.LongFullPath); + + + + if (!hasPath || !isVolume && !isDeviceInfo && !isDrive) + throw new ArgumentException(Resources.Argument_must_be_DriveLetter_or_VolumeGuid_or_DevicePath, "devicePath"); + + + return Path.AddTrailingDirectorySeparator(devicePath, false); + } + } +} diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs index 2edf54b55..dc0ac1516 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs @@ -33,32 +33,29 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrives() { - var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, deviceInfo, true)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ToArray(); + var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, null, deviceInfo, true, true)).Where(physicalDrive => null != physicalDrive).ToArray(); - var pVolumes = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(volumeGuid, null, false)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ThenBy(physicalDrive => physicalDrive.PartitionNumber).ToArray(); + var pVolumes = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(null, volumeGuid, null, false, false)).Where(physicalDrive => null != physicalDrive).ToArray(); - var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(driveName, null, false)).Where(physicalDrive => null != physicalDrive).OrderBy(physicalDrive => physicalDrive.DeviceNumber).ThenBy(physicalDrive => physicalDrive.PartitionNumber).ToArray(); - - - var populatedPhysicalDrives = new Collection(); + var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(null, driveName, null, false, false)).Where(physicalDrive => null != physicalDrive).ToArray(); foreach (var pDrive in physicalDrives) { var pDriveInfo = new PhysicalDriveInfo(pDrive) { - PartitionNumber = pDrive.PartitionNumber + StorageDeviceInfo = {PartitionNumber = pDrive.StorageDeviceInfo.PartitionNumber} }; - + // Get volume from physical drive matching DeviceNumber. - foreach (var pDriveVolume in pVolumes.Where(pDriveVolume => pDriveVolume.DeviceNumber == pDrive.DeviceNumber)) + foreach (var pDriveVolume in pVolumes.Where(pDriveVolume => pDriveVolume.StorageDeviceInfo.DeviceNumber == pDrive.StorageDeviceInfo.DeviceNumber)) { if (null == pDriveInfo.PartitionNumbers) pDriveInfo.PartitionNumbers = new Collection(); - pDriveInfo.PartitionNumbers.Add(pDriveVolume.PartitionNumber); + pDriveInfo.PartitionNumbers.Add(pDriveVolume.StorageDeviceInfo.PartitionNumber); if (null == pDriveInfo.VolumeGuids) @@ -69,21 +66,18 @@ public static IEnumerable EnumeratePhysicalDrives() // Get logical drive from volume matching DeviceNumber and PartitionNumber. - foreach (var pDriveLogical in pLogicalDrives.Where(pDriveLogical => pDriveLogical.DeviceNumber == pDriveVolume.DeviceNumber && pDriveLogical.PartitionNumber == pDriveVolume.PartitionNumber)) + foreach (var pDriveLogical in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pDriveVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pDriveVolume.StorageDeviceInfo.PartitionNumber)) { if (null == pDriveInfo.LogicalDrives) pDriveInfo.LogicalDrives = new Collection(); - pDriveInfo.LogicalDrives.Add(pDriveLogical.DevicePath); + pDriveInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(pDriveLogical.DevicePath)); } } - populatedPhysicalDrives.Add(pDriveInfo); + yield return pDriveInfo; } - - - return populatedPhysicalDrives.OrderBy(pDriveInfo => pDriveInfo.DeviceNumber).ThenBy(pDriveInfo => pDriveInfo.PartitionNumber); } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index a9b649e2c..620683ab8 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -31,11 +31,14 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// [AlphaFS] Retrieves the physical drive on the Computer that is related to the volume GUID, logical drive name or . + /// [AlphaFS] Retrieves the physical drive on the Computer that is related to the logical drive name, volume GUID or . /// Do not call this method for every volume or logical drive on the system as each call queries all physical drives and associated volumes and logical drives. /// Instead, use method and property or . /// - /// A instance that represents the physical drive on the Computer. + /// A instance that represents the physical drive on the Computer or null on error/no data available. + /// + /// + /// /// /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". @@ -47,21 +50,26 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) bool isDrive; bool isVolume; bool isDeviceInfo; + string logicalDrive; devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); - - var pDriveInfo = GetPhysicalDriveInfoCore(devicePath, null, false); - if (null == pDriveInfo) + var storageInfo = GetStorageTypeInfoCore(devicePath, false); + + if (null == storageInfo) return null; - var partitionNumber = pDriveInfo.PartitionNumber; - + if (isDrive) + { + GetDevicePath(devicePath, out logicalDrive); + devicePath = logicalDrive; + } + - pDriveInfo = isDeviceInfo + var pDriveInfo = isDeviceInfo - ? EnumeratePhysicalDrives().FirstOrDefault(pDrive => pDrive.DeviceNumber == pDriveInfo.DeviceNumber && pDrive.PartitionNumber == partitionNumber) + ? EnumeratePhysicalDrives().FirstOrDefault(pDrive => pDrive.StorageDeviceInfo.DeviceNumber == storageInfo.DeviceNumber && pDrive.StorageDeviceInfo.PartitionNumber == storageInfo.PartitionNumber) : isVolume ? EnumeratePhysicalDrives().FirstOrDefault(pDrive => null != pDrive.VolumeGuids && pDrive.VolumeGuids.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) @@ -72,21 +80,20 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) if (null != pDriveInfo) - pDriveInfo.PartitionNumber = partitionNumber; + pDriveInfo.StorageDeviceInfo.PartitionNumber = storageInfo.PartitionNumber; return pDriveInfo; } - - /// [AlphaFS] Gets the physical drive information such as DeviceType, DeviceNumber, PartitionNumber and the serial number and Product ID. - /// A instance that represents the physical drive on the Computer or null on error. + /// A instance that represents the physical drive on the Computer or null on error/no data available. /// /// /// /// + /// A instance. /// /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". @@ -94,10 +101,11 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// /// A instance. /// + /// /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, DeviceInfo deviceInfo, bool getDeviceData) + internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(StorageDeviceInfo storageInfo, string devicePath, DeviceInfo deviceInfo, bool getDeviceData, bool getAllData) { var isDeviceInfo = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); @@ -105,83 +113,60 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(string devicePath, De devicePath = deviceInfo.DevicePath; - string logicalDrive; + if (null == storageInfo) + storageInfo = GetStorageTypeInfoCore(devicePath, false); - var pathToDevice = ValidateAndGetPathToDevice(devicePath, out logicalDrive); - - if (Utils.IsNullOrWhiteSpace(pathToDevice)) + if (null == storageInfo) return null; - var storageDevice = GetDeviceNumberAndType(pathToDevice); - - if (null == storageDevice) - return null; - - - var device = storageDevice.Value; - var diskNumber = device.DeviceNumber; - - var physicalDriveInfo = new PhysicalDriveInfo + var pDriveInfo = new PhysicalDriveInfo(storageInfo) { DevicePath = devicePath, - DeviceNumber = diskNumber, - PartitionNumber = device.PartitionNumber, // "FriendlyName" usually contains a more complete name, as seen in Windows Explorer. - Name = isDeviceInfo ? deviceInfo.FriendlyName : null + Name = isDeviceInfo ? deviceInfo.FriendlyName : null, }; - + if (getDeviceData) { - var physicalDrive = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, diskNumber.ToString(CultureInfo.InvariantCulture)); + //var physicalDrivePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, storageInfo.DeviceNumber.ToString(CultureInfo.InvariantCulture)); try { // Requires elevation. - SetDeviceData(physicalDrive, physicalDriveInfo); + PopulatePhysicalDriveInfo(getAllData, devicePath, pDriveInfo); } catch { } } - //if (null != logicalDrive) - //{ - try - { - // Requires elevation. - //GetVolumeDiskExtents(logicalDrive); + ////if (null != logicalDrive) + ////{ + // try + // { + // // Requires elevation. + // //GetVolumeDiskExtents(logicalDrive); - var pDrive = @"\\.\PhysicalDrive0"; + // var pDrive = @"\\.\PhysicalDrive0"; - GetDiskPartitions(pDrive); - GetDiskGeometry(pDrive); - GetDiskLayout(pDrive); - } - catch { } - //} + // GetDiskPartitions(pDrive); + // GetDiskGeometry(pDrive); + // GetDiskLayout(pDrive); + // } + // catch { } + ////} - return physicalDriveInfo; + return pDriveInfo; } - + /// Sets the physical drive properties such as FriendlyName, device size and serial number. Requires elevation. - private static void SetDeviceData(string physicalDrive, PhysicalDriveInfo physicalDriveInfo) + private static void PopulatePhysicalDriveInfo(bool getAllData, string devicePath, PhysicalDriveInfo physicalDriveInfo) { - // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes - // without accessing that file or device, even if GENERIC_READ access would have been denied. - // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. - //const int desiredAccess = 0; - - // Requires elevation for. - const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; - - //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - - - using (var safeHandle = OpenPhysicalDrive(physicalDrive, desiredAccess)) + using (var safeHandle = OpenPhysicalDrive(devicePath, FileSystemRights.Read | FileSystemRights.Write)) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { @@ -190,12 +175,16 @@ private static void SetDeviceData(string physicalDrive, PhysicalDriveInfo physic }; - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, physicalDrive, NativeMethods.DefaultFileBufferSize / 2)) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, devicePath, NativeMethods.DefaultFileBufferSize / 2)) { var storageDescriptor = safeBuffer.PtrToStructure(0); - physicalDriveInfo.BusType = (StorageBusType) storageDescriptor.BusType; + physicalDriveInfo.StorageDeviceInfo.BusType = (StorageBusType) storageDescriptor.BusType; + + if (!getAllData) + return; + physicalDriveInfo.CommandQueueing = storageDescriptor.CommandQueueing; @@ -222,80 +211,12 @@ private static void SetDeviceData(string physicalDrive, PhysicalDriveInfo physic var lastError = Marshal.GetLastWin32Error(); if (!success) - NativeError.ThrowException(lastError, string.Format(CultureInfo.InvariantCulture, "Drive: {0}", physicalDrive)); + NativeError.ThrowException(lastError, string.Format(CultureInfo.InvariantCulture, "Device: {0}", devicePath)); physicalDriveInfo.TotalSize = safeBuffer.ReadInt64(); } } } - - - /// Retrieves the storage DeviceType, DeviceNumber and PartitionNumber. No elevation needed. - private static NativeMethods.STORAGE_DEVICE_NUMBER? GetDeviceNumberAndType(string devicePath) - { - // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes - // without accessing that file or device, even if GENERIC_READ access would have been denied. - // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. - const int desiredAccess = 0; - - // Requires elevation for. - //const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; - - //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - - - // No elevation needed. - - using (var safeHandle = OpenPhysicalDrive(devicePath, desiredAccess)) - - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath)) - - return null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?) null; - } - - - private static string ValidateAndGetPathToDevice(string devicePath, out string logicalDrive) - { - bool isDrive; - bool isVolume; - bool isDeviceInfo; - - devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); - - devicePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", isDrive ? Path.LogicalDrivePrefix : string.Empty, Path.RemoveTrailingDirectorySeparator(devicePath)); - - logicalDrive = isDrive ? devicePath : null; - - return devicePath; - } - - - private static string ValidateDevicePath(string devicePath, out bool isDrive, out bool isVolume, out bool isDeviceInfo) - { - if (Utils.IsNullOrWhiteSpace(devicePath)) - throw new ArgumentNullException("devicePath"); - - - // Resolve single drive letter or get root directory information. - - devicePath = devicePath.Length == 1 ? devicePath + Path.VolumeSeparatorChar : Path.GetPathRoot(devicePath, false); - - var hasPath = !Utils.IsNullOrWhiteSpace(devicePath); - - - isDrive = hasPath && Path.IsLogicalDriveCore(devicePath, PathFormat.FullPath); - - isVolume = hasPath && devicePath.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase); - - isDeviceInfo = hasPath && !isDrive && !isVolume && devicePath.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal); - - - if (!hasPath || !isDrive && !isVolume && !isDeviceInfo) - throw new ArgumentException(Resources.Argument_must_be_DriveLetter_or_VolumeGuid_or_DevicePath, "devicePath"); - - - return Path.AddTrailingDirectorySeparator(devicePath, false); - } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageTypeInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageTypeInfo.cs new file mode 100644 index 000000000..30e0148ac --- /dev/null +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageTypeInfo.cs @@ -0,0 +1,114 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 Device + { + /// [AlphaFS] Get the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// A instance that represent the storage device on the Computer that is related to . + /// + /// + /// + /// + /// + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string (when is set to ). + /// + public static StorageDeviceInfo GetStorageTypeInfo(string devicePath) + { + return GetStorageTypeInfoCore(devicePath, false); + } + + + /// [AlphaFS] Get the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// A instance that represent the storage device on the Computer that is related to . + /// + /// + /// + /// + /// + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string (when is set to ). + /// + /// When true also get the which requires elevated rights. + public static StorageDeviceInfo GetStorageTypeInfo(string devicePath, bool getBusType) + { + return GetStorageTypeInfoCore(devicePath, getBusType); + } + + + /// [AlphaFS] Get the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// A instance that represent the storage device on the Computer that is related to . + /// + /// + /// + /// + /// + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string (when is set to ). + /// + /// When true also get the which requires elevated rights. + internal static StorageDeviceInfo GetStorageTypeInfoCore(string devicePath, bool getBusType) + { + string logicalDrive; + + var pathToDevice = GetDevicePath(devicePath, out logicalDrive); + + if (Utils.IsNullOrWhiteSpace(pathToDevice)) + return null; + + + // No elevation needed. + + using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) + + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath)) + { + var storage = null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?) null; + + if (null != storage) + { + var storageInfo = new StorageDeviceInfo((NativeMethods.STORAGE_DEVICE_NUMBER) storage); + + if (getBusType) + { + // Requires elevation. + + var pDriveInfo = GetPhysicalDriveInfoCore(storageInfo, pathToDevice, null, true, false); + + if (null != pDriveInfo) + storageInfo.BusType = pDriveInfo.StorageDeviceInfo.BusType; + } + + return storageInfo; + } + } + + return null; + } + } +} diff --git a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs index f6f9fc8f2..25c52b115 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs @@ -35,30 +35,33 @@ public sealed class PhysicalDriveInfo #region Constructors /// Initializes a PhysicalDriveInfo instance. - public PhysicalDriveInfo() + private PhysicalDriveInfo() { - PartitionNumber = -1; + StorageDeviceInfo = new StorageDeviceInfo + { + DeviceNumber = -1, + PartitionNumber = -1 + }; } /// Initializes a PhysicalDriveInfo instance. - public PhysicalDriveInfo(PhysicalDriveInfo pDriveInfo) : this() + public PhysicalDriveInfo(StorageDeviceInfo storageInfo) { - CopyTo(pDriveInfo, this); + StorageDeviceInfo = storageInfo; } - #endregion // Constructors - - - #region Properties - /// The bus type of the physical drive. - public StorageBusType BusType { get; internal set; } + /// Initializes a PhysicalDriveInfo instance. + public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) + { + CopyTo(physicalDriveInfo, this); + } + #endregion // Constructors - /// The index number of the physical drive. - public int DeviceNumber { get; internal set; } + #region Properties /// The path to the device. /// A string that represents the path to the device. @@ -82,34 +85,34 @@ public PhysicalDriveInfo(PhysicalDriveInfo pDriveInfo) : this() public bool RemovableMedia { get; internal set; } - /// Returns the "FriendlyName" of the physical drive. + /// The "FriendlyName" of the physical drive. public string Name { get; internal set; } - - /// Indicates the partition number of the device is returned in this member, if the device can be partitioned. Otherwise, -1 is returned. - public int PartitionNumber { get; internal set; } - - - /// Indicates the partition number of the device is returned in this member, if the device can be partitioned. Otherwise, -1 is returned. + + /// The partition numbers that are located on the physical drive. public Collection PartitionNumbers { get; internal set; } - /// The Partitions located on the physical drive. - public string[] Partitions { get; internal set; } + ///// The partitions that are located on the physical drive. + //public string[] Partitions { get; internal set; } /// The product revision of the physical drive. public string ProductRevision { get; internal set; } - /// Gets the serial number of the physical drive. If the physical drive has no serial number or the session is not elevated, this member is -1. + /// The storage device type and device- and partition number. + public StorageDeviceInfo StorageDeviceInfo { get; internal set; } + + + /// The serial number of the physical drive. If the physical drive has no serial number or the session is not elevated -1 is returned. public string SerialNumber { get; internal set; } - /// The total size of the physical drive. If the session is not elevated, this member is -1. + /// The total size of the physical drive. If the session is not elevated -1 is returned public long TotalSize { get; internal set; } - /// 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. + /// The total size of the physical drive, formatted as a unit size. public string TotalSizeUnitSize { get { return Utils.UnitSizeToText(TotalSize); } @@ -124,11 +127,37 @@ public string TotalSizeUnitSize #region Methods + /// Checks if the logical drive or volume is located on the physical drive. + /// + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// + public bool ContainsVolume(string devicePath) + { + bool isDrive; + bool isVolume; + bool isDeviceInfo; + + devicePath = Device.ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + + + if (isDrive && null != LogicalDrives) + { + devicePath = Path.RemoveTrailingDirectorySeparator(devicePath, false); + + return LogicalDrives.Any(driveName => driveName.Equals(devicePath, StringComparison.OrdinalIgnoreCase)); + } + + + return isVolume && null != VolumeGuids && VolumeGuids.Any(guid => guid.Equals(devicePath, StringComparison.OrdinalIgnoreCase)); + } + + /// Returns the "FriendlyName" of the physical drive. /// A string that represents this instance. public override string ToString() { - return Name; + return Name ?? DevicePath; } @@ -142,11 +171,13 @@ public override bool Equals(object obj) var other = obj as PhysicalDriveInfo; - return null != other && null != other.DevicePath && + return null != other && null != other.DevicePath && null != other.StorageDeviceInfo && other.DevicePath.Equals(DevicePath, StringComparison.OrdinalIgnoreCase) && - other.DeviceNumber.Equals(DeviceNumber) && other.PartitionNumber.Equals(PartitionNumber); + other.StorageDeviceInfo.Equals(StorageDeviceInfo) && + + other.StorageDeviceInfo.DeviceNumber.Equals(StorageDeviceInfo.DeviceNumber) && other.StorageDeviceInfo.PartitionNumber.Equals(StorageDeviceInfo.PartitionNumber); } @@ -182,10 +213,12 @@ private static void CopyTo(T source, T destination) { // Properties listed here should not be overwritten by the physical drive template. - var excludedProps = new[] {"PartitionNumber"}; + //var excludedProps = new[] {"PartitionNumber"}; + + //var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite && !excludedProps.Any(prop => prop.Equals(x.Name))).ToArray(); - var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite && !excludedProps.Any(prop => prop.Equals(x.Name))).ToArray(); + var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite).ToArray(); var dstProps = srcProps.ToArray(); diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs new file mode 100644 index 000000000..2054185e0 --- /dev/null +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -0,0 +1,126 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + /// Provides access to information of a device, on a local or remote host. + [Serializable] + [SecurityCritical] + public sealed class StorageDeviceInfo + { + #region Constructors + + /// Initializes a StorageDeviceInfo instance. + public StorageDeviceInfo() + { + BusType = StorageBusType.Unknown; + DeviceType = StorageDeviceType.Unknown; + } + + + internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() + { + DeviceType = device.DeviceType; + DeviceNumber = device.DeviceNumber; + PartitionNumber = device.PartitionNumber; + } + + #endregion // Constructors + + + #region Methods + + /// Returns storage device as: "DeviceNumber:PartitionNumber DeviceType/BusType". + /// A string that represents this instance. + public override string ToString() + { + return string.Format(CultureInfo.CurrentCulture, "{0}:{1} {2}/{3}", DeviceNumber, PartitionNumber, DeviceType.ToString(), BusType.ToString()); + } + + + /// Determines whether the specified Object is equal to the current Object. + /// Another object to compare to. + /// if the specified Object is equal to the current Object; otherwise, . + public override bool Equals(object obj) + { + if (null == obj || GetType() != obj.GetType()) + return false; + + var other = obj as StorageDeviceInfo; + + return null != other && other.DeviceType == DeviceType && other.DeviceNumber == DeviceNumber && other.PartitionNumber == PartitionNumber; + } + + + /// Serves as a hash function for a particular type. + /// A hash code for the current Object. + public override int GetHashCode() + { + return DeviceNumber + PartitionNumber + DeviceType.GetHashCode(); + } + + + /// Implements the operator == + /// A. + /// B. + /// The result of the operator. + public static bool operator ==(StorageDeviceInfo left, StorageDeviceInfo right) + { + return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); + } + + + /// Implements the operator != + /// A. + /// B. + /// The result of the operator. + public static bool operator !=(StorageDeviceInfo left, StorageDeviceInfo right) + { + return !(left == right); + } + + #endregion // Methods + + + #region Properties + + /// The storage bus type. + public StorageBusType BusType { get; internal set; } + + + /// The storage device type. + public StorageDeviceType DeviceType { get; internal set; } + + + /// The device number of the storage device, starting at 0. + public int DeviceNumber { get; internal set; } + + + /// The partition number of the storage device, starting at 1. If the device cannot be partitioned, like a CDROM, -1 is returned. + public int PartitionNumber { get; internal set; } + + #endregion // Properties + } +} diff --git a/AlphaFS/Device/Volume/VolumeInfo.cs b/AlphaFS/Device/Volume/VolumeInfo.cs index 94555094b..f507af3a9 100644 --- a/AlphaFS/Device/Volume/VolumeInfo.cs +++ b/AlphaFS/Device/Volume/VolumeInfo.cs @@ -178,6 +178,7 @@ public bool DirectAccess /// The volume GUID. + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public string Guid { get diff --git a/AlphaFS/Filesystem/Native Other/IoControlCode.cs b/AlphaFS/Filesystem/Native Other/IoControlCode.cs index 41ce7a0f7..72aeb3ba3 100644 --- a/AlphaFS/Filesystem/Native Other/IoControlCode.cs +++ b/AlphaFS/Filesystem/Native Other/IoControlCode.cs @@ -31,8 +31,8 @@ internal static partial class NativeMethods [Flags] internal enum IoControlCode : uint { - ///// Retrieves the physical location of a specified volume on one or more disks. - //IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), + /// Retrieves the physical location of a specified volume on one or more disks. + IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), /// Return properties of a storage device or adapter. The request indicates the kind of information to retrieve, such as inquiry data for a device or capabilities and limitations of an adapter. diff --git a/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs b/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs index b1474f03e..bab97923b 100644 --- a/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs +++ b/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs @@ -53,11 +53,15 @@ internal static bool IsLogicalDriveCore(string path, PathFormat pathFormat) } - // Don't use char.IsLetter() here as that can be misleading; The only valid drive letters are: A-Z. + path = GetRegularPathCore(path, GetFullPathOptions.None, false); + + var regularPath = path.StartsWith(LogicalDrivePrefix, StringComparison.OrdinalIgnoreCase) ? path.Substring(LogicalDrivePrefix.Length) : path; + + var c = regularPath.ToUpperInvariant()[0]; - var c = path.ToUpperInvariant()[0]; + // Don't use char.IsLetter() here as that can be misleading; The only valid drive letters are: A-Z. - return path[1] == VolumeSeparatorChar && c >= 'A' && c <= 'Z'; + return regularPath[1] == VolumeSeparatorChar && c >= 'A' && c <= 'Z'; } } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs index a489ed0cb..0fbcfe817 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs @@ -31,103 +31,134 @@ public enum DeviceGuid #region 1394 and 61883 Devices /// The BUS1394_CLASS_GUID device interface class is defined for 1394 bus devices. - [Description("6BDD1FC1-810F-11d0-BEC7-08002BE2092F")] Bus1394, + [Description("6BDD1FC1-810F-11d0-BEC7-08002BE2092F")] + Bus1394, /// The GUID_61883_CLASS device interface class is defined for devices in the 61883 device setup class. - [Description("7EBEFBC0-3200-11d2-B4C2-00A0C9697D07")] Guid61883, + [Description("7EBEFBC0-3200-11d2-B4C2-00A0C9697D07")] + Guid61883, #endregion // 1394 and 61883 Devices + #region Battery and ACPI devices /// The GUID_DEVICE_APPLICATIONLAUNCH_BUTTON device interface class is defined for Advanced Configuration and Power Interface (ACPI) application start buttons. - [Description("629758EE-986E-4D9E-8E47-DE27F8AB054D")] ApplicationLaunchButton, + [Description("629758EE-986E-4D9E-8E47-DE27F8AB054D")] + ApplicationLaunchButton, /// The GUID_DEVICE_BATTERY device interface class is defined for battery devices. - [Description("72631E54-78A4-11D0-BCF7-00AA00B7B32A")] Battery, + [Description("72631E54-78A4-11D0-BCF7-00AA00B7B32A")] + Battery, /// The GUID_DEVICE_LID device interface class is defined for Advanced Configuration and Power Interface (ACPI) lid devices. - [Description("4AFA3D52-74A7-11d0-be5e-00A0C9062857")] Lid, + [Description("4AFA3D52-74A7-11d0-be5e-00A0C9062857")] + Lid, /// The GUID_DEVICE_MEMORY device interface class is defined for Advanced Configuration and Power Interface (ACPI) memory devices. - [Description("3FD0F03D-92E0-45FB-B75C-5ED8FFB01021")] Memory, + [Description("3FD0F03D-92E0-45FB-B75C-5ED8FFB01021")] + Memory, /// The GUID_DEVICE_MESSAGE_INDICATOR device interface class is defined for Advanced Configuration and Power Interface (ACPI) message indicator devices. - [Description("CD48A365-FA94-4CE2-A232-A1B764E5D8B4")] MessageIndicator, + [Description("CD48A365-FA94-4CE2-A232-A1B764E5D8B4")] + MessageIndicator, /// The GUID_DEVICE_PROCESSOR device interface class is defined for Advanced Configuration and Power Interface (ACPI) processor devices. - [Description("97FADB10-4E33-40AE-359C-8BEF029DBDD0")] Processor, + [Description("97FADB10-4E33-40AE-359C-8BEF029DBDD0")] + Processor, /// The GUID_DEVICE_SYS_BUTTON device interface classis defined for Advanced Configuration and Power Interface (ACPI) system power button devices. - [Description("4AFA3D53-74A7-11d0-be5e-00A0C9062857")] SysButton, + [Description("4AFA3D53-74A7-11d0-be5e-00A0C9062857")] + SysButton, /// The GUID_DEVICE_THERMAL_ZONE device interface class is defined for Advanced Configuration and Power Interface (ACPI) thermal zone devices. - [Description("4AFA3D51-74A7-11d0-be5e-00A0C9062857")] ThermalZone, + [Description("4AFA3D51-74A7-11d0-be5e-00A0C9062857")] + ThermalZone, #endregion // Battery and ACPI devices + #region Bluetooth Devices /// The GUID_BTHPORT_DEVICE_INTERFACE device interface class is defined for Bluetooth radios. - [Description("0850302A-B344-4fda-9BE9-90576B8D46F0")] Bluetooth, + [Description("0850302A-B344-4fda-9BE9-90576B8D46F0")] + Bluetooth, #endregion // Bluetooth Devices + #region Display and Image Devices /// 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. - [Description("FDE5BBA4-B3F9-46FB-BDAA-0728CE3100B4")] Brightness, + [Description("FDE5BBA4-B3F9-46FB-BDAA-0728CE3100B4")] + Brightness, /// The GUID_DEVINTERFACE_DISPLAY_ADAPTER device interface class is defined for display views that are supported by display adapters. - [Description("5B45201D-F2F2-4F3B-85BB-30FF1F953599")] DisplayAdapter, + [Description("5B45201D-F2F2-4F3B-85BB-30FF1F953599")] + DisplayAdapter, /// 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. - [Description("2564AA4F-DDDB-4495-B497-6AD4A84163D7")] I2C, + [Description("2564AA4F-DDDB-4495-B497-6AD4A84163D7")] + I2C, /// The GUID_DEVINTERFACE_IMAGE device interface class is defined for WIA devices and Still Image (STI) devices, including digital cameras and scanners. - [Description("6BDD1FC6-810F-11D0-BEC7-08002BE2092F")] StillImage, + [Description("6BDD1FC6-810F-11D0-BEC7-08002BE2092F")] + StillImage, /// The GUID_DEVINTERFACE_MONITOR device interface class is defined for monitor devices. - [Description("E6F07B5F-EE97-4a90-B076-33F57BF4EAA7")] Monitor, + [Description("E6F07B5F-EE97-4a90-B076-33F57BF4EAA7")] + Monitor, /// 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. - [Description("BF4672DE-6B4E-4BE4-A325-68A91EA49C09")] OutputProtectionManagement, + [Description("BF4672DE-6B4E-4BE4-A325-68A91EA49C09")] + OutputProtectionManagement, /// The GUID_DEVINTERFACE_VIDEO_OUTPUT_ARRIVAL device interface class is defined for child devices of display devices. - [Description("1AD9E4F0-F88D-4360-BAB9-4C2D55E564CD")] VideoOutputArrival, + [Description("1AD9E4F0-F88D-4360-BAB9-4C2D55E564CD")] + VideoOutputArrival, /// The GUID_DISPLAY_DEVICE_ARRIVAL device interface class is defined for display adapters. - [Description("1CA05180-A699-450A-9A0C-DE4FBE3DDD89")] DisplayDeviceArrival, + [Description("1CA05180-A699-450A-9A0C-DE4FBE3DDD89")] + DisplayDeviceArrival, #endregion // Display and Image Devices + #region Interactive Input Devices /// The GUID_DEVINTERFACE_HID device interface class is defined for HID collections. - [Description("4D1E55B2-F16F-11CF-88CB-001111000030")] Hid, + [Description("4D1E55B2-F16F-11CF-88CB-001111000030")] + Hid, /// The GUID_DEVINTERFACE_KEYBOARD device interface class is defined for keyboard devices. - [Description("4D1E55B2-F16F-11CF-88CB-001111000030")] Keyboard, + [Description("4D1E55B2-F16F-11CF-88CB-001111000030")] + Keyboard, /// The GUID_DEVINTERFACE_MOUSE device interface class is defined for mouse devices. - [Description("378DE44C-56EF-11D1-BC8C-00A0C91405DD")] Mouse, + [Description("378DE44C-56EF-11D1-BC8C-00A0C91405DD")] + Mouse, #endregion // Interactive Input Devices + #region Modem Devices /// The GUID_DEVINTERFACE_MODEM device interface class is defined for modem devices. - [Description("2C7089AA-2E0E-11D1-B114-00C04FC2AAE4")] Modem, + [Description("2C7089AA-2E0E-11D1-B114-00C04FC2AAE4")] + Modem, #endregion // Modem Devices + #region Network Devices /// The GUID_DEVINTERFACE_NET device interface class is defined for network devices. - [Description("CAC88484-7515-4C03-82E6-71A87ABAC361")] Network, + [Description("CAC88484-7515-4C03-82E6-71A87ABAC361")] + Network, #endregion // Network Devices + #region Serial and Parallel Port Devices /// The GUID_DEVINTERFACE_COMPORT device interface class is defined for COM ports. @@ -136,66 +167,76 @@ public enum DeviceGuid ComPort, /// The GUID_DEVINTERFACE_PARALLEL device interface class is defined for parallel ports that support an IEEE 1284-compatible hardware interface. - [Description("97F76EF0-F883-11D0-AF1F-0000F800845C")] Parallel, + [Description("97F76EF0-F883-11D0-AF1F-0000F800845C")] + Parallel, /// The GUID_DEVINTERFACE_PARCLASS device interface class is defined for devices that are attached to a parallel port. - [Description("811FC6A5-F728-11D0-A537-0000F8753ED1")] ParallelClass, + [Description("811FC6A5-F728-11D0-A537-0000F8753ED1")] + ParallelClass, /// The GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR device interface class is defined for Plug and Play (PnP) serial ports. - [Description("4D36E978-E325-11CE-BFC1-08002BE10318")] SerialEnumBusEnumerator, + [Description("4D36E978-E325-11CE-BFC1-08002BE10318")] + SerialEnumBusEnumerator, #endregion // Serial and Parallel Port Devices + #region Storage Devices /// The GUID_DEVINTERFACE_CDCHANGER device interface class is defined for CD-ROM changer devices. - [Description("53F56312-B6BF-11D0-94F2-00A0C91EFB8B")] CDChanger, + [Description("53F56312-B6BF-11D0-94F2-00A0C91EFB8B")] + CDChanger, /// The GUID_DEVINTERFACE_CDROM device interface class is defined for CD-ROM storage devices. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CDROM")] [Description("53F56308-B6BF-11D0-94F2-00A0C91EFB8B")] - CDROM, + CDRom, /// The GUID_DEVINTERFACE_DISK device interface class is defined for hard disk storage devices. - [Description("53F56307-B6BF-11D0-94F2-00A0C91EFB8B")] Disk, + [Description("53F56307-B6BF-11D0-94F2-00A0C91EFB8B")] + Disk, /// The GUID_DEVINTERFACE_FLOPPY device interface class is defined for floppy disk storage devices. - [Description("53F56311-B6BF-11D0-94F2-00A0C91EFB8B")] Floppy, + [Description("53F56311-B6BF-11D0-94F2-00A0C91EFB8B")] + Floppy, /// The GUID_DEVINTERFACE_MEDIUMCHANGER device interface class is defined for medium changer devices. - [Description("53F56310-B6BF-11D0-94F2-00A0C91EFB8B")] MediumChanger, + [Description("53F56310-B6BF-11D0-94F2-00A0C91EFB8B")] + MediumChanger, /// The GUID_DEVINTERFACE_PARTITION device interface class is defined for partition devices. - [Description("53F5630A-B6BF-11D0-94F2-00A0C91EFB8B")] Partition, + [Description("53F5630A-B6BF-11D0-94F2-00A0C91EFB8B")] + Partition, /// The GUID_DEVINTERFACE_STORAGEPORT device interface class is defined for storage port devices. - [Description("2ACCFE60-C130-11D2-B082-00A0C91EFB8B")] StoragePort, + [Description("2ACCFE60-C130-11D2-B082-00A0C91EFB8B")] + StoragePort, /// The GUID_DEVINTERFACE_TAPE device interface class is defined for tape storage devices. - [Description("53F5630B-B6BF-11D0-94F2-00A0C91EFB8B")] Tape, + [Description("53F5630B-B6BF-11D0-94F2-00A0C91EFB8B")] + Tape, /// The GUID_DEVINTERFACE_VOLUME device interface class is defined for volume devices. - [Description("53F5630D-B6BF-11D0-94F2-00A0C91EFB8B")] Volume, + [Description("53F5630D-B6BF-11D0-94F2-00A0C91EFB8B")] + Volume, /// The GUID_DEVINTERFACE_WRITEONCEDISK device interface class is defined for write-once disk devices. - [Description("53F5630C-B6BF-11D0-94F2-00A0C91EFB8B")] WriteOnceDisk, + [Description("53F5630C-B6BF-11D0-94F2-00A0C91EFB8B")] + WriteOnceDisk, #endregion // Storage Devices + #region USB Devices /// The GUID_DEVINTERFACE_USB_DEVICE device interface class is defined for USB devices that are attached to a USB hub. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] [Description("A5DCBF10-6530-11D2-901F-00C04FB951ED")] UsbDevice, /// The GUID_DEVINTERFACE_USB_HOST_CONTROLLER device interface class is defined for USB host controller devices. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] [Description("3ABF6F2D-71C4-462A-8A92-1E6861E6AF27")] UsbHostController, /// The GUID_DEVINTERFACE_USB_HUB device interface class is defined for USB hub devices. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] [Description("F18A0E88-C30C-11D0-8815-00A0C906BED8")] UsbHub diff --git a/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs b/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs index d4d7e0fce..ef2a52cc0 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs @@ -19,6 +19,8 @@ * THE SOFTWARE. */ +using System; + namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods @@ -57,7 +59,7 @@ internal enum SetupDiGetDeviceRegistryPropertyEnum Class = 7, /// SPDRP_CLASSGUID - /// Represents the of the device setup class that a device instance belongs to. + /// Represents the of the device setup class that a device instance belongs to. /// ClassGuid = 8, @@ -166,4 +168,4 @@ internal enum SetupDiGetDeviceRegistryPropertyEnum BaseContainerId = 36 } } -} \ No newline at end of file +} diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs index bd81d5172..b631ae9d9 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Filesystem public enum StorageBusType { /// Indicates an unknown bus type. - None = NativeMethods.STORAGE_BUS_TYPE.BusTypeUnknown, + Unknown = NativeMethods.STORAGE_BUS_TYPE.BusTypeUnknown, /// Indicates a SCSI bus type. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SCSI")] diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs index 88bceaba7..f36342681 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs @@ -35,12 +35,10 @@ public enum StorageDeviceType Beep = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BEEP, /// FILE_DEVICE_CD_ROM parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CDROM")] - CDROM = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM, + CDRom = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM, /// FILE_DEVICE_CD_ROM_FILE_SYSTEM parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CDROM")] - CDROMFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM_FILE_SYSTEM, + CDRomFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM_FILE_SYSTEM, /// FILE_DEVICE_CONTROLLER parameter. Controller = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CONTROLLER, diff --git a/AlphaFS/Resources.Designer.cs b/AlphaFS/Resources.Designer.cs index 6f979e275..d6d69ffee 100644 --- a/AlphaFS/Resources.Designer.cs +++ b/AlphaFS/Resources.Designer.cs @@ -251,7 +251,7 @@ internal static string InvalidDriveLetterArgument { } /// - /// Looks up a localized string similar to Argument must be a drive letter: "C" or RootDir: "C:\". + /// Looks up a localized string similar to Argument must be a drive letter: "C", "C:" or RootDir: "C:\". /// internal static string InvalidLogicalDriveArgument { get { diff --git a/AlphaFS/Resources.resx b/AlphaFS/Resources.resx index 49149f86a..099a4fc09 100644 --- a/AlphaFS/Resources.resx +++ b/AlphaFS/Resources.resx @@ -254,7 +254,7 @@ Argument must be a drive letter: "C", RootDir: "C:\" or UNC path: "\\server\share" - Argument must be a drive letter: "C" or RootDir: "C:\" + Argument must be a drive letter: "C", "C:" or RootDir: "C:\" Argument must be a drive letter: "C", "C:\" or Volume GUID. From 3a99019a9cae86f4c554266317716a55c2b5de4d Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 15 Feb 2018 12:18:58 +0100 Subject: [PATCH 045/133] -Method EnumeratePhysicalDrives now shows CDRom drives; -Renamed method: Device.GetStorageTypeInfo to: Device.GetStorageDeviceInfo; -Added property PhysicalDriveInfo.DeviceDescription; -Code improvement, work in progress; --- .../AlphaFS_Device.EnumerateDevices.cs | 7 +- ....GetStorageDeviceInfo_FromLogicalDrive.cs} | 4 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 2 +- AlphaFS/AlphaFS.csproj | 2 +- AlphaFS/Device/Device.EnumerateDevices.cs | 68 +++--- AlphaFS/Device/Device.GetDeviceIoData.cs | 5 +- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 85 +++---- AlphaFS/Device/Device.InvokeDeviceIoData.cs | 4 +- AlphaFS/Device/DeviceInfo.cs | 6 +- .../Device.CreateDirectoryJunction.cs | 15 +- .../Device.DeleteDirectoryJunction.cs | 4 +- .../Junctions, Links/Device.GetLinkTarget.cs | 32 +-- .../Device.EnumeratePhysicalDrives.cs | 108 ++++++++- .../Device.GetPhysicalDriveInfo.cs | 35 ++- ...Info.cs => Device.GetStorageDeviceInfo.cs} | 45 ++-- .../PhysicalDriveInfo/PhysicalDriveInfo.cs | 14 +- AlphaFS/Device/Volume/VolumeInfo.cs | 2 +- .../NativeMethods.DeviceManagement.cs | 207 ++++++++---------- .../Structures, Enumerations/DeviceGuid.cs | 184 +++++++++++++++- .../SetupDiGetDeviceRegistryPropertyEnum.cs | 14 +- .../SafeGlobalMemoryBufferHandle.cs | 21 +- AlphaFS/Win32Errors.cs | 3 + 22 files changed, 542 insertions(+), 325 deletions(-) rename AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/{AlphaFS_Device.GetStorageTypeInfo.cs => AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs} (95%) rename AlphaFS/Device/PhysicalDriveInfo/{Device.GetStorageTypeInfo.cs => Device.GetStorageDeviceInfo.cs} (77%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs index 1efe1d062..4fab7742e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs @@ -40,7 +40,7 @@ public void AlphaFS_Device_EnumerateDevices_Local_Success() UnitTestConstants.PrintUnitTestHeader(false); - var tempPath = UnitTestConstants.LocalHost; + var host = UnitTestConstants.LocalHost; var classCount = 0; foreach (var deviceClass in EnumMemberToList()) @@ -49,8 +49,7 @@ public void AlphaFS_Device_EnumerateDevices_Local_Success() Console.WriteLine("#{0:000}\tClass: [{1}]", ++classCount, deviceClass); - foreach (var device in Alphaleonis.Win32.Filesystem.Device.EnumerateDevices(tempPath, deviceClass)) - + foreach (var device in Alphaleonis.Win32.Filesystem.Device.EnumerateDevices(host, deviceClass)) UnitTestConstants.Dump(device, -24); } @@ -72,7 +71,7 @@ private static IEnumerable EnumMemberToList() var enumValArray = Enum.GetValues(enumType).Cast().OrderBy(e => e.ToString()).ToList(); var enumValList = new List(enumValArray.Count); - enumValList.AddRange(enumValArray.Select(val => (T)Enum.Parse(enumType, val.ToString()))); + enumValList.AddRange(enumValArray.Select(val => (T) Enum.Parse(enumType, val.ToString()))); return enumValList; } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageTypeInfo.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs similarity index 95% rename from AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageTypeInfo.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index 5716c3291..09c97ad57 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageTypeInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDriveInfoTest [TestMethod] - public void AlphaFS_Device_GetStorageTypeInfo_FromLogicalDrive_Success() + public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -43,7 +43,7 @@ public void AlphaFS_Device_GetStorageTypeInfo_FromLogicalDrive_Success() Console.WriteLine(); Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, drive.Name); - var storageInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageTypeInfo(drive.Name, true); + var storageInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageDeviceInfo(drive.Name, true); UnitTestConstants.Dump(storageInfo, -15); diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 813d552fe..cd3662f38 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -150,7 +150,7 @@ - + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index fb294f962..09bf9cb02 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -202,7 +202,7 @@ - + diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Device.EnumerateDevices.cs index 48abe870b..f839e9af6 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -35,7 +35,7 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) { - return EnumerateDevicesCore(null, deviceGuid); + return EnumerateDevicesCore(null, deviceGuid, true); } @@ -46,7 +46,7 @@ public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) [SecurityCritical] public static IEnumerable EnumerateDevices(string hostName, DeviceGuid deviceGuid) { - return EnumerateDevicesCore(hostName, deviceGuid); + return EnumerateDevicesCore(hostName, deviceGuid, true); } @@ -54,7 +54,7 @@ public static IEnumerable EnumerateDevices(string hostName, DeviceGu /// [AlphaFS] Enumerates all available devices on the local or remote host. [SecurityCritical] - internal static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid interfaceGuid, bool getAllProperties = true) + internal static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid interfaceGuid, bool getAllProperties) { // CM_Connect_Machine() // MSDN Note: Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed. @@ -109,17 +109,14 @@ internal static IEnumerable EnumerateDevicesCore(string hostName, De var deviceInfo = new DeviceInfo(hostName) { ClassGuid = deviceGuid, - DevicePath = GetInterfaceDetails(safeHandle, ref interfaceData, ref diData).DevicePath + DevicePath = GetDeviceInterfaceDetail(safeHandle, ref interfaceData, ref diData).DevicePath, + InstanceID = GetDeviceInstanceID(safeMachineHandle, hostName, diData) }; if (getAllProperties) - { SetDeviceProperties(safeHandle, deviceInfo, diData); - deviceInfo.InstanceID = GetDeviceInstanceID(safeMachineHandle, hostName, diData); - } - else SetMinimalDeviceProperties(safeHandle, deviceInfo, diData); @@ -174,13 +171,9 @@ private static string GetDeviceInstanceID(SafeCmConnectMachineHandle safeMachine /// Builds a Device Interface Detail Data structure. /// An initialized NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA instance. [SecurityCritical] - private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetInterfaceDetails(SafeHandle safeHandle, ref NativeMethods.SP_DEVICE_INTERFACE_DATA interfaceData, ref NativeMethods.SP_DEVINFO_DATA infoData) + 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 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); @@ -189,7 +182,6 @@ private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetInterfaceDetails if (!success) NativeError.ThrowException(lastError); - return didd; } @@ -197,51 +189,45 @@ private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetInterfaceDetails [SecurityCritical] private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum property) { - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize / 4)) - { - uint regDataType; + var bufferSize = NativeMethods.DefaultFileBufferSize / 8; - var success = NativeMethods.SetupDiGetDeviceRegistryProperty(safeHandle, ref infoData, property, out regDataType, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero); + 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(); + var lastError = Marshal.GetLastWin32Error(); - // 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 (success) + return safeBuffer.PtrToStringUni(); - if (!success) - { - if (lastError != Win32Errors.ERROR_INVALID_DATA) - NativeError.ThrowException(lastError); + // 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. - return string.Empty; - } + if (lastError == Win32Errors.ERROR_INVALID_DATA) + return string.Empty; - return safeBuffer.PtrToStringUni(); - } + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, property.ToString()); + } } [SecurityCritical] private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) { - deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.BaseContainerId)); - - deviceInfo.CompatibleIds = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.CompatibleIds); + SetMinimalDeviceProperties(safeHandle, deviceInfo, infoData); - deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class); - deviceInfo.DeviceDescription = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceDescription); + deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.BaseContainerId)); - //deviceInfo.DeviceType = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceType); + 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.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); - deviceInfo.HardwareId = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.HardwareId); deviceInfo.LocationInformation = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.LocationInformation); @@ -261,11 +247,11 @@ private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo { 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.DeviceType = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceType); - if (Utils.IsNullOrWhiteSpace(deviceInfo.FriendlyName)) - deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceDescription); + deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); } diff --git a/AlphaFS/Device/Device.GetDeviceIoData.cs b/AlphaFS/Device/Device.GetDeviceIoData.cs index 7189ddcd6..f30494e5e 100644 --- a/AlphaFS/Device/Device.GetDeviceIoData.cs +++ b/AlphaFS/Device/Device.GetDeviceIoData.cs @@ -35,15 +35,14 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa { NativeMethods.IsValidHandle(safeHandle); - //var nativeOverlapped = new NativeOverlapped(); + var bufferSize = size > -1 ? size : Marshal.SizeOf(typeof(T)); while (true) { - uint bytesReturned; var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index 99a6d8506..fc2c2959b 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -31,9 +31,9 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Device { // https://github.com/t00/TestCrypt/blob/master/TestCrypt/PhysicalDrive.cs - + [SecurityCritical] - internal static NativeMethods.PARTITION_INFORMATION_EX? GetDiskPartitions(string logicalDrive) + internal static object GetDriveStuff(string logicalDrive) { // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. @@ -47,81 +47,62 @@ public static partial class Device using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) - - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_PARTITION_INFO_EX, logicalDrive)) { - if (null != safeBuffer) + // DRIVE_LAYOUT_INFORMATION_EX + + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, logicalDrive)) { - var structure = safeBuffer.PtrToStructure(0); + if (null != safeBuffer) + { + var structure = safeBuffer.PtrToStructure(0); - return structure; + //return structure; + } } - } - - return null; - } - - - [SecurityCritical] - internal static NativeMethods.DRIVE_LAYOUT_INFORMATION_EX? GetDiskLayout(string logicalDrive) - { - // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes - // without accessing that file or device, even if GENERIC_READ access would have been denied. - // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. - //const int desiredAccess = 0; - // Requires elevation. - const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; - //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; + // DISK_GEOMETRY_EX - - using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) - - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, logicalDrive)) - { - if (null != safeBuffer) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, logicalDrive)) { - var structure = safeBuffer.PtrToStructure(0); + if (null != safeBuffer) + { + var structure = safeBuffer.PtrToStructure(0); - return structure; + //return structure; + } } - } - return null; - } + // VOLUME_DISK_EXTENTS - [SecurityCritical] - internal static NativeMethods.DISK_GEOMETRY_EX? GetDiskGeometry(string logicalDrive) - { - // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes - // without accessing that file or device, even if GENERIC_READ access would have been denied. - // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. - //const int desiredAccess = 0; + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, logicalDrive)) + { + if (null != safeBuffer) + { + var structure = safeBuffer.PtrToStructure(0); - // Requires elevation. - const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; + //return structure; + } + } - //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - - using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) + // PARTITION_INFORMATION_EX - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, logicalDrive)) - { - if (null != safeBuffer) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_PARTITION_INFO_EX, logicalDrive)) { - var structure = safeBuffer.PtrToStructure(0); + if (null != safeBuffer) + { + var structure = safeBuffer.PtrToStructure(0); - return structure; + //return structure; + } } } return null; } - //[SecurityCritical] //internal static void GetVolumeDiskExtents(string logicalDrive) //{ diff --git a/AlphaFS/Device/Device.InvokeDeviceIoData.cs b/AlphaFS/Device/Device.InvokeDeviceIoData.cs index 0f89eaaf0..95d398130 100644 --- a/AlphaFS/Device/Device.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Device.InvokeDeviceIoData.cs @@ -41,11 +41,9 @@ private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle while (true) { - uint bytesReturned; - var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - var success = NativeMethods.DeviceIoControlAnyObjectGetSet(safeHandle, controlCode, anyObject, (uint) bufferSize, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoControlAnyObjectGetSet(safeHandle, controlCode, anyObject, (uint) bufferSize, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/DeviceInfo.cs b/AlphaFS/Device/DeviceInfo.cs index c466dcee4..a17a99c2a 100644 --- a/AlphaFS/Device/DeviceInfo.cs +++ b/AlphaFS/Device/DeviceInfo.cs @@ -60,7 +60,7 @@ public DeviceInfo(string host) [SecurityCritical] public IEnumerable EnumerateDevices(DeviceGuid deviceGuid) { - return Device.EnumerateDevicesCore(HostName, deviceGuid); + return Device.EnumerateDevicesCore(HostName, deviceGuid, true); } #endregion // Methods @@ -91,8 +91,8 @@ public IEnumerable EnumerateDevices(DeviceGuid deviceGuid) /// The device interface path. public string DevicePath { get; internal set; } - - ///// Represents the device type of a device instance. + + ///// The device type of a device instance. //public string DeviceType { get; internal set; } diff --git a/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs b/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs index 86f234e7e..d21d66c3a 100644 --- a/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs +++ b/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs @@ -36,17 +36,20 @@ internal static void CreateDirectoryJunction(SafeFileHandle safeHandle, string d var header = new NativeMethods.ReparseDataBufferHeader { ReparseTag = ReparsePointTag.MountPoint, - ReparseDataLength = (ushort)(targetDirBytes.Length + 12) + ReparseDataLength = (ushort) (targetDirBytes.Length + 12) }; + var mountPoint = new NativeMethods.MountPointReparseBuffer { SubstituteNameOffset = 0, - SubstituteNameLength = (ushort)targetDirBytes.Length, - PrintNameOffset = (ushort)(targetDirBytes.Length + UnicodeEncoding.CharSize), + SubstituteNameLength = (ushort) targetDirBytes.Length, + + PrintNameOffset = (ushort) (targetDirBytes.Length + UnicodeEncoding.CharSize), PrintNameLength = 0 }; + var reparseDataBuffer = new NativeMethods.REPARSE_DATA_BUFFER { ReparseTag = header.ReparseTag, @@ -54,12 +57,14 @@ internal static void CreateDirectoryJunction(SafeFileHandle safeHandle, string d SubstituteNameOffset = mountPoint.SubstituteNameOffset, SubstituteNameLength = mountPoint.SubstituteNameLength, + PrintNameOffset = mountPoint.PrintNameOffset, PrintNameLength = mountPoint.PrintNameLength, PathBuffer = new byte[MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 16] // 16368 }; + targetDirBytes.CopyTo(reparseDataBuffer.PathBuffer, 0); @@ -67,10 +72,10 @@ internal static void CreateDirectoryJunction(SafeFileHandle safeHandle, string d { safeBuffer.StructureToPtr(reparseDataBuffer, false); - uint bytesReturned; - var success = NativeMethods.DeviceIoJunctions(safeHandle, NativeMethods.IoControlCode.FSCTL_SET_REPARSE_POINT, safeBuffer, (uint)(targetDirBytes.Length + 20), IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoJunctions(safeHandle, NativeMethods.IoControlCode.FSCTL_SET_REPARSE_POINT, safeBuffer, (uint) (targetDirBytes.Length + 20), IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); + if (!success) NativeError.ThrowException(lastError, directoryPath); } diff --git a/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs b/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs index ff15dc2e7..3a979e18b 100644 --- a/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs +++ b/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs @@ -42,10 +42,10 @@ internal static void DeleteDirectoryJunction(SafeFileHandle safeHandle) { safeBuffer.StructureToPtr(reparseDataBuffer, false); - uint bytesReturned; - var success = NativeMethods.DeviceIoJunctions(safeHandle, NativeMethods.IoControlCode.FSCTL_DELETE_REPARSE_POINT, safeBuffer, REPARSE_DATA_BUFFER_HEADER_SIZE, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoJunctions(safeHandle, NativeMethods.IoControlCode.FSCTL_DELETE_REPARSE_POINT, safeBuffer, REPARSE_DATA_BUFFER_HEADER_SIZE, IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); + if (!success) NativeError.ThrowException(lastError); } diff --git a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs index 52c7a799a..ba56e7978 100644 --- a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs +++ b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs @@ -88,38 +88,24 @@ internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, stri [SecurityCritical] private static SafeGlobalMemoryBufferHandle GetLinkTargetData(SafeFileHandle safeHandle, string reparsePath) { - var safeBuffer = new SafeGlobalMemoryBufferHandle(MAXIMUM_REPARSE_DATA_BUFFER_SIZE); + NativeMethods.IsValidHandle(safeHandle); + + var bufferSize = MAXIMUM_REPARSE_DATA_BUFFER_SIZE; while (true) { - uint bytesReturned; - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); + var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); + + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, 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; - } + if (success) + return safeBuffer; - if (lastError != Win32Errors.ERROR_SUCCESS) - NativeError.ThrowException(lastError, reparsePath); - } - - else - break; + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, reparsePath); } - - - return safeBuffer; } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs index dc0ac1516..abe3911df 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; @@ -33,49 +34,132 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrives() { - var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, null, deviceInfo, true, true)).Where(physicalDrive => null != physicalDrive).ToArray(); + var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, null, deviceInfo, true)).Where(physicalDrive => null != physicalDrive).ToArray(); + + var pVolumes = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(null, volumeGuid, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); - var pVolumes = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(null, volumeGuid, null, false, false)).Where(physicalDrive => null != physicalDrive).ToArray(); - - var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(null, driveName, null, false, false)).Where(physicalDrive => null != physicalDrive).ToArray(); + var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(null, driveName, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); foreach (var pDrive in physicalDrives) { var pDriveInfo = new PhysicalDriveInfo(pDrive) { - StorageDeviceInfo = {PartitionNumber = pDrive.StorageDeviceInfo.PartitionNumber} + StorageDeviceInfo = + { + DeviceNumber = pDrive.StorageDeviceInfo.DeviceNumber, + PartitionNumber = pDrive.StorageDeviceInfo.PartitionNumber + } }; // Get volume from physical drive matching DeviceNumber. - foreach (var pDriveVolume in pVolumes.Where(pDriveVolume => pDriveVolume.StorageDeviceInfo.DeviceNumber == pDrive.StorageDeviceInfo.DeviceNumber)) + foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDriveInfo.StorageDeviceInfo.DeviceNumber)) { - if (null == pDriveInfo.PartitionNumbers) - pDriveInfo.PartitionNumbers = new Collection(); + // Add device volume labels. + + if (null == pDriveInfo.VolumeLabels) + pDriveInfo.VolumeLabels = new Collection(); + + pDriveInfo.VolumeLabels.Add(pVolume.Name); + + + // Add device partition index numbers. - pDriveInfo.PartitionNumbers.Add(pDriveVolume.StorageDeviceInfo.PartitionNumber); + if (null == pDriveInfo.PartitionIndexes) + pDriveInfo.PartitionIndexes = new Collection(); + pDriveInfo.PartitionIndexes.Add(pVolume.StorageDeviceInfo.PartitionNumber); + + + // Add device volume GUIDs. if (null == pDriveInfo.VolumeGuids) pDriveInfo.VolumeGuids = new Collection(); - pDriveInfo.VolumeGuids.Add(pDriveVolume.DevicePath); + pDriveInfo.VolumeGuids.Add(pVolume.DevicePath); + + // Get logical drive from volume matching DeviceNumber and PartitionNumber. - foreach (var pDriveLogical in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pDriveVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pDriveVolume.StorageDeviceInfo.PartitionNumber)) + foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pVolume.StorageDeviceInfo.PartitionNumber)) { if (null == pDriveInfo.LogicalDrives) pDriveInfo.LogicalDrives = new Collection(); - pDriveInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(pDriveLogical.DevicePath)); + pDriveInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(pLogicalDrive.DevicePath)); } } + yield return pDriveInfo; + } + + + // Windows Disk Management shows CD-ROM so mimic that behaviour. + var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, null, deviceInfo, true)).Where(physicalDrive => null != physicalDrive).ToArray(); + + foreach (var pCdRom in cdRoms) + { + var pDriveInfo = new PhysicalDriveInfo(pCdRom) + { + StorageDeviceInfo = + { + DeviceNumber = pCdRom.StorageDeviceInfo.DeviceNumber, + PartitionNumber = pCdRom.StorageDeviceInfo.PartitionNumber + } + }; + + + // Get volume from CDRom matching DeviceNumber. + + var pVolume = pVolumes.FirstOrDefault(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDriveInfo.StorageDeviceInfo.DeviceNumber && pVol.StorageDeviceInfo.PartitionNumber == pDriveInfo.StorageDeviceInfo.PartitionNumber); + + if (null != pVolume) + { + // Add device volume labels. + + if (null == pDriveInfo.VolumeLabels) + pDriveInfo.VolumeLabels = new Collection(); + + pDriveInfo.VolumeLabels.Add(pVolume.Name); + + + // Add device partition index numbers. + + if (null == pDriveInfo.PartitionIndexes) + pDriveInfo.PartitionIndexes = new Collection(); + + pDriveInfo.PartitionIndexes.Add(pVolume.StorageDeviceInfo.PartitionNumber); + + + // Add device volume GUIDs. + + if (null == pDriveInfo.VolumeGuids) + pDriveInfo.VolumeGuids = new Collection(); + + pDriveInfo.VolumeGuids.Add(pVolume.DevicePath); + + + + + // Get logical drive from CDRom matching DeviceNumber and PartitionNumber. + + var logicalDrive = pLogicalDrives.FirstOrDefault(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pVolume.StorageDeviceInfo.PartitionNumber); + + if (null != logicalDrive) + { + if (null == pDriveInfo.LogicalDrives) + pDriveInfo.LogicalDrives = new Collection(); + + pDriveInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(logicalDrive.DevicePath)); + } + } + + yield return pDriveInfo; } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index 620683ab8..ec67fa41c 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -54,7 +54,7 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); - var storageInfo = GetStorageTypeInfoCore(devicePath, false); + var storageInfo = GetStorageDeviceInfoCore(devicePath, false); if (null == storageInfo) return null; @@ -105,7 +105,7 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(StorageDeviceInfo storageInfo, string devicePath, DeviceInfo deviceInfo, bool getDeviceData, bool getAllData) + internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(StorageDeviceInfo storageInfo, string devicePath, DeviceInfo deviceInfo, bool? getAllData) { var isDeviceInfo = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); @@ -114,7 +114,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(StorageDeviceInfo sto if (null == storageInfo) - storageInfo = GetStorageTypeInfoCore(devicePath, false); + storageInfo = GetStorageDeviceInfoCore(devicePath, false); if (null == storageInfo) return null; @@ -122,21 +122,35 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(StorageDeviceInfo sto var pDriveInfo = new PhysicalDriveInfo(storageInfo) { + DeviceDescription = isDeviceInfo ? deviceInfo.DeviceDescription : null, + DevicePath = devicePath, // "FriendlyName" usually contains a more complete name, as seen in Windows Explorer. Name = isDeviceInfo ? deviceInfo.FriendlyName : null, }; - - if (getDeviceData) + + if (null != getAllData) { //var physicalDrivePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, storageInfo.DeviceNumber.ToString(CultureInfo.InvariantCulture)); try { // Requires elevation. - PopulatePhysicalDriveInfo(getAllData, devicePath, pDriveInfo); + PopulatePhysicalDriveInfo((bool) getAllData, devicePath, pDriveInfo); + + + //// CDRom, SD Card. + //if (pDriveInfo.StorageDeviceInfo.DeviceType == StorageDeviceType.CDRom) + //{ + // if (isDeviceInfo) + // { + // deviceInfo.ClassGuid = new Guid(Utils.GetEnumDescription(DeviceGuid.CDRom)); + + // pDriveInfo.Name = deviceInfo.FriendlyName; + // } + //} } catch { } } @@ -151,9 +165,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(StorageDeviceInfo sto // var pDrive = @"\\.\PhysicalDrive0"; - // GetDiskPartitions(pDrive); - // GetDiskGeometry(pDrive); - // GetDiskLayout(pDrive); + // GetDriveStuff(devicePath); // } // catch { } ////} @@ -203,10 +215,9 @@ private static void PopulatePhysicalDriveInfo(bool getAllData, string devicePath // Get the device size. - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(long)))) + using (var safeBuffer = SafeGlobalMemoryBufferHandle.FromLong(physicalDriveInfo.TotalSize)) { - uint bytesReturned; - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageTypeInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs similarity index 77% rename from AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageTypeInfo.cs rename to AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs index 30e0148ac..bff27c651 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageTypeInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs @@ -36,9 +36,9 @@ public static partial class Device /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// A string (when is set to ). /// - public static StorageDeviceInfo GetStorageTypeInfo(string devicePath) + public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { - return GetStorageTypeInfoCore(devicePath, false); + return GetStorageDeviceInfoCore(devicePath, false); } @@ -54,9 +54,9 @@ public static StorageDeviceInfo GetStorageTypeInfo(string devicePath) /// A string (when is set to ). /// /// When true also get the which requires elevated rights. - public static StorageDeviceInfo GetStorageTypeInfo(string devicePath, bool getBusType) + public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath, bool getBusType) { - return GetStorageTypeInfoCore(devicePath, getBusType); + return GetStorageDeviceInfoCore(devicePath, getBusType); } @@ -72,7 +72,7 @@ public static StorageDeviceInfo GetStorageTypeInfo(string devicePath, bool getBu /// A string (when is set to ). /// /// When true also get the which requires elevated rights. - internal static StorageDeviceInfo GetStorageTypeInfoCore(string devicePath, bool getBusType) + internal static StorageDeviceInfo GetStorageDeviceInfoCore(string devicePath, bool getBusType) { string logicalDrive; @@ -81,32 +81,35 @@ internal static StorageDeviceInfo GetStorageTypeInfoCore(string devicePath, bool if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; - - // No elevation needed. - using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) + // No elevation needed. - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath)) - { - var storage = null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?) null; + //try { + using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) - if (null != storage) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath)) { - var storageInfo = new StorageDeviceInfo((NativeMethods.STORAGE_DEVICE_NUMBER) storage); + var storage = null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?) null; - if (getBusType) + if (null != storage) { - // Requires elevation. + var storageInfo = new StorageDeviceInfo((NativeMethods.STORAGE_DEVICE_NUMBER) storage); - var pDriveInfo = GetPhysicalDriveInfoCore(storageInfo, pathToDevice, null, true, false); + if (getBusType) + { + // Requires elevation. - if (null != pDriveInfo) - storageInfo.BusType = pDriveInfo.StorageDeviceInfo.BusType; - } + var pDriveInfo = GetPhysicalDriveInfoCore(storageInfo, pathToDevice, null, false); - return storageInfo; + if (null != pDriveInfo) + storageInfo.BusType = pDriveInfo.StorageDeviceInfo.BusType; + } + + return storageInfo; + } } - } + //} + //catch {} return null; } diff --git a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs index 25c52b115..869be77dd 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs @@ -63,6 +63,10 @@ public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) #region Properties + /// The device description. + public string DeviceDescription { get; internal set; } + + /// The path to the device. /// A string that represents the path to the device. /// A drive path such as: "C:", "D:\", @@ -89,8 +93,8 @@ public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) public string Name { get; internal set; } - /// The partition numbers that are located on the physical drive. - public Collection PartitionNumbers { get; internal set; } + /// The partition index numbers that are located on the physical drive. + public Collection PartitionIndexes { get; internal set; } ///// The partitions that are located on the physical drive. @@ -119,9 +123,13 @@ public string TotalSizeUnitSize } - /// The volumes that are located on the physical drive. + /// A collection of volume GUID strings of volumes that are located on the physical drive. public Collection VolumeGuids { get; internal set; } + + /// A collection of volume label strings of volumes that are located on the physical drive. + public Collection VolumeLabels { get; internal set; } + #endregion // Properties diff --git a/AlphaFS/Device/Volume/VolumeInfo.cs b/AlphaFS/Device/Volume/VolumeInfo.cs index f507af3a9..a0ff5d89b 100644 --- a/AlphaFS/Device/Volume/VolumeInfo.cs +++ b/AlphaFS/Device/Volume/VolumeInfo.cs @@ -206,7 +206,7 @@ public string Guid /// Gets the label of the volume. /// The label of the volume. - /// This property is the label assigned to the volume, such "MyDrive" + /// This property is the label assigned to the volume, such as: "MyDrive" public string Name { get; private set; } diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs index d0241e989..bbb1b74d5 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs @@ -32,81 +32,69 @@ internal static partial class NativeMethods #region CM_Xxx /// The CM_Connect_Machine function creates a connection to a remote machine. - /// - /// 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. - /// Available in Microsoft Windows 2000 and later versions of Windows. - /// - /// Name of the unc server. - /// [out] The ph machine. /// /// If the operation succeeds, the function returns CR_SUCCESS. /// Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h. /// + /// + /// Available in Microsoft Windows 2000 and later versions of Windows. + ///   + /// 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. + /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CM_Connect_MachineW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] public static extern int CM_Connect_Machine([MarshalAs(UnmanagedType.LPWStr)] string uncServerName, out SafeCmConnectMachineHandle phMachine); - /// - /// The CM_Get_Device_ID_Ex function retrieves the device instance ID for a specified device instance on a local or a remote machine. - /// - /// - /// 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. - ///   - /// Available in Microsoft Windows 2000 and later versions of Windows. - /// - /// The dn development instance. - /// The buffer. - /// Length of the buffer. - /// The ul flags. - /// The machine. + + /// The CM_Get_Device_ID_Ex function retrieves the device instance ID for a specified device instance on a local or a remote machine. /// /// If the operation succeeds, the function returns CR_SUCCESS. /// Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h. /// + /// + /// Available in Microsoft Windows 2000 and later versions of Windows. + ///   + /// 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. + /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CM_Get_Device_ID_ExW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] public static extern int CM_Get_Device_ID_Ex([MarshalAs(UnmanagedType.U4)] uint dnDevInst, SafeGlobalMemoryBufferHandle buffer, [MarshalAs(UnmanagedType.U4)] uint bufferLen, [MarshalAs(UnmanagedType.U4)] uint ulFlags, SafeCmConnectMachineHandle hMachine); - /// - /// The CM_Disconnect_Machine function removes a connection to a remote machine. - /// + + /// The CM_Disconnect_Machine function removes a connection to a remote machine. + /// + /// If the operation succeeds, the function returns CR_SUCCESS. + /// Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h. + /// /// + /// Available in Microsoft Windows 2000 and later versions of Windows. + ///   /// 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. + ///   /// SetLastError is set to . - /// Available in Microsoft Windows 2000 and later versions of Windows. /// - /// The machine. - /// - /// If the operation succeeds, the function returns CR_SUCCESS. - /// Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h. - /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] internal static extern int CM_Disconnect_Machine(IntPtr hMachine); - /// - /// The CM_Get_Parent_Ex function obtains a device instance handle to the parent node of a specified device node (devnode) in a local - /// or a remote machine's device tree. - /// - /// - /// 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. - /// Available in Microsoft Windows 2000 and later versions of Windows. - /// - /// [out] The pdn development instance. - /// The dn development instance. - /// The ul flags. - /// The machine. + + /// The CM_Get_Parent_Ex function obtains a device instance handle to the parent node of a specified device node (devnode) in a local or a remote machine's device tree. /// /// If the operation succeeds, the function returns CR_SUCCESS. /// Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h. /// + /// + /// Available in Microsoft Windows 2000 and later versions of Windows. + ///   + /// 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. + /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] @@ -117,56 +105,71 @@ internal static partial class NativeMethods #region DeviceIoControl - /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. - /// - /// If the operation completes successfully, the return value is nonzero. - /// If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError. - /// + /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. /// - /// To retrieve a handle to the device, you must call the function with either the name of a device or - /// the name of the driver associated with a device. + /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. /// To specify a device name, use the following format: \\.\DeviceName /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 /// - /// The device. - /// The i/o control code. - /// Buffer for in data. - /// Size of the in buffer. - /// Buffer for out data. - /// Size of the out buffer. - /// [out] The bytes returned. - /// The overlapped. + /// + /// + /// If the operation completes successfully, the return value is nonzero. + /// If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError. + /// [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 DeviceIoControl(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, IntPtr lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); + internal static extern bool DeviceIoControl(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, IntPtr lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, IntPtr lpBytesReturned, IntPtr lpOverlapped); + /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. + /// + /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. + /// To specify a device name, use the following format: \\.\DeviceName + /// Minimum supported client: Windows XP + /// Minimum supported server: Windows Server 2003 + /// + /// + /// + /// If the operation completes successfully, the return value is nonzero. + /// If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError. + /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControlAnyObjectGetSet(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, [MarshalAs(UnmanagedType.AsAny)] object lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); + internal static extern bool DeviceIoControlAnyObjectGetSet(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, [MarshalAs(UnmanagedType.AsAny)] object lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, IntPtr lpBytesReturned, IntPtr lpOverlapped); + /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. + /// + /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. + /// To specify a device name, use the following format: \\.\DeviceName + /// Minimum supported client: Windows XP + /// Minimum supported server: Windows Server 2003 + /// + /// + /// + /// If the operation completes successfully, the return value is nonzero. + /// If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError. + /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoJunctions(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, SafeGlobalMemoryBufferHandle lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, IntPtr lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped); + internal static extern bool DeviceIoJunctions(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] IoControlCode dwIoControlCode, SafeGlobalMemoryBufferHandle lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, IntPtr lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, IntPtr lpBytesReturned, IntPtr lpOverlapped); #endregion // DeviceIoControl #region SetupDiXxx - /// - /// The SetupDiDestroyDeviceInfoList function deletes a device information set and frees all associated memory. - /// + /// The SetupDiDestroyDeviceInfoList function deletes a device information set and frees all associated memory. /// - /// SetLastError is set to . /// Available in Microsoft Windows 2000 and later versions of Windows. + ///   + /// SetLastError is set to . /// - /// Information describing the development. + /// /// /// The function returns TRUE if it is successful. /// Otherwise, it returns FALSE and the logged error can be retrieved with a call to GetLastError. @@ -176,22 +179,12 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetupDiDestroyDeviceInfoList(IntPtr hDevInfo); - /// - /// The SetupDiEnumDeviceInterfaces function enumerates the device interfaces that are contained in a device information set. - /// + + /// The SetupDiEnumDeviceInterfaces function enumerates the device interfaces that are contained in a device information set. /// - /// Repeated calls to this function return an structure for a different device - /// interface. - /// This function can be called repeatedly to get information about interfaces in a device information set that are - /// associated - /// with a particular device information element or that are associated with all device information elements. /// Available in Microsoft Windows 2000 and later versions of Windows. /// - /// Information describing the development. - /// Information describing the development. - /// [in,out] Unique identifier for the interface class. - /// Zero-based index of the member. - /// [in,out] Information describing the device interface. + /// /// /// SetupDiEnumDeviceInterfaces returns TRUE if the function completed without error. /// If the function completed with an error, FALSE is returned and the error code for the failure can be retrieved by calling @@ -202,47 +195,29 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetupDiEnumDeviceInterfaces(SafeHandle hDevInfo, IntPtr devInfo, ref Guid interfaceClassGuid, [MarshalAs(UnmanagedType.U4)] uint memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData); - /// - /// The SetupDiGetClassDevsEx function returns a handle to a device information set that contains requested device information elements - /// for a local or a remote computer. - /// + + /// The SetupDiGetClassDevsEx function returns a handle to a device information set that contains requested device information elements for a local or a remote computer. /// - /// The caller of SetupDiGetClassDevsEx must delete the returned device information set when it is no longer needed by calling - /// . /// Available in Microsoft Windows 2000 and later versions of Windows. /// - /// [in,out] Unique identifier for the class. - /// The enumerator. - /// The parent. - /// The devs ex flags. - /// Set the device information belongs to. - /// Name of the machine. - /// The reserved. + /// /// /// If the operation succeeds, SetupDiGetClassDevsEx returns a handle to a device information set that contains all installed /// devices that matched the supplied parameters. - /// If the operation fails, the function returns INVALID_HANDLE_VALUE. To get extended error information, call - /// GetLastError. + /// If the operation fails, the function returns INVALID_HANDLE_VALUE. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern SafeSetupDiClassDevsExHandle SetupDiGetClassDevsEx(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, [MarshalAs(UnmanagedType.U4)] SetupDiGetClassDevsExFlags devsExFlags, IntPtr deviceInfoSet, [MarshalAs(UnmanagedType.LPWStr)] string machineName, IntPtr reserved); - /// - /// The SetupDiGetDeviceInterfaceDetail function returns details about a device interface. - /// + + /// The SetupDiGetDeviceInterfaceDetail function returns details about a device interface. /// - /// The interface detail returned by this function consists of a device path that can be passed to Win32 functions such as - /// CreateFile. - /// Do not attempt to parse the device path symbolic name. The device path can be reused across system starts. /// Available in Microsoft Windows 2000 and later versions of Windows. + ///   + /// The interface detail returned by this function consists of a device path that can be passed to Win32 functions such as CreateFile. Do not attempt to parse the device path symbolic name. The device path can be reused across system starts. /// - /// Information describing the development. - /// [in,out] Information describing the device interface. - /// [in,out] Information describing the device interface detail. - /// Size of the device interface detail data. - /// Size of the required. - /// [in,out] Information describing the device information. + /// /// /// SetupDiGetDeviceInterfaceDetail returns TRUE if the function completed without error. /// If the function completed with an error, FALSE is returned and the error code for the failure can be retrieved by calling @@ -253,27 +228,21 @@ internal static partial class NativeMethods [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetupDiGetDeviceInterfaceDetail(SafeHandle hDevInfo, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData, [MarshalAs(UnmanagedType.U4)] uint deviceInterfaceDetailDataSize, IntPtr requiredSize, ref SP_DEVINFO_DATA deviceInfoData); - /// - /// The SetupDiGetDeviceRegistryProperty function retrieves a specified Plug and Play device property. + + /// The SetupDiGetDeviceRegistryProperty function retrieves a specified Plug and Play device property. + /// + /// Available in Microsoft Windows 2000 and later versions of Windows. + /// /// - /// Available in Microsoft Windows 2000 and later versions of Windows. - /// Set the device information belongs to. - /// [in,out] Information describing the device information. - /// The property. - /// [out] Type of the property register data. - /// Buffer for property data. - /// Size of the property buffer. - /// Size of the required. /// /// SetupDiGetDeviceRegistryProperty returns TRUE if the call was successful. /// Otherwise, it returns FALSE and the logged error can be retrieved by making a call to GetLastError. - /// SetupDiGetDeviceRegistryProperty returns the ERROR_INVALID_DATA error code if the requested property does not exist for a - /// device or if the property data is not valid. + /// SetupDiGetDeviceRegistryProperty returns the ERROR_INVALID_DATA error code if the requested property does not exist for a device or if the property data is not valid. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SetupDiGetDeviceRegistryProperty(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, SetupDiGetDeviceRegistryPropertyEnum property, [MarshalAs(UnmanagedType.U4)] out uint propertyRegDataType, SafeGlobalMemoryBufferHandle propertyBuffer, [MarshalAs(UnmanagedType.U4)] uint propertyBufferSize, IntPtr requiredSize); + internal static extern bool SetupDiGetDeviceRegistryProperty(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, SetupDiGetDeviceRegistryPropertyEnum property, IntPtr propertyRegDataType, SafeGlobalMemoryBufferHandle propertyBuffer, [MarshalAs(UnmanagedType.U4)] uint propertyBufferSize, IntPtr requiredSize); #endregion // SetupDiXxx } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs index 0fbcfe817..9fbecab63 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs @@ -19,11 +19,190 @@ * THE SOFTWARE. */ +using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { + ///// System-Defined Device Interface Classes + ///// http://msdn.microsoft.com/en-us/library/windows/hardware/ff541389%28v=vs.85%29.aspx + //public static class DeviceGuids + //{ + // #region 1394 and 61883 Devices + + // /// The BUS1394_CLASS_GUID device interface class is defined for 1394 bus devices. + // public static Guid Bus1394 = new Guid("6BDD1FC1-810F-11d0-BEC7-08002BE2092F"); + + // /// The GUID_61883_CLASS device interface class is defined for devices in the 61883 device setup class. + // public static Guid Guid61883 = new Guid("7EBEFBC0-3200-11d2-B4C2-00A0C9697D07"); + + // #endregion // 1394 and 61883 Devices + + + // #region Battery and ACPI devices + + // /// The GUID_DEVICE_APPLICATIONLAUNCH_BUTTON device interface class is defined for Advanced Configuration and Power Interface (ACPI) application start buttons. + // public static Guid ApplicationLaunchButton = new Guid("629758EE-986E-4D9E-8E47-DE27F8AB054D"); + + // /// The GUID_DEVICE_BATTERY device interface class is defined for battery devices. + // public static Guid Battery = new Guid("72631E54-78A4-11D0-BCF7-00AA00B7B32A"); + + // /// The GUID_DEVICE_LID device interface class is defined for Advanced Configuration and Power Interface (ACPI) lid devices. + // public static Guid Lid = new Guid("4AFA3D52-74A7-11d0-be5e-00A0C9062857"); + + // /// The GUID_DEVICE_MEMORY device interface class is defined for Advanced Configuration and Power Interface (ACPI) memory devices. + // public static Guid Memory = new Guid("3FD0F03D-92E0-45FB-B75C-5ED8FFB01021"); + + // /// The GUID_DEVICE_MESSAGE_INDICATOR device interface class is defined for Advanced Configuration and Power Interface (ACPI) message indicator devices. + // public static Guid MessageIndicator = new Guid("CD48A365-FA94-4CE2-A232-A1B764E5D8B4"); + + // /// The GUID_DEVICE_PROCESSOR device interface class is defined for Advanced Configuration and Power Interface (ACPI) processor devices. + // public static Guid Processor = new Guid("97FADB10-4E33-40AE-359C-8BEF029DBDD0"); + + // /// The GUID_DEVICE_SYS_BUTTON device interface classis defined for Advanced Configuration and Power Interface (ACPI) system power button devices. + // public static Guid SysButton = new Guid("4AFA3D53-74A7-11d0-be5e-00A0C9062857"); + + // /// The GUID_DEVICE_THERMAL_ZONE device interface class is defined for Advanced Configuration and Power Interface (ACPI) thermal zone devices. + // public static Guid ThermalZone = new Guid("4AFA3D51-74A7-11d0-be5e-00A0C9062857"); + + // #endregion // Battery and ACPI devices + + + // #region Bluetooth Devices + + // /// The GUID_BTHPORT_DEVICE_INTERFACE device interface class is defined for Bluetooth radios. + // public static Guid Bluetooth = new Guid("0850302A-B344-4fda-9BE9-90576B8D46F0"); + + // #endregion // Bluetooth Devices + + + // #region Display and Image Devices + + // /// 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. + // public static Guid Brightness = new Guid("FDE5BBA4-B3F9-46FB-BDAA-0728CE3100B4"); + + // /// The GUID_DEVINTERFACE_DISPLAY_ADAPTER device interface class is defined for display views that are supported by display adapters. + // public static Guid DisplayAdapter = new Guid("5B45201D-F2F2-4F3B-85BB-30FF1F953599"); + + // /// 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. + // public static Guid I2C = new Guid("2564AA4F-DDDB-4495-B497-6AD4A84163D7"); + + // /// The GUID_DEVINTERFACE_IMAGE device interface class is defined for WIA devices and Still Image (STI) devices, including digital cameras and scanners. + // public static Guid StillImage = new Guid("6BDD1FC6-810F-11D0-BEC7-08002BE2092F"); + + // /// The GUID_DEVINTERFACE_MONITOR device interface class is defined for monitor devices. + // public static Guid Monitor = new Guid("E6F07B5F-EE97-4a90-B076-33F57BF4EAA7"); + + // /// 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. + // public static Guid OutputProtectionManagement = new Guid("BF4672DE-6B4E-4BE4-A325-68A91EA49C09"); + + // /// The GUID_DEVINTERFACE_VIDEO_OUTPUT_ARRIVAL device interface class is defined for child devices of display devices. + // public static Guid VideoOutputArrival = new Guid("1AD9E4F0-F88D-4360-BAB9-4C2D55E564CD"); + + // /// The GUID_DISPLAY_DEVICE_ARRIVAL device interface class is defined for display adapters. + // public static Guid DisplayDeviceArrival = new Guid("1CA05180-A699-450A-9A0C-DE4FBE3DDD89"); + + // #endregion // Display and Image Devices + + + // #region Interactive Input Devices + + // /// The GUID_DEVINTERFACE_HID device interface class is defined for HID collections. + // public static Guid Hid = new Guid("4D1E55B2-F16F-11CF-88CB-001111000030"); + + // /// The GUID_DEVINTERFACE_KEYBOARD device interface class is defined for keyboard devices. + // public static Guid Keyboard = new Guid("4D1E55B2-F16F-11CF-88CB-001111000030"); + + // /// The GUID_DEVINTERFACE_MOUSE device interface class is defined for mouse devices. + // public static Guid Mouse = new Guid("378DE44C-56EF-11D1-BC8C-00A0C91405DD"); + + // #endregion // Interactive Input Devices + + + // #region Modem Devices + + // /// The GUID_DEVINTERFACE_MODEM device interface class is defined for modem devices. + // public static Guid Modem = new Guid("2C7089AA-2E0E-11D1-B114-00C04FC2AAE4"); + + // #endregion // Modem Devices + + + // #region Network Devices + + // /// The GUID_DEVINTERFACE_NET device interface class is defined for network devices. + // public static Guid Network = new Guid("CAC88484-7515-4C03-82E6-71A87ABAC361"); + + // #endregion // Network Devices + + + // #region Serial and Parallel Port Devices + + // /// The GUID_DEVINTERFACE_COMPORT device interface class is defined for COM ports. + // public static Guid ComPort = new Guid("86E0D1E0-8089-11D0-9CE4-08003E301F73"); + + // /// The GUID_DEVINTERFACE_PARALLEL device interface class is defined for parallel ports that support an IEEE 1284-compatible hardware interface. + // public static Guid Parallel = new Guid("97F76EF0-F883-11D0-AF1F-0000F800845C"); + + // /// The GUID_DEVINTERFACE_PARCLASS device interface class is defined for devices that are attached to a parallel port. + // public static Guid ParallelClass = new Guid("97F76EF0-F883-11D0-AF1F-0000F800845C"); + + // /// The GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR device interface class is defined for Plug and Play (PnP) serial ports. + // public static Guid SerialEnumBusEnumerator = new Guid("4D36E978-E325-11CE-BFC1-08002BE10318"); + + // #endregion // Serial and Parallel Port Devices + + + // #region Storage Devices + + // /// The GUID_DEVINTERFACE_CDCHANGER device interface class is defined for CD-ROM changer devices. + // public static Guid CDChanger = new Guid("53F56312-B6BF-11D0-94F2-00A0C91EFB8B"); + + // /// The GUID_DEVINTERFACE_CDROM device interface class is defined for CD-ROM storage devices. + // public static Guid CDRom = new Guid("53F56308-B6BF-11D0-94F2-00A0C91EFB8B"); + + // /// The GUID_DEVINTERFACE_DISK device interface class is defined for hard disk storage devices. + // public static Guid Disk = new Guid("53F56307-B6BF-11D0-94F2-00A0C91EFB8B"); + + // /// The GUID_DEVINTERFACE_FLOPPY device interface class is defined for floppy disk storage devices. + // public static Guid Floppy = new Guid("53F56311-B6BF-11D0-94F2-00A0C91EFB8B"); + + // /// The GUID_DEVINTERFACE_MEDIUMCHANGER device interface class is defined for medium changer devices. + // public static Guid MediumChanger = new Guid("53F56310-B6BF-11D0-94F2-00A0C91EFB8B"); + + // /// The GUID_DEVINTERFACE_PARTITION device interface class is defined for partition devices. + // public static Guid Partition = new Guid("53F5630A-B6BF-11D0-94F2-00A0C91EFB8B"); + + // /// The GUID_DEVINTERFACE_STORAGEPORT device interface class is defined for storage port devices. + // public static Guid StoragePort = new Guid("2ACCFE60-C130-11D2-B082-00A0C91EFB8B"); + + // /// The GUID_DEVINTERFACE_TAPE device interface class is defined for tape storage devices. + // public static Guid Tape = new Guid("53F5630B-B6BF-11D0-94F2-00A0C91EFB8B"); + + // /// The GUID_DEVINTERFACE_VOLUME device interface class is defined for volume devices. + // public static Guid Volume = new Guid("53F5630D-B6BF-11D0-94F2-00A0C91EFB8B"); + + // /// The GUID_DEVINTERFACE_WRITEONCEDISK device interface class is defined for write-once disk devices. + // public static Guid WriteOnceDisk = new Guid("53F5630C-B6BF-11D0-94F2-00A0C91EFB8B"); + + // #endregion // Storage Devices + + + // #region USB Devices + + // /// The GUID_DEVINTERFACE_USB_DEVICE device interface class is defined for USB devices that are attached to a USB hub. + // public static Guid UsbDevice = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED"); + + // /// The GUID_DEVINTERFACE_USB_HOST_CONTROLLER device interface class is defined for USB host controller devices. + // public static Guid UsbHostController = new Guid("3ABF6F2D-71C4-462A-8A92-1E6861E6AF27"); + + // /// The GUID_DEVINTERFACE_USB_HUB device interface class is defined for USB hub devices. + // public static Guid UsbHub = new Guid("F18A0E88-C30C-11D0-8815-00A0C906BED8"); + + // #endregion // USB Devices + //} + + /// System-Defined Device Interface Classes /// http://msdn.microsoft.com/en-us/library/windows/hardware/ff541389%28v=vs.85%29.aspx public enum DeviceGuid @@ -223,20 +402,23 @@ public enum DeviceGuid [Description("53F5630C-B6BF-11D0-94F2-00A0C91EFB8B")] WriteOnceDisk, + #endregion // Storage Devices - #region USB Devices /// The GUID_DEVINTERFACE_USB_DEVICE device interface class is defined for USB devices that are attached to a USB hub. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] [Description("A5DCBF10-6530-11D2-901F-00C04FB951ED")] UsbDevice, /// The GUID_DEVINTERFACE_USB_HOST_CONTROLLER device interface class is defined for USB host controller devices. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] [Description("3ABF6F2D-71C4-462A-8A92-1E6861E6AF27")] UsbHostController, /// The GUID_DEVINTERFACE_USB_HUB device interface class is defined for USB hub devices. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] [Description("F18A0E88-C30C-11D0-8815-00A0C906BED8")] UsbHub diff --git a/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs b/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs index ef2a52cc0..2d5a19f6f 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs @@ -58,10 +58,10 @@ internal enum SetupDiGetDeviceRegistryPropertyEnum /// Class = 7, - /// SPDRP_CLASSGUID - /// Represents the of the device setup class that a device instance belongs to. - /// - ClassGuid = 8, + ///// SPDRP_CLASSGUID + ///// Represents the of the device setup class that a device instance belongs to. + ///// + //ClassGuid = 8, /// SPDRP_DRIVER /// Represents the registry entry name of the driver key for a device instance. @@ -93,9 +93,7 @@ internal enum SetupDiGetDeviceRegistryPropertyEnum /// PhysicalDeviceObjectName = 14, - ///// SPDRP_CAPABILITIES - //// Represents the capabilities of a device instance. - //// + ///// SPDRP_CAPABILITIES - Represents the capabilities of a device instance. //Capabilities = 15, ///// SPDRP_UI_NUMBER - Represents a number for the device instance that can be displayed in a user interface item. @@ -163,7 +161,7 @@ internal enum SetupDiGetDeviceRegistryPropertyEnum LocationPaths = 35, /// SPDRP_BASE_CONTAINERID - /// Represents the value of the base container identifier (ID) .The Windows Plug and Play (PnP) manager assigns this value to the device node (devnode). + /// Represents the value of the base container identifier (ID) .The Windows Plug and Play (PnP) manager assigns this value to the device node (devnode). /// BaseContainerId = 36 } diff --git a/AlphaFS/Safe Handles/SafeGlobalMemoryBufferHandle.cs b/AlphaFS/Safe Handles/SafeGlobalMemoryBufferHandle.cs index 293a9b80c..23216656f 100644 --- a/AlphaFS/Safe Handles/SafeGlobalMemoryBufferHandle.cs +++ b/AlphaFS/Safe Handles/SafeGlobalMemoryBufferHandle.cs @@ -20,6 +20,7 @@ */ using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; @@ -29,37 +30,40 @@ namespace Alphaleonis.Win32 internal sealed class SafeGlobalMemoryBufferHandle : SafeNativeMemoryBufferHandle { /// Creates new instance with zero IntPtr. - public SafeGlobalMemoryBufferHandle() - : base(true) + public SafeGlobalMemoryBufferHandle() : base(true) { } + /// Initializes a new instance of the class allocating the specified number of bytes of unmanaged memory. /// The capacity. - public SafeGlobalMemoryBufferHandle(int capacity) : - base(capacity) + public SafeGlobalMemoryBufferHandle(int capacity) : base(capacity) { SetHandle(Marshal.AllocHGlobal(capacity)); } - private SafeGlobalMemoryBufferHandle(IntPtr buffer, int capacity) - : base(buffer, capacity) + + private SafeGlobalMemoryBufferHandle(IntPtr buffer, int capacity) : base(buffer, capacity) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] + + [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))); + 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) @@ -68,6 +72,7 @@ public static SafeGlobalMemoryBufferHandle FromStringUni(string str) return new SafeGlobalMemoryBufferHandle(Marshal.StringToHGlobalUni(str), str.Length * UnicodeEncoding.CharSize + UnicodeEncoding.CharSize); } + /// Called when object is disposed or finalized. protected override bool ReleaseHandle() { diff --git a/AlphaFS/Win32Errors.cs b/AlphaFS/Win32Errors.cs index b38fc6107..4bc15d53a 100644 --- a/AlphaFS/Win32Errors.cs +++ b/AlphaFS/Win32Errors.cs @@ -64,7 +64,10 @@ public static int GetHrFromWin32Error(uint errorCode) //public const uint ERROR_BAD_ENVIRONMENT = 10; //public const uint ERROR_BAD_FORMAT = 11; //public const uint ERROR_INVALID_ACCESS = 12; + + /// (13) The data is invalid. public const uint ERROR_INVALID_DATA = 13; + //public const uint ERROR_OUTOFMEMORY = 14; /// (15) The system cannot find the drive specified. From 472869f22092af6a803d21f35ba7d7eba789a0b7 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 16 Feb 2018 10:40:57 +0100 Subject: [PATCH 046/133] Code improvement, work in progress. --- AlphaFS/Device/Device.GetDeviceIoData.cs | 6 +- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 118 ++++++++++-------- AlphaFS/Device/Device.ValidateDevicePath.cs | 4 - .../Device.GetPhysicalDriveInfo.cs | 44 +------ .../Device.GetStorageDeviceInfo.cs | 46 +++++-- AlphaFS/Device/StorageDeviceInfo.cs | 2 +- .../Filesystem/Native Other/DISK_EXTENT.cs | 13 +- .../DRIVE_LAYOUT_INFORMATION_EX.cs | 10 +- .../DRIVE_LAYOUT_INFORMATION_GPT.cs | 1 + .../DRIVE_LAYOUT_INFORMATION_MBR.cs | 1 + .../Native Other/PARTITION_INFORMATION_EX.cs | 10 +- .../Native Other/PARTITION_INFORMATION_MBR.cs | 1 + .../Native Other/VOLUME_DISK_EXTENTS.cs | 2 +- .../Filesystem/Path Class/Path.GetFullPath.cs | 2 +- 14 files changed, 132 insertions(+), 128 deletions(-) diff --git a/AlphaFS/Device/Device.GetDeviceIoData.cs b/AlphaFS/Device/Device.GetDeviceIoData.cs index f30494e5e..1d7b05541 100644 --- a/AlphaFS/Device/Device.GetDeviceIoData.cs +++ b/AlphaFS/Device/Device.GetDeviceIoData.cs @@ -51,10 +51,8 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa return safeBuffer; - // ERROR_INVALID_FUNCTION: Dynamic disk. - // ERROR_NOT_SUPPORTED : CD/DVD without medium. - - if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_NOT_SUPPORTED) + // Dynamic disk. + if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) return null; diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index fc2c2959b..bf0c6d3cb 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -20,17 +20,77 @@ */ using System; -using System.Collections.Generic; -using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - // https://github.com/t00/TestCrypt/blob/master/TestCrypt/PhysicalDrive.cs + private static NativeMethods.VOLUME_DISK_EXTENTS? GetVolumeDiskExtents(SafeFileHandle safeHandle) + { + NativeMethods.VOLUME_DISK_EXTENTS? structure; + var structSize = Marshal.SizeOf(typeof(NativeMethods.VOLUME_DISK_EXTENTS)); + var bufferSize = structSize; + bool success; + int lastError; + + + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) + { + success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + + lastError = Marshal.GetLastWin32Error(); + + structure = safeBuffer.PtrToStructure(0); + } + + + if (!success) + { + if (lastError != Win32Errors.ERROR_MORE_DATA) + return null; + + + // 2018-02-15 Yomodo: Not fully tested. + + + var numberOfExtents = ((NativeMethods.VOLUME_DISK_EXTENTS) structure).NumberOfDiskExtents; + + bufferSize = (int) (structSize * numberOfExtents); + + + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) + { + success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + + lastError = Marshal.GetLastWin32Error(); + + + if (success) + { + numberOfExtents = (uint) safeBuffer.PtrToStructure(0).NumberOfExtents; + + var diskExtent = new NativeMethods.DISK_EXTENT[numberOfExtents]; + + + for (int i = 0, itemOffset = 0; i < numberOfExtents - 1; i++, itemOffset = structSize * i) + { + diskExtent[i] = safeBuffer.PtrToStructure(itemOffset); + } + + + return new NativeMethods.VOLUME_DISK_EXTENTS {Extents = diskExtent}; + } + } + } + + + return structure; + } + [SecurityCritical] internal static object GetDriveStuff(string logicalDrive) @@ -74,19 +134,6 @@ internal static object GetDriveStuff(string logicalDrive) } - // VOLUME_DISK_EXTENTS - - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, logicalDrive)) - { - if (null != safeBuffer) - { - var structure = safeBuffer.PtrToStructure(0); - - //return structure; - } - } - - // PARTITION_INFORMATION_EX using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_PARTITION_INFO_EX, logicalDrive)) @@ -102,44 +149,5 @@ internal static object GetDriveStuff(string logicalDrive) return null; } - - //[SecurityCritical] - //internal static void GetVolumeDiskExtents(string logicalDrive) - //{ - // // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes - // // without accessing that file or device, even if GENERIC_READ access would have been denied. - // // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. - // //const int desiredAccess = 0; - - // // Requires elevation. - // const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; - - // //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - - - // using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) - // - // using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, logicalDrive)) - // { - // if (null != safeBuffer) - // { - // var structure = safeBuffer.PtrToStructure(0); - - // var numberOfDiskExtents = structure.NumberOfDiskExtents; - - // var objectSize = Marshal.SizeOf(typeof(NativeMethods.VOLUME_DISK_EXTENTS)); - - - // for (int i = 0, itemOffset = 0; i < numberOfDiskExtents; i++, itemOffset += objectSize) - // { - // structure = safeBuffer.PtrToStructure(itemOffset); - - // //var pDiskExtent = structure.Extents[i]; - - // //yield return structure; - // } - // } - // } - //} } } diff --git a/AlphaFS/Device/Device.ValidateDevicePath.cs b/AlphaFS/Device/Device.ValidateDevicePath.cs index 4c51c3910..f91f6006e 100644 --- a/AlphaFS/Device/Device.ValidateDevicePath.cs +++ b/AlphaFS/Device/Device.ValidateDevicePath.cs @@ -20,7 +20,6 @@ */ using System; -using System.Globalization; namespace Alphaleonis.Win32.Filesystem { @@ -38,9 +37,6 @@ internal static string ValidateDevicePath(string devicePath, out bool isDrive, o var hasPath = !Utils.IsNullOrWhiteSpace(devicePath); - //if (hasPath) - // devicePath = Path.AddTrailingDirectorySeparator(devicePath, false); - isVolume = hasPath && devicePath.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase); diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index ec67fa41c..67cf7bbc8 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -133,44 +133,15 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(StorageDeviceInfo sto if (null != getAllData) { - //var physicalDrivePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, storageInfo.DeviceNumber.ToString(CultureInfo.InvariantCulture)); - try { // Requires elevation. PopulatePhysicalDriveInfo((bool) getAllData, devicePath, pDriveInfo); - - - //// CDRom, SD Card. - //if (pDriveInfo.StorageDeviceInfo.DeviceType == StorageDeviceType.CDRom) - //{ - // if (isDeviceInfo) - // { - // deviceInfo.ClassGuid = new Guid(Utils.GetEnumDescription(DeviceGuid.CDRom)); - - // pDriveInfo.Name = deviceInfo.FriendlyName; - // } - //} } catch { } } - ////if (null != logicalDrive) - ////{ - // try - // { - // // Requires elevation. - // //GetVolumeDiskExtents(logicalDrive); - - // var pDrive = @"\\.\PhysicalDrive0"; - - // GetDriveStuff(devicePath); - // } - // catch { } - ////} - - return pDriveInfo; } @@ -204,9 +175,11 @@ private static void PopulatePhysicalDriveInfo(bool getAllData, string devicePath physicalDriveInfo.RemovableMedia = storageDescriptor.RemovableMedia; + if (Utils.IsNullOrWhiteSpace(physicalDriveInfo.Name)) physicalDriveInfo.Name = safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductIdOffset).Trim(); + // Get the device hardware serial number. physicalDriveInfo.SerialNumber = safeBuffer.PtrToStringAnsi((int) storageDescriptor.SerialNumberOffset).Trim(); @@ -215,18 +188,9 @@ private static void PopulatePhysicalDriveInfo(bool getAllData, string devicePath // Get the device size. - using (var safeBuffer = SafeGlobalMemoryBufferHandle.FromLong(physicalDriveInfo.TotalSize)) - { - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); - - var lastError = Marshal.GetLastWin32Error(); + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, devicePath)) - if (!success) - NativeError.ThrowException(lastError, string.Format(CultureInfo.InvariantCulture, "Device: {0}", devicePath)); - - - physicalDriveInfo.TotalSize = safeBuffer.ReadInt64(); - } + physicalDriveInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs index bff27c651..ccd4dec2f 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs @@ -20,6 +20,11 @@ */ using System; +using System.ComponentModel; +using System.Globalization; +using System.IO; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { @@ -82,18 +87,39 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(string devicePath, bo return null; + StartGetData: + // No elevation needed. - //try { - using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) + using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) + { + StorageDeviceInfo storageInfo = null; - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath)) + + var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); + + if (null == safeBuffer) { - var storage = null != safeBuffer ? safeBuffer.PtrToStructure(0) : (NativeMethods.STORAGE_DEVICE_NUMBER?) null; + // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + + + var volDiskExtents = GetVolumeDiskExtents(safeHandle); + + if (volDiskExtents.HasValue) + { + // Use the first disk extent. - if (null != storage) + pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); + + goto StartGetData; + } + } + + else + { + using (safeBuffer) { - var storageInfo = new StorageDeviceInfo((NativeMethods.STORAGE_DEVICE_NUMBER) storage); + storageInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure(0)); if (getBusType) { @@ -104,14 +130,12 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(string devicePath, bo if (null != pDriveInfo) storageInfo.BusType = pDriveInfo.StorageDeviceInfo.BusType; } - - return storageInfo; } } - //} - //catch {} - return null; + + return storageInfo; + } } } } diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs index 2054185e0..f876fc6e7 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -106,7 +106,7 @@ public override int GetHashCode() #region Properties - /// The storage bus type. + /// The storage bus type. Requires elevated rights. public StorageBusType BusType { get; internal set; } diff --git a/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs b/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs index b3a977183..cf1282d49 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs @@ -31,13 +31,20 @@ internal struct DISK_EXTENT { /// The number of the disk that contains this extent. This is the same number that is used to construct the name of the disk, /// for example, the X in "\\.\PhysicalDriveX" or "\\?\HarddiskX". - public int DiskNumber; + [MarshalAs(UnmanagedType.U4)] public readonly int DiskNumber; /// The offset from the beginning of the disk to the extent, in bytes. - public long StartingOffset; + [MarshalAs(UnmanagedType.U8)] public readonly long StartingOffset; /// The number of bytes in this extent. - public long ExtentLength; + [MarshalAs(UnmanagedType.U8)] public readonly long ExtentLength; + } + + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct DiskExtentsBeforeArray + { + [MarshalAs(UnmanagedType.U4)] public readonly int NumberOfExtents; } } } diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs index 285d32cc3..703a31efc 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs @@ -37,22 +37,26 @@ internal static partial class NativeMethods internal struct DRIVE_LAYOUT_INFORMATION_EX { /// The style of the partitions on the drive enumerated by the enumeration. - public PARTITION_STYLE PartitionStyle; + public readonly PARTITION_STYLE PartitionStyle; /// The number of partitions on the drive. On hard disks with the MBR layout, this value will always be a multiple of 4. - [MarshalAs(UnmanagedType.U4)] public uint PartitionCount; + [MarshalAs(UnmanagedType.U4)] public readonly uint PartitionCount; public DRIVE_LAYOUT_INFORMATION_UNION DriveLayoutInformation; + /// A variable-sized array of structures, one structure for each partition on the drive. [MarshalAs(UnmanagedType.ByValArray, SizeConst = PartitionEntriesCount)] - public PARTITION_INFORMATION_EX[] PartitionEntry; + public readonly PARTITION_INFORMATION_EX[] PartitionEntry; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct DRIVE_LAYOUT_INFORMATION_UNION { + /// A structure containing information about the master boot record type partitioning on the drive. public DRIVE_LAYOUT_INFORMATION_MBR Mbr; + + /// A structure containing information about the GUID disk partition type partitioning on the drive. public DRIVE_LAYOUT_INFORMATION_GPT Gpt; } } diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs index c2a08e65e..b784e557d 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs @@ -31,6 +31,7 @@ internal static partial class NativeMethods /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct DRIVE_LAYOUT_INFORMATION_GPT { /// The GUID of the disk. diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs index f15ad0491..139ba3ebe 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs @@ -30,6 +30,7 @@ internal static partial class NativeMethods /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct DRIVE_LAYOUT_INFORMATION_MBR { /// The signature of the drive. diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs index a68b4207c..ac59c8690 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs @@ -30,7 +30,7 @@ internal static partial class NativeMethods /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// - [StructLayout(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct PARTITION_INFORMATION_EX { /// The format of the partition. @@ -52,11 +52,11 @@ internal struct PARTITION_INFORMATION_EX } - [StructLayout(LayoutKind.Explicit)] - public struct PARTITION_INFORMATION_UNION + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct PARTITION_INFORMATION_UNION { - [FieldOffset(0)] public PARTITION_INFORMATION_GPT Gpt; - [FieldOffset(0)] public PARTITION_INFORMATION_MBR Mbr; + public PARTITION_INFORMATION_MBR Mbr; + public PARTITION_INFORMATION_GPT Gpt; } } } diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs index 15f119e5d..b2c0dbf86 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs @@ -30,6 +30,7 @@ internal static partial class NativeMethods /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct PARTITION_INFORMATION_MBR { /// The type of partition. diff --git a/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs b/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs index a9e04d3c1..653abba26 100644 --- a/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs +++ b/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs @@ -30,7 +30,7 @@ internal static partial class NativeMethods internal struct VOLUME_DISK_EXTENTS { /// The number of disks in the volume (a volume can span multiple disks). - public uint NumberOfDiskExtents; + [MarshalAs(UnmanagedType.U4)] public readonly uint NumberOfDiskExtents; /// An array of structures. [MarshalAs(UnmanagedType.ByValArray)] public DISK_EXTENT[] Extents; diff --git a/AlphaFS/Filesystem/Path Class/Path.GetFullPath.cs b/AlphaFS/Filesystem/Path Class/Path.GetFullPath.cs index 7ca1a5fd2..5695ef496 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetFullPath.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetFullPath.cs @@ -289,7 +289,7 @@ private static string ApplyFullPathOptions(string path, GetFullPathOptions optio path = AddTrailingDirectorySeparator(path, false); if ((options & GetFullPathOptions.RemoveTrailingDirectorySeparator) != 0) - path = RemoveTrailingDirectorySeparator(path); + path = RemoveTrailingDirectorySeparator(path, false); if ((options & GetFullPathOptions.CheckInvalidPathChars) != 0) CheckInvalidPathChars(path, (options & GetFullPathOptions.CheckAdditional) != 0, false); From 84c2c4ffa6be2fe36eecdd36097e9e2de679b258 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 16 Feb 2018 19:15:03 +0100 Subject: [PATCH 047/133] Added ProcessContext static class that determine the context of the current process. Populates bool properties: IsAdministrator, IsElevatedProcess, IsUacEnabled and IsWindowsService. --- .../AlphaFS_ProcessContextTest.cs | 66 ++++++++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 + AlphaFS/AlphaFS.csproj | 15 +- .../Native Methods/NativeMethods.Utilities.cs | 6 +- AlphaFS/Resources.Designer.cs | 9 + AlphaFS/Resources.resx | 3 + AlphaFS/Safe Handles/SafeTokenHandle.cs | 54 ++++++ AlphaFS/Security/InternalPrivilegeEnabler.cs | 4 +- .../NativeMethods.AdjustTokenPrivileges.cs | 2 +- ...template.cs => NativeMethods.Constants.cs} | 10 +- .../NativeMethods.GetTokenInformation.cs | 41 +++++ .../NativeMethods.LookupPrivilegeValue.cs | 2 +- .../NativeMethods.OpenProcessToken.cs | 42 +++++ AlphaFS/Security/Native Other/Luid.cs | 10 +- .../Security/Native Other/SE_OBJECT_TYPE.cs | 4 + AlphaFS/Security/Native Other/TOKEN.cs | 67 ++++++++ .../Native Other/TOKEN_ELEVATION_TYPE.cs | 43 +++++ .../Native Other/TOKEN_INFORMATION_CLASS.cs | 160 ++++++++++++++++++ ...TokenPrivileges.cs => TOKEN_PRIVILEGES.cs} | 15 +- AlphaFS/Security/Privilege.cs | 14 +- AlphaFS/Security/ProcessContext.cs | 146 ++++++++++++++++ AlphaFS/Security/SecurityAttributes.cs | 13 +- 22 files changed, 695 insertions(+), 32 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS ProcessContext Class/AlphaFS_ProcessContextTest.cs create mode 100644 AlphaFS/Safe Handles/SafeTokenHandle.cs rename AlphaFS/Security/Native Methods/{NativeMethods.template.cs => NativeMethods.Constants.cs} (77%) create mode 100644 AlphaFS/Security/Native Methods/NativeMethods.GetTokenInformation.cs create mode 100644 AlphaFS/Security/Native Methods/NativeMethods.OpenProcessToken.cs create mode 100644 AlphaFS/Security/Native Other/TOKEN.cs create mode 100644 AlphaFS/Security/Native Other/TOKEN_ELEVATION_TYPE.cs create mode 100644 AlphaFS/Security/Native Other/TOKEN_INFORMATION_CLASS.cs rename AlphaFS/Security/Native Other/{TokenPrivileges.cs => TOKEN_PRIVILEGES.cs} (59%) create mode 100644 AlphaFS/Security/ProcessContext.cs diff --git a/AlphaFS.UnitTest/AlphaFS ProcessContext Class/AlphaFS_ProcessContextTest.cs b/AlphaFS.UnitTest/AlphaFS ProcessContext Class/AlphaFS_ProcessContextTest.cs new file mode 100644 index 000000000..5cb348419 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS ProcessContext Class/AlphaFS_ProcessContextTest.cs @@ -0,0 +1,66 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// This is a test class for ProcessContext and is intended to contain all ProcessContext Unit Tests. + [TestClass] + public class AlphaFS_ProcessContextTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_ProcessContext() + { + UnitTestConstants.PrintUnitTestHeader(false); + Console.WriteLine(); + + + 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); + + + Assert.AreEqual(new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator), isAdmin); + + + Assert.IsFalse(IsWindowsService); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 02a574003..3c3d199ee 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -167,6 +167,7 @@ + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 985901d9c..58fd9671b 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -444,6 +444,7 @@ + @@ -535,6 +536,8 @@ + + @@ -548,7 +551,11 @@ - + + + + + @@ -564,6 +571,7 @@ + @@ -579,9 +587,8 @@ - + - @@ -612,7 +619,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs index 16785fc08..a5276ca75 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs @@ -42,7 +42,7 @@ internal static uint GetLowOrderDword(long lowPart) } - internal static long LuidToLong(Luid luid) + internal static long LuidToLong(LUID luid) { var high = (ulong) luid.HighPart << 32; var low = (ulong) luid.LowPart & 0x00000000FFFFFFFF; @@ -51,9 +51,9 @@ internal static long LuidToLong(Luid luid) } - internal static Luid LongToLuid(long lluid) + internal static LUID LongToLuid(long lluid) { - return new Luid {HighPart = (uint) (lluid >> 32), LowPart = (uint) (lluid & 0xFFFFFFFF)}; + return new LUID {HighPart = (uint) (lluid >> 32), LowPart = (uint) (lluid & 0xFFFFFFFF)}; } diff --git a/AlphaFS/Resources.Designer.cs b/AlphaFS/Resources.Designer.cs index 708bf1a5e..526c04dcc 100644 --- a/AlphaFS/Resources.Designer.cs +++ b/AlphaFS/Resources.Designer.cs @@ -133,6 +133,15 @@ internal static string File_Or_Directory_Already_Exists { } } + /// + /// Looks up a localized string similar to Failed to get the current WindowsIdentity.. + /// + internal static string GetCurrentWindowsIdentityFailed { + get { + return ResourceManager.GetString("GetCurrentWindowsIdentityFailed", resourceCulture); + } + } + /// /// Looks up a localized string similar to Cannot add and remove trailing DirectorySeparator simultaneously.. /// diff --git a/AlphaFS/Resources.resx b/AlphaFS/Resources.resx index 3220908a3..2b2bdf3b3 100644 --- a/AlphaFS/Resources.resx +++ b/AlphaFS/Resources.resx @@ -259,4 +259,7 @@ No drive letters available. + + Failed to get the current WindowsIdentity. + \ No newline at end of file diff --git a/AlphaFS/Safe Handles/SafeTokenHandle.cs b/AlphaFS/Safe Handles/SafeTokenHandle.cs new file mode 100644 index 000000000..0272d34a3 --- /dev/null +++ b/AlphaFS/Safe Handles/SafeTokenHandle.cs @@ -0,0 +1,54 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 Alphaleonis.Win32.Filesystem; +using Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32 +{ + [SecurityCritical] + public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid + { + /// Initializes a new instance of the class. + public SafeTokenHandle() : base(true) + { + } + + + /// Initializes a new instance of the class. + /// The handle. + /// [owns handle]. + public SafeTokenHandle(IntPtr handle, bool callerHandle) : base(callerHandle) + { + SetHandle(handle); + } + + + /// When overridden in a derived class, executes the code required to free the handle. + /// if the handle is released successfully; otherwise, in the event of a catastrophic failure, . In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. + protected override bool ReleaseHandle() + { + return NativeMethods.CloseHandle(handle); + } + } +} diff --git a/AlphaFS/Security/InternalPrivilegeEnabler.cs b/AlphaFS/Security/InternalPrivilegeEnabler.cs index 74ae14592..b3c094d72 100644 --- a/AlphaFS/Security/InternalPrivilegeEnabler.cs +++ b/AlphaFS/Security/InternalPrivilegeEnabler.cs @@ -78,9 +78,9 @@ private void AdjustPrivilege(bool enable) { uint length; var hToken = currentIdentity.Token; - var mOldPrivilege = new TokenPrivileges(); + var mOldPrivilege = new TOKEN_PRIVILEGES(); - var newPrivilege = new TokenPrivileges + var newPrivilege = new TOKEN_PRIVILEGES { PrivilegeCount = 1, Luid = Filesystem.NativeMethods.LongToLuid(EnabledPrivilege.LookupLuid()), diff --git a/AlphaFS/Security/Native Methods/NativeMethods.AdjustTokenPrivileges.cs b/AlphaFS/Security/Native Methods/NativeMethods.AdjustTokenPrivileges.cs index 9aec9c80f..3316c3a0d 100644 --- a/AlphaFS/Security/Native Methods/NativeMethods.AdjustTokenPrivileges.cs +++ b/AlphaFS/Security/Native Methods/NativeMethods.AdjustTokenPrivileges.cs @@ -38,6 +38,6 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, ref TokenPrivileges newState, uint bufferLength, out TokenPrivileges previousState, out uint returnLength); + internal static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, ref TOKEN_PRIVILEGES newState, uint bufferLength, out TOKEN_PRIVILEGES previousState, out uint returnLength); } } diff --git a/AlphaFS/Security/Native Methods/NativeMethods.template.cs b/AlphaFS/Security/Native Methods/NativeMethods.Constants.cs similarity index 77% rename from AlphaFS/Security/Native Methods/NativeMethods.template.cs rename to AlphaFS/Security/Native Methods/NativeMethods.Constants.cs index 935702c8f..35abed276 100644 --- a/AlphaFS/Security/Native Methods/NativeMethods.template.cs +++ b/AlphaFS/Security/Native Methods/NativeMethods.Constants.cs @@ -19,16 +19,14 @@ * THE SOFTWARE. */ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Runtime.InteropServices; -using System.Security; -using Microsoft.Win32.SafeHandles; - namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { + /// Combines DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER access. + public const uint STANDARD_RIGHTS_REQUIRED = 983040; + /// The right to read the information in the object's security descriptor, not including the information in the system access control list (SACL). + public const uint STANDARD_RIGHTS_READ = 131072; } } diff --git a/AlphaFS/Security/Native Methods/NativeMethods.GetTokenInformation.cs b/AlphaFS/Security/Native Methods/NativeMethods.GetTokenInformation.cs new file mode 100644 index 000000000..245e74526 --- /dev/null +++ b/AlphaFS/Security/Native Methods/NativeMethods.GetTokenInformation.cs @@ -0,0 +1,41 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; +using System.Security; + +namespace Alphaleonis.Win32.Security +{ + internal static partial class NativeMethods + { + /// The GetTokenInformation function retrieves a specified type of information about an access token. The calling process must have appropriate access rights to obtain the information. + /// + /// 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. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool GetTokenInformation(SafeTokenHandle tokenHandle, [MarshalAs(UnmanagedType.U4)] TOKEN_INFORMATION_CLASS tokenInformationClass, SafeGlobalMemoryBufferHandle tokenInformation, [MarshalAs(UnmanagedType.U4)] uint tokenInformationLength, [MarshalAs(UnmanagedType.U4)] out uint returnLength); + } +} diff --git a/AlphaFS/Security/Native Methods/NativeMethods.LookupPrivilegeValue.cs b/AlphaFS/Security/Native Methods/NativeMethods.LookupPrivilegeValue.cs index d2b4c7d5d..3f4e7aee6 100644 --- a/AlphaFS/Security/Native Methods/NativeMethods.LookupPrivilegeValue.cs +++ b/AlphaFS/Security/Native Methods/NativeMethods.LookupPrivilegeValue.cs @@ -37,6 +37,6 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "LookupPrivilegeValueW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool LookupPrivilegeValue([MarshalAs(UnmanagedType.LPWStr)] string lpSystemName, [MarshalAs(UnmanagedType.LPWStr)] string lpName, out Luid lpLuid); + internal static extern bool LookupPrivilegeValue([MarshalAs(UnmanagedType.LPWStr)] string lpSystemName, [MarshalAs(UnmanagedType.LPWStr)] string lpName, out LUID lpLuid); } } diff --git a/AlphaFS/Security/Native Methods/NativeMethods.OpenProcessToken.cs b/AlphaFS/Security/Native Methods/NativeMethods.OpenProcessToken.cs new file mode 100644 index 000000000..a304459e9 --- /dev/null +++ b/AlphaFS/Security/Native Methods/NativeMethods.OpenProcessToken.cs @@ -0,0 +1,42 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Security +{ + internal static partial class NativeMethods + { + /// The OpenProcessToken function opens the access token associated with a process. + /// + /// If the function succeeds, the function returns nonzero. + /// If the function fails, it returns zero. To get extended error information, call GetLastError. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool OpenProcessToken(IntPtr processHandle, [MarshalAs(UnmanagedType.U4)] TOKEN desiredAccess, out SafeTokenHandle tokenHandle); + } +} diff --git a/AlphaFS/Security/Native Other/Luid.cs b/AlphaFS/Security/Native Other/Luid.cs index 518d14ac6..bad9de2b9 100644 --- a/AlphaFS/Security/Native Other/Luid.cs +++ b/AlphaFS/Security/Native Other/Luid.cs @@ -23,10 +23,18 @@ namespace Alphaleonis.Win32.Security { + /// An LUID is a 64-bit value guaranteed to be unique only on the system on which it was generated. The uniqueness of a locally unique identifier (LUID) is guaranteed only until the system is restarted. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct Luid + internal struct LUID { + /// Low-order bits. [MarshalAs(UnmanagedType.U4)] public uint LowPart; + + /// High-order bits. [MarshalAs(UnmanagedType.U4)] public uint HighPart; } } diff --git a/AlphaFS/Security/Native Other/SE_OBJECT_TYPE.cs b/AlphaFS/Security/Native Other/SE_OBJECT_TYPE.cs index 57eaa3904..87977410b 100644 --- a/AlphaFS/Security/Native Other/SE_OBJECT_TYPE.cs +++ b/AlphaFS/Security/Native Other/SE_OBJECT_TYPE.cs @@ -24,6 +24,10 @@ namespace Alphaleonis.Win32.Security /// 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. /// + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// internal enum SE_OBJECT_TYPE { /// Unknown object type. diff --git a/AlphaFS/Security/Native Other/TOKEN.cs b/AlphaFS/Security/Native Other/TOKEN.cs new file mode 100644 index 000000000..4f5231eb4 --- /dev/null +++ b/AlphaFS/Security/Native Other/TOKEN.cs @@ -0,0 +1,67 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// [AlphaFS] Access rights for access-token objects. + [Flags] + internal enum TOKEN : uint + { + /// Required to attach a primary token to a process. The SE_ASSIGNPRIMARYTOKEN_NAME privilege is also required to accomplish this task. + TOKEN_ASSIGN_PRIMARY = 1, + + /// Required to duplicate an access token. + TOKEN_DUPLICATE = 2, + + /// Required to attach an impersonation access token to a process. + TOKEN_IMPERSONATE = 4, + + /// Required to query an access token. + TOKEN_QUERY = 8, + + /// Required to query the source of an access token. + TOKEN_QUERY_SOURCE = 16, + + /// Required to enable or disable the privileges in an access token. + TOKEN_ADJUST_PRIVILEGES = 32, + + /// Required to adjust the attributes of the groups in an access token. + TOKEN_ADJUST_GROUPS = 64, + + /// Required to change the default owner, primary group, or DACL of an access token. + TOKEN_ADJUST_DEFAULT = 128, + + /// Required to adjust the session ID of an access token. The SE_TCB_NAME privilege is required. + TOKEN_ADJUST_SESSIONID = 256, + + /// Combines STANDARD_RIGHTS_READ and TOKEN_QUERY. + TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY, + + /// Combines all possible access rights for a token. + 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 + } + } +} diff --git a/AlphaFS/Security/Native Other/TOKEN_ELEVATION_TYPE.cs b/AlphaFS/Security/Native Other/TOKEN_ELEVATION_TYPE.cs new file mode 100644 index 000000000..bfd865d56 --- /dev/null +++ b/AlphaFS/Security/Native Other/TOKEN_ELEVATION_TYPE.cs @@ -0,0 +1,43 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// The TOKEN_ELEVATION_TYPE enumeration indicates the elevation type of token being queried by the GetTokenInformation function. + /// + /// Minimum supported client: Windows Vista [desktop apps only] + /// Minimum supported server: Windows Server 2008 [desktop apps only] + /// + internal enum TOKEN_ELEVATION_TYPE + { + ///// 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). + //TokenElevationTypeDefault = 1, + + /// The token is an elevated token: UAC is enabled and User is elevated. + TokenElevationTypeFull = 2, + + ///// The token is a limited token: UAC is enabled but User is not elevated. + //TokenElevationTypeLimited = 3 + } + } +} diff --git a/AlphaFS/Security/Native Other/TOKEN_INFORMATION_CLASS.cs b/AlphaFS/Security/Native Other/TOKEN_INFORMATION_CLASS.cs new file mode 100644 index 000000000..312aa811d --- /dev/null +++ b/AlphaFS/Security/Native Other/TOKEN_INFORMATION_CLASS.cs @@ -0,0 +1,160 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// The TOKEN_INFORMATION_CLASS enumeration contains values that specify the type of information being assigned to or retrieved from an access token. + /// The GetTokenInformation function uses these values to indicate the type of token information to retrieve. + /// The SetTokenInformation function uses these values to set the token information. + /// + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + internal enum TOKEN_INFORMATION_CLASS + { + ///// The buffer receives a TOKEN_USER structure that contains the user account of the token. + //TokenUser = 1, + + ///// The buffer receives a TOKEN_GROUPS structure that contains the group accounts associated with the token. + //TokenGroups = 2, + + ///// The buffer receives a TOKEN_PRIVILEGES structure that contains the privileges of the token. + //TokenPrivileges = 3, + + ///// The buffer receives a TOKEN_OWNER structure that contains the default owner security identifier (SID) for newly created objects. + //TokenOwner = 4, + + ///// The buffer receives a TOKEN_PRIMARY_GROUP structure that contains the default primary group SID for newly created objects. + //TokenPrimaryGroup = 5, + + ///// The buffer receives a TOKEN_DEFAULT_DACL structure that contains the default DACL for newly created objects. + //TokenDefaultDacl = 6, + + ///// The buffer receives a TOKEN_SOURCE structure that contains the source of the token. TOKEN_QUERY_SOURCE access is needed to retrieve this information. + //TokenSource = 7, + + ///// The buffer receives a TOKEN_TYPE value that indicates whether the token is a primary or impersonation token. + //TokenType = 8, + + ///// 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. + //TokenImpersonationLevel = 9, + + ///// The buffer receives a TOKEN_STATISTICS structure that contains various token statistics. + //TokenStatistics = 10, + + ///// The buffer receives a TOKEN_GROUPS structure that contains the list of restricting SIDs in a restricted token. + //TokenRestrictedSids = 11, + + ///// The buffer receives a DWORD value that indicates the Terminal Services session identifier that is associated with the token. + //TokenSessionId = 12, + + ///// 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. + //TokenGroupsAndPrivileges = 13, + + ///// Reserved. + //TokenSessionReference = 14, + + ///// The buffer receives a DWORD value that is nonzero if the token includes the SANDBOX_INERT flag. + //TokenSandBoxInert = 15, + + ///// Reserved. + //TokenAuditPolicy = 16, + + ///// The buffer receives a TOKEN_ORIGIN value. + //TokenOrigin = 17, + + /// The buffer receives a TOKEN_ELEVATION_TYPE value that specifies the elevation level of the token. + TokenElevationType = 18, + + ///// The buffer receives a TOKEN_LINKED_TOKEN structure that contains a handle to another token that is linked to this token. + //TokenLinkedToken = 19, + + ///// The buffer receives a TOKEN_ELEVATION structure that specifies whether the token is elevated. + //TokenElevation = 20, + + ///// The buffer receives a DWORD value that is nonzero if the token has ever been filtered. + //TokenHasRestrictions = 21, + + ///// The buffer receives a TOKEN_ACCESS_INFORMATION structure that specifies security information contained in the token. + //TokenAccessInformation = 22, + + ///// The buffer receives a DWORD value that is nonzero if virtualization is allowed for the token. + //TokenVirtualizationAllowed = 23, + + ///// The buffer receives a DWORD value that is nonzero if virtualization is enabled for the token. + //TokenVirtualizationEnabled = 24, + + ///// The buffer receives a TOKEN_MANDATORY_LABEL structure that specifies the token's integrity level. + //TokenIntegrityLevel = 25, + + ///// The buffer receives a DWORD value that is nonzero if the token has the UIAccess flag set. + //TokenUIAccess = 26, + + ///// The buffer receives a TOKEN_MANDATORY_POLICY structure that specifies the token's mandatory integrity policy. + //TokenMandatoryPolicy = 27, + + ///// The buffer receives a TOKEN_GROUPS structure that specifies the token's logon SID. + //TokenLogonSid = 28, + + ///// The buffer receives a DWORD value that is nonzero if the token is an app container token. + //TokenIsAppContainer = 29, + + ///// The buffer receives a TOKEN_GROUPS structure that contains the capabilities associated with the token. + //TokenCapabilities = 30, + + ///// The buffer receives a TOKEN_APPCONTAINER_INFORMATION structure that contains the AppContainerSid associated with the token. + //TokenAppContainerSid = 31, + + ///// 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. + //TokenAppContainerNumber = 32, + + ///// The buffer receives a CLAIM_SECURITY_ATTRIBUTES_INFORMATION structure that contains the user claims associated with the token. + //TokenUserClaimAttributes = 33, + + ///// The buffer receives a CLAIM_SECURITY_ATTRIBUTES_INFORMATION structure that contains the device claims associated with the token. + //TokenDeviceClaimAttributes = 34, + + ///// This value is reserved. + //TokenRestrictedUserClaimAttributes = 35, + + ///// This value is reserved. + //TokenRestrictedDeviceClaimAttributes = 36, + + ///// The buffer receives a TOKEN_GROUPS structure that contains the device groups that are associated with the token. + //TokenDeviceGroups = 37, + + ///// The buffer receives a TOKEN_GROUPS structure that contains the restricted device groups that are associated with the token. + //TokenRestrictedDeviceGroups = 38, + + ///// This value is reserved. + //TokenSecurityAttributes = 39, + + ///// This value is reserved. + //TokenIsRestricted = 40, + + ///// The maximum value for this enumeration. + //MaxTokenInfoClass = 41 + } + } +} diff --git a/AlphaFS/Security/Native Other/TokenPrivileges.cs b/AlphaFS/Security/Native Other/TOKEN_PRIVILEGES.cs similarity index 59% rename from AlphaFS/Security/Native Other/TokenPrivileges.cs rename to AlphaFS/Security/Native Other/TOKEN_PRIVILEGES.cs index bfbe0c0e6..9451372b6 100644 --- a/AlphaFS/Security/Native Other/TokenPrivileges.cs +++ b/AlphaFS/Security/Native Other/TOKEN_PRIVILEGES.cs @@ -23,11 +23,22 @@ namespace Alphaleonis.Win32.Security { + /// The TOKEN_PRIVILEGES structure contains information about a set of privileges for an access token. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct TokenPrivileges + internal struct TOKEN_PRIVILEGES { + /// This must be set to the number of entries in the Privileges array. [MarshalAs(UnmanagedType.U4)] public uint PrivilegeCount; - internal Luid Luid; + + /// Specifies an array of LUID_AND_ATTRIBUTES structures. Each structure contains the LUID and attributes of a privilege. + public LUID Luid; + + /// The attributes of a privilege can be a combination of the following values: + /// SE_PRIVILEGE_ENABLED: The privilege is enabled. + /// SE_PRIVILEGE_ENABLED_BY_DEFAULT: The privilege is enabled by default. + /// SE_PRIVILEGE_REMOVED: Used to remove a privilege. For details, see AdjustTokenPrivileges. + /// SE_PRIVILEGE_USED_FOR_ACCESS: The privilege was used to gain access to an object or service. This flag is used to identify the relevant privileges in a set passed by a client application that may contain unnecessary privileges. + /// [MarshalAs(UnmanagedType.U4)] public uint Attributes; } } diff --git a/AlphaFS/Security/Privilege.cs b/AlphaFS/Security/Privilege.cs index 1dce65815..e461dedf9 100644 --- a/AlphaFS/Security/Privilege.cs +++ b/AlphaFS/Security/Privilege.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -267,7 +267,7 @@ public string LookupDisplayName() uint languageId; const uint initialCapacity = 10; var displayNameCapacity = initialCapacity; - var displayName = new StringBuilder((int) displayNameCapacity); + var displayName = new StringBuilder((int)displayNameCapacity); var success = NativeMethods.LookupPrivilegeDisplayName(_systemName, _name, ref displayName, ref displayNameCapacity, out languageId); @@ -277,7 +277,7 @@ public string LookupDisplayName() { if (lastError == Win32Errors.ERROR_INSUFFICIENT_BUFFER) { - displayName = new StringBuilder((int) displayNameCapacity + 1); + displayName = new StringBuilder((int)displayNameCapacity + 1); success = NativeMethods.LookupPrivilegeDisplayName(_systemName, _name, ref displayName, ref displayNameCapacity, out languageId); @@ -296,10 +296,10 @@ public string LookupDisplayName() /// Retrieves the locally unique identifier (LUID) used on to represent this privilege (on the system from which it originates). /// the locally unique identifier (LUID) used on to represent this privilege (on the system from which it originates). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Luid")] - [SecurityCritical] + [SecurityCritical] public long LookupLuid() { - Luid luid; + LUID luid; var success = NativeMethods.LookupPrivilegeValue(_systemName, _name, out luid); @@ -338,8 +338,8 @@ public override bool Equals(object obj) (null == _systemName && null == other._systemName || null != _systemName && _systemName.Equals(other._systemName, StringComparison.OrdinalIgnoreCase)); } - - + + /// Serves as a hash function for a particular type. /// A hash code for the current Object. public override int GetHashCode() diff --git a/AlphaFS/Security/ProcessContext.cs b/AlphaFS/Security/ProcessContext.cs new file mode 100644 index 000000000..b9dab560c --- /dev/null +++ b/AlphaFS/Security/ProcessContext.cs @@ -0,0 +1,146 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// [AlphaFS] Class to determine the context of the current process. + public static class ProcessContext + { + #region Properties + + /// [AlphaFS] Determines if the current process is run in the context of an Administrator. + /// if the current process is run in the context of an Administrator; otherwise, . + 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); + } + } + + + /// [AlphaFS] Determines if UAC is enabled and that the current process is in an elevated state. + /// If the current User is the default Administrator then the process is assumed to be in an elevated state. + /// This assumption is made because by default, the default Administrator (disabled by default) gets all access rights without showing an UAC prompt. + /// + /// if UAC is enabled and the current process is in an elevated state; otherwise, . + public static bool IsElevatedProcess + { + get + { + return IsUacEnabled && (GetProcessElevationType() == NativeMethods.TOKEN_ELEVATION_TYPE.TokenElevationTypeFull || IsAdministrator); + } + } + + + /// [AlphaFS] Determines if UAC is enabled by reading the "EnableLUA" registry key of the local Computer. + /// if the UAC status was successfully read from registry; otherwise, . + [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); + } + } + + + /// [AlphaFS] Determines if the current process is run in the context of a Windows Service. + /// if the current process is run in the context of a Windows Service; otherwise, . + 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); + } + + + /// [AlphaFS] Retrieves the elevation type of the current process. + /// A value. + 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(); + } + } + } +} diff --git a/AlphaFS/Security/SecurityAttributes.cs b/AlphaFS/Security/SecurityAttributes.cs index 2e8cbb312..0d7b16c6c 100644 --- a/AlphaFS/Security/SecurityAttributes.cs +++ b/AlphaFS/Security/SecurityAttributes.cs @@ -28,7 +28,10 @@ namespace Alphaleonis.Win32.Security { internal static partial class NativeMethods { - /// Class used to represent the SECURITY_ATTRIBUTES native Win32 structure. It provides initialization function from an object. + /// 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. + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class SecurityAttributes : IDisposable { @@ -37,7 +40,7 @@ internal sealed class SecurityAttributes : IDisposable [MarshalAs(UnmanagedType.U4)] private int _length; - + private readonly SafeGlobalMemoryBufferHandle _securityDescriptor; @@ -67,8 +70,8 @@ private static SafeGlobalMemoryBufferHandle ToUnmanagedSecurityAttributes(Object { if (null == securityDescriptor) return new SafeGlobalMemoryBufferHandle(); - - + + var src = securityDescriptor.GetSecurityDescriptorBinaryForm(); var safeBuffer = new SafeGlobalMemoryBufferHandle(src.Length); @@ -84,7 +87,7 @@ private static SafeGlobalMemoryBufferHandle ToUnmanagedSecurityAttributes(Object } } - + public void Dispose() { if (null != _securityDescriptor && !_securityDescriptor.IsClosed) From c7216cef69d63d59e63d9c3ea9191ed9b0b92496 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 17 Feb 2018 10:42:37 +0100 Subject: [PATCH 048/133] -Improved method EnumeratePhysicalDrives; -Using Security.ProcessContext.IsElevatedProcess to retrieve more info when process is elevated; --- .../Device.EnumeratePhysicalDrives.cs | 150 ++++++++---------- .../Device.GetPhysicalDriveInfo.cs | 43 +++-- .../Device.GetStorageDeviceInfo.cs | 22 ++- AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs | 2 +- AlphaFS/Security/ProcessContext.cs | 6 +- 5 files changed, 103 insertions(+), 120 deletions(-) diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs index abe3911df..abc071baa 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; @@ -34,134 +33,125 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrives() { - var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, null, deviceInfo, true)).Where(physicalDrive => null != physicalDrive).ToArray(); + return EnumeratePhysicalDrives(Security.ProcessContext.IsElevatedProcess); + } + + + /// [AlphaFS] Enumerates the physical drives on the Computer, populated with volume- and logical drive information. + /// An collection that represents the physical drives on the Computer. + [SecurityCritical] + internal static IEnumerable EnumeratePhysicalDrives(bool isElevated) + { + var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(isElevated, null, null, deviceInfo, true)).Where(physicalDrive => null != physicalDrive).ToArray(); - var pVolumes = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(null, volumeGuid, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); + var pVolumes = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(isElevated, null, volumeGuid, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); - var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(null, driveName, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); + var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(isElevated, null, driveName, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); foreach (var pDrive in physicalDrives) - { - var pDriveInfo = new PhysicalDriveInfo(pDrive) - { - StorageDeviceInfo = - { - DeviceNumber = pDrive.StorageDeviceInfo.DeviceNumber, - PartitionNumber = pDrive.StorageDeviceInfo.PartitionNumber - } - }; - - // Get volume from physical drive matching DeviceNumber. + yield return PopulatePhysicalDrive(pDrive, pVolumes, pLogicalDrives); - foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDriveInfo.StorageDeviceInfo.DeviceNumber)) - { - // Add device volume labels. - if (null == pDriveInfo.VolumeLabels) - pDriveInfo.VolumeLabels = new Collection(); + // Windows Disk Management shows CD-ROM so mimic that behaviour. - pDriveInfo.VolumeLabels.Add(pVolume.Name); + var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => GetPhysicalDriveInfoCore(isElevated, null, null, deviceInfo, true)).Where(physicalDrive => null != physicalDrive).ToArray(); + foreach (var pCdRom in cdRoms) - // Add device partition index numbers. + yield return PopulatePhysicalCDRom(pCdRom, pVolumes, pLogicalDrives); + } - if (null == pDriveInfo.PartitionIndexes) - pDriveInfo.PartitionIndexes = new Collection(); - pDriveInfo.PartitionIndexes.Add(pVolume.StorageDeviceInfo.PartitionNumber); + private static void PopulateLogicalDriveDetails(PhysicalDriveInfo pDriveInfo, PhysicalDriveInfo pLogicalDrive) + { + // Add device logical drive. + + if (null == pDriveInfo.LogicalDrives) + pDriveInfo.LogicalDrives = new Collection(); + pDriveInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(pLogicalDrive.DevicePath)); + } - // Add device volume GUIDs. - if (null == pDriveInfo.VolumeGuids) - pDriveInfo.VolumeGuids = new Collection(); + private static void PopulateVolumeDetails(PhysicalDriveInfo pDriveInfo, PhysicalDriveInfo pVolume) + { + // Add device volume labels. - pDriveInfo.VolumeGuids.Add(pVolume.DevicePath); + if (null == pDriveInfo.VolumeLabels) + pDriveInfo.VolumeLabels = new Collection(); + pDriveInfo.VolumeLabels.Add(pVolume.Name); - - - // Get logical drive from volume matching DeviceNumber and PartitionNumber. - foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pVolume.StorageDeviceInfo.PartitionNumber)) - { - if (null == pDriveInfo.LogicalDrives) - pDriveInfo.LogicalDrives = new Collection(); + // Add device partition index numbers. - pDriveInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(pLogicalDrive.DevicePath)); - } - } + if (null == pDriveInfo.PartitionIndexes) + pDriveInfo.PartitionIndexes = new Collection(); + pDriveInfo.PartitionIndexes.Add(pVolume.StorageDeviceInfo.PartitionNumber); - yield return pDriveInfo; - } + // Add device volume GUIDs. - // Windows Disk Management shows CD-ROM so mimic that behaviour. - var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => GetPhysicalDriveInfoCore(null, null, deviceInfo, true)).Where(physicalDrive => null != physicalDrive).ToArray(); + if (null == pDriveInfo.VolumeGuids) + pDriveInfo.VolumeGuids = new Collection(); - foreach (var pCdRom in cdRoms) - { - var pDriveInfo = new PhysicalDriveInfo(pCdRom) - { - StorageDeviceInfo = - { - DeviceNumber = pCdRom.StorageDeviceInfo.DeviceNumber, - PartitionNumber = pCdRom.StorageDeviceInfo.PartitionNumber - } - }; + pDriveInfo.VolumeGuids.Add(pVolume.DevicePath); + } - // Get volume from CDRom matching DeviceNumber. + private static PhysicalDriveInfo PopulatePhysicalCDRom(PhysicalDriveInfo pCdRom, PhysicalDriveInfo[] pVolumes, PhysicalDriveInfo[] pLogicalDrives) + { + var pDriveInfo = new PhysicalDriveInfo(pCdRom) {StorageDeviceInfo = pCdRom.StorageDeviceInfo}; - var pVolume = pVolumes.FirstOrDefault(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDriveInfo.StorageDeviceInfo.DeviceNumber && pVol.StorageDeviceInfo.PartitionNumber == pDriveInfo.StorageDeviceInfo.PartitionNumber); - if (null != pVolume) - { - // Add device volume labels. + // Get volume from CDRom matching DeviceNumber. - if (null == pDriveInfo.VolumeLabels) - pDriveInfo.VolumeLabels = new Collection(); + var pVolume = pVolumes.SingleOrDefault(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDriveInfo.StorageDeviceInfo.DeviceNumber && pVol.StorageDeviceInfo.PartitionNumber == pDriveInfo.StorageDeviceInfo.PartitionNumber); - pDriveInfo.VolumeLabels.Add(pVolume.Name); + if (null != pVolume) + { + PopulateVolumeDetails(pDriveInfo, pVolume); - // Add device partition index numbers. + // Get logical drive from CDRom matching DeviceNumber and PartitionNumber. - if (null == pDriveInfo.PartitionIndexes) - pDriveInfo.PartitionIndexes = new Collection(); + var pLogicalDrive = pLogicalDrives.SingleOrDefault(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pVolume.StorageDeviceInfo.PartitionNumber); - pDriveInfo.PartitionIndexes.Add(pVolume.StorageDeviceInfo.PartitionNumber); + if (null != pLogicalDrive) + PopulateLogicalDriveDetails(pDriveInfo, pLogicalDrive); + } - // Add device volume GUIDs. + return pDriveInfo; + } - if (null == pDriveInfo.VolumeGuids) - pDriveInfo.VolumeGuids = new Collection(); - pDriveInfo.VolumeGuids.Add(pVolume.DevicePath); + private static PhysicalDriveInfo PopulatePhysicalDrive(PhysicalDriveInfo pDrive, PhysicalDriveInfo[] pVolumes, PhysicalDriveInfo[] pLogicalDrives) + { + var pDriveInfo = new PhysicalDriveInfo(pDrive) {StorageDeviceInfo = pDrive.StorageDeviceInfo}; + foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDriveInfo.StorageDeviceInfo.DeviceNumber)) + { + var volumeDriveNumber = pVolume.StorageDeviceInfo.DeviceNumber; + var volumePartitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; - // Get logical drive from CDRom matching DeviceNumber and PartitionNumber. + PopulateVolumeDetails(pDriveInfo, pVolume); - var logicalDrive = pLogicalDrives.FirstOrDefault(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pVolume.StorageDeviceInfo.PartitionNumber); - if (null != logicalDrive) - { - if (null == pDriveInfo.LogicalDrives) - pDriveInfo.LogicalDrives = new Collection(); + // Get logical drive from volume matching DeviceNumber and PartitionNumber. - pDriveInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(logicalDrive.DevicePath)); - } - } - + foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == volumeDriveNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == volumePartitionNumber)) - yield return pDriveInfo; + PopulateLogicalDriveDetails(pDriveInfo, pLogicalDrive); } + + + return pDriveInfo; } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index 67cf7bbc8..2c6e11904 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -21,9 +21,7 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Globalization; using System.Linq; -using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; @@ -31,9 +29,9 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// [AlphaFS] Retrieves the physical drive on the Computer that is related to the logical drive name, volume GUID or . + /// [AlphaFS] Retrieves the physical drive on the Computer that is related to the logical drive name, volume GUID or . /// Do not call this method for every volume or logical drive on the system as each call queries all physical drives and associated volumes and logical drives. - /// Instead, use method and property or . + /// Instead, use method and property and/or . /// /// A instance that represents the physical drive on the Computer or null on error/no data available. /// @@ -52,9 +50,12 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) bool isDeviceInfo; string logicalDrive; - devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); - var storageInfo = GetStorageDeviceInfoCore(devicePath, false); + var isElevated = Security.ProcessContext.IsElevatedProcess; + + devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + + var storageInfo = GetStorageDeviceInfoCore(isElevated, devicePath, false); if (null == storageInfo) return null; @@ -69,13 +70,13 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) var pDriveInfo = isDeviceInfo - ? EnumeratePhysicalDrives().FirstOrDefault(pDrive => pDrive.StorageDeviceInfo.DeviceNumber == storageInfo.DeviceNumber && pDrive.StorageDeviceInfo.PartitionNumber == storageInfo.PartitionNumber) + ? EnumeratePhysicalDrives(isElevated).FirstOrDefault(pDrive => pDrive.StorageDeviceInfo.DeviceNumber == storageInfo.DeviceNumber && pDrive.StorageDeviceInfo.PartitionNumber == storageInfo.PartitionNumber) : isVolume - ? EnumeratePhysicalDrives().FirstOrDefault(pDrive => null != pDrive.VolumeGuids && pDrive.VolumeGuids.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) + ? EnumeratePhysicalDrives(isElevated).FirstOrDefault(pDrive => null != pDrive.VolumeGuids && pDrive.VolumeGuids.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) : isDrive - ? EnumeratePhysicalDrives().FirstOrDefault(pDrive => null != pDrive.LogicalDrives && pDrive.LogicalDrives.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) + ? EnumeratePhysicalDrives(isElevated).FirstOrDefault(pDrive => null != pDrive.LogicalDrives && pDrive.LogicalDrives.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) : null; @@ -87,12 +88,15 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) } - /// [AlphaFS] Gets the physical drive information such as DeviceType, DeviceNumber, PartitionNumber and the serial number and Product ID. + + + /// [AlphaFS] Retrieves the physical drive information such as DeviceType, DeviceNumber, PartitionNumber and the serial number and Product ID. /// A instance that represents the physical drive on the Computer or null on error/no data available. /// /// /// /// + /// /// A instance. /// /// A drive path such as: "C", "C:" or "C:\". @@ -100,12 +104,12 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// A string (when is set to ). /// /// A instance. - /// /// + /// /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(StorageDeviceInfo storageInfo, string devicePath, DeviceInfo deviceInfo, bool? getAllData) + internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, StorageDeviceInfo storageInfo, string devicePath, DeviceInfo deviceInfo, bool? getAllData) { var isDeviceInfo = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); @@ -114,7 +118,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(StorageDeviceInfo sto if (null == storageInfo) - storageInfo = GetStorageDeviceInfoCore(devicePath, false); + storageInfo = GetStorageDeviceInfoCore(isElevated, devicePath, false); if (null == storageInfo) return null; @@ -129,17 +133,10 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(StorageDeviceInfo sto // "FriendlyName" usually contains a more complete name, as seen in Windows Explorer. Name = isDeviceInfo ? deviceInfo.FriendlyName : null, }; - - if (null != getAllData) - { - try - { - // Requires elevation. - PopulatePhysicalDriveInfo((bool) getAllData, devicePath, pDriveInfo); - } - catch { } - } + + if (isElevated && null != getAllData) + PopulatePhysicalDriveInfo((bool) getAllData, devicePath, pDriveInfo); return pDriveInfo; diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs index ccd4dec2f..facf31007 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs @@ -20,17 +20,13 @@ */ using System; -using System.ComponentModel; using System.Globalization; -using System.IO; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// [AlphaFS] Get the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . /// A instance that represent the storage device on the Computer that is related to . /// /// @@ -43,11 +39,11 @@ public static partial class Device /// public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { - return GetStorageDeviceInfoCore(devicePath, false); + return GetStorageDeviceInfoCore(Security.ProcessContext.IsElevatedProcess, devicePath, false); } - /// [AlphaFS] Get the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . /// A instance that represent the storage device on the Computer that is related to . /// /// @@ -61,23 +57,24 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) /// When true also get the which requires elevated rights. public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath, bool getBusType) { - return GetStorageDeviceInfoCore(devicePath, getBusType); + return GetStorageDeviceInfoCore(Security.ProcessContext.IsElevatedProcess, devicePath, getBusType); } - /// [AlphaFS] Get the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . /// A instance that represent the storage device on the Computer that is related to . /// /// /// /// + /// /// /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// A string (when is set to ). /// /// When true also get the which requires elevated rights. - internal static StorageDeviceInfo GetStorageDeviceInfoCore(string devicePath, bool getBusType) + internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, string devicePath, bool getBusType) { string logicalDrive; @@ -121,11 +118,10 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(string devicePath, bo { storageInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure(0)); + if (getBusType) { - // Requires elevation. - - var pDriveInfo = GetPhysicalDriveInfoCore(storageInfo, pathToDevice, null, false); + var pDriveInfo = GetPhysicalDriveInfoCore(isElevated, storageInfo, pathToDevice, null, false); if (null != pDriveInfo) storageInfo.BusType = pDriveInfo.StorageDeviceInfo.BusType; diff --git a/AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs b/AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs index ae122de81..9441f5f18 100644 --- a/AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs +++ b/AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs @@ -41,7 +41,7 @@ public static DiskSpaceInfo GetDiskFreeSpace(string drivePath) } - /// [AlphaFS] + /// [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. /// diff --git a/AlphaFS/Security/ProcessContext.cs b/AlphaFS/Security/ProcessContext.cs index b9dab560c..16ea084b7 100644 --- a/AlphaFS/Security/ProcessContext.cs +++ b/AlphaFS/Security/ProcessContext.cs @@ -57,7 +57,7 @@ public static bool IsAdministrator } - /// [AlphaFS] Determines if UAC is enabled and that the current process is in an elevated state. + /// [AlphaFS] Determines that UAC is enabled and that the current process is in an elevated state. /// If the current User is the default Administrator then the process is assumed to be in an elevated state. /// This assumption is made because by default, the default Administrator (disabled by default) gets all access rights without showing an UAC prompt. /// @@ -71,7 +71,7 @@ public static bool IsElevatedProcess } - /// [AlphaFS] Determines if UAC is enabled by reading the "EnableLUA" registry key of the local Computer. + /// [AlphaFS] Determines that UAC is enabled by reading the "EnableLUA" registry key of the local Computer. /// if the UAC status was successfully read from registry; otherwise, . [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Uac")] public static bool IsUacEnabled @@ -85,7 +85,7 @@ public static bool IsUacEnabled } - /// [AlphaFS] Determines if the current process is run in the context of a Windows Service. + /// [AlphaFS] Determines that the current process is run in the context of a Windows Service. /// if the current process is run in the context of a Windows Service; otherwise, . public static bool IsWindowsService { From d813fc30e70285d1bf7dd23e704503faf32f477c Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 17 Feb 2018 12:59:42 +0100 Subject: [PATCH 049/133] Code improvement, work in progress. --- AlphaFS/Device/Device.EnumerateDevices.cs | 11 +++++++---- AlphaFS/Device/Device.GetDeviceIoData.cs | 6 +++++- .../PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs | 5 ++--- .../PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs | 2 +- .../Filesystem/Structures, Enumerations/DeviceGuid.cs | 1 - 5 files changed, 15 insertions(+), 10 deletions(-) diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Device.EnumerateDevices.cs index f839e9af6..260f48a40 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -56,6 +56,10 @@ public static IEnumerable EnumerateDevices(string hostName, DeviceGu [SecurityCritical] internal static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid interfaceGuid, 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. @@ -86,7 +90,7 @@ internal static IEnumerable EnumerateDevicesCore(string hostName, De // Start enumerating device interfaces. - do + while (true) { var interfaceData = new NativeMethods.SP_DEVICE_INTERFACE_DATA {cbSize = interfaceStructSize}; @@ -122,8 +126,7 @@ internal static IEnumerable EnumerateDevicesCore(string hostName, De yield return deviceInfo; - - } while (true); + } } } @@ -206,7 +209,7 @@ private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMet // the requested property does not exist for a device or if the property data is not valid. if (lastError == Win32Errors.ERROR_INVALID_DATA) - return string.Empty; + return null; bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, property.ToString()); diff --git a/AlphaFS/Device/Device.GetDeviceIoData.cs b/AlphaFS/Device/Device.GetDeviceIoData.cs index 1d7b05541..d4366e5a2 100644 --- a/AlphaFS/Device/Device.GetDeviceIoData.cs +++ b/AlphaFS/Device/Device.GetDeviceIoData.cs @@ -52,7 +52,11 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa // Dynamic disk. - if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) + if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || + + // Request device number from a DeviceGuid.StillImage device. + lastError == Win32Errors.ERROR_NOT_SUPPORTED) + return null; diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index 2c6e11904..bdad46ec6 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -96,7 +96,7 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// /// /// - /// + /// indicates the current process is in an elevated state, allowing to retrieve more data. /// A instance. /// /// A drive path such as: "C", "C:" or "C:\". @@ -105,7 +105,6 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// /// A instance. /// - /// /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] @@ -135,7 +134,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, Stor }; - if (isElevated && null != getAllData) + if (null != getAllData && isElevated) PopulatePhysicalDriveInfo((bool) getAllData, devicePath, pDriveInfo); diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs index facf31007..68b6d7773 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs @@ -67,7 +67,7 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath, bool get /// /// /// - /// + /// indicates the current process is in an elevated state, allowing to retrieve more data. /// /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs index 9fbecab63..e98404555 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; From 6a9ec41c74ef67ca5206ae8a127d744c3b758f89 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 17 Feb 2018 23:21:26 +0100 Subject: [PATCH 050/133] -Added class Filesystem.StorageAdapterInfo; -Code improvement, work in progress. --- .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 6 +- ...ice.GetPhysicalDriveInfo_FromDevicePath.cs | 9 +- ...e.GetPhysicalDriveInfo_FromLogicalDrive.cs | 9 +- ..._Device.GetPhysicalDriveInfo_FromVolume.cs | 16 +- ...e.GetStorageDeviceInfo_FromLogicalDrive.cs | 6 +- AlphaFS/AlphaFS.csproj | 8 +- AlphaFS/Device/Device.EnumerateDevices.cs | 17 +- AlphaFS/Device/Device.InvokeDeviceIoData.cs | 4 + .../Device.EnumeratePhysicalDrives.cs | 28 +- .../Device.GetPhysicalDriveInfo.cs | 77 +++-- .../Device.GetStorageDeviceInfo.cs | 53 +-- .../PhysicalDriveInfo/PhysicalDriveInfo.cs | 48 +-- AlphaFS/Device/StorageAdapterInfo.cs | 164 ++++++++++ AlphaFS/Device/StorageDeviceInfo.cs | 95 ++++-- .../Filesystem/Native Other/DISK_GEOMETRY.cs | 2 +- AlphaFS/Filesystem/Native Other/MEDIA_TYPE.cs | 112 ------- .../STORAGE_ADAPTER_DESCRIPTOR.cs | 105 ++++++ .../Native Other/STORAGE_BUS_TYPE.cs | 4 + .../Native Other/STORAGE_DEVICE_DESCRIPTOR.cs | 20 +- .../Native Other/STORAGE_MEDIA_TYPE.cs | 303 ++++++++++++++++++ .../Native Other/STORAGE_PROPERTY_ID.cs | 109 +++++++ .../Native Other/STORAGE_PROPERTY_QUERY.cs | 4 +- .../Native Other/STORAGE_QUERY_TYPE.cs | 46 +++ AlphaFS/Safe Handles/SafeTokenHandle.cs | 1 + AlphaFS/Security/ProcessContext.cs | 2 + 25 files changed, 952 insertions(+), 296 deletions(-) create mode 100644 AlphaFS/Device/StorageAdapterInfo.cs delete mode 100644 AlphaFS/Filesystem/Native Other/MEDIA_TYPE.cs create mode 100644 AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs create mode 100644 AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs create mode 100644 AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs create mode 100644 AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs index dc8e10f09..fc762b542 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -45,9 +45,11 @@ public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]", ++pDriveCount, pDrive.StorageDeviceInfo.DeviceNumber); - UnitTestConstants.Dump(pDrive, -17); + UnitTestConstants.Dump(pDrive, -24); - UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -15, true); + UnitTestConstants.Dump(pDrive.StorageAdapterInfo, -28, true); + + UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -17, true); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs index 18803e1f7..74300f695 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs @@ -45,12 +45,15 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromDevicePath_Success() Console.WriteLine(); - Console.WriteLine("#{0:000}\tDevice Path: [{1}]", ++deviceCount, devicePath); + Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); - UnitTestConstants.Dump(pDrive, -17); + UnitTestConstants.Dump(pDrive, -24); - UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -15, true); + UnitTestConstants.Dump(pDrive.StorageAdapterInfo, -28, true); + + UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -17, true); + Console.WriteLine(); Assert.IsNotNull(pDrive); diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs index e295e294c..47050153f 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs @@ -43,12 +43,15 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromLogicalDrive_Success() var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceDrive); Console.WriteLine(); - Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, sourceDrive); + Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]", ++driveCount, sourceDrive); - UnitTestConstants.Dump(pDrive, -17); + UnitTestConstants.Dump(pDrive, -24); - UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -15, true); + UnitTestConstants.Dump(pDrive.StorageAdapterInfo, -28, true); + + UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -17, true); + Console.WriteLine(); Assert.IsNotNull(pDrive); diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs index e3ca8ea30..abcb01e20 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs @@ -44,23 +44,19 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromVolume_Success() var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive).ToUpperInvariant(); - //var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(@"t:\"); - - // \\?\Volume{db5044f9-bd1f-4243-ab97-4b985eb29e80}\, - // \\?\Volume{43dd0652-8ecf-4943-8275-016fc09f02c7}\, - // \\?\Volume{e32f9cf5-7978-4aaa-9525-86cf401487ad}\, - // \\?\Volume{50685374-f895-11e7-a43e-f49634afb3a5}\ - var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceVolume); Console.WriteLine(); - Console.WriteLine("#{0:000}\tVolume: [{1}]", ++volumeCount, sourceVolume); + Console.WriteLine("#{0:000}\tInput Volume: [{1}]", ++volumeCount, sourceVolume); - UnitTestConstants.Dump(pDrive, -17); + UnitTestConstants.Dump(pDrive, -24); - UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -15, true); + UnitTestConstants.Dump(pDrive.StorageAdapterInfo, -28, true); + + UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -17, true); + Console.WriteLine(); Assert.IsNotNull(pDrive); diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index 09c97ad57..2a8f20103 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -41,11 +41,11 @@ public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { Console.WriteLine(); - Console.WriteLine("#{0:000}\tLogical Drive: [{1}]", ++driveCount, drive.Name); + Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]", ++driveCount, drive.Name); - var storageInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageDeviceInfo(drive.Name, true); + var storageInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageDeviceInfo(drive.Name); - UnitTestConstants.Dump(storageInfo, -15); + UnitTestConstants.Dump(storageInfo, -17); Assert.IsNotNull(storageInfo); diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 80563fa29..0d59fc0d5 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -201,6 +201,7 @@ + @@ -319,8 +320,8 @@ + - @@ -332,6 +333,9 @@ + + + @@ -688,7 +692,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Device.EnumerateDevices.cs index f6990021f..ead4d5a95 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -221,10 +221,7 @@ private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMet private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) { SetMinimalDeviceProperties(safeHandle, deviceInfo, infoData); - - - deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.BaseContainerId)); - + deviceInfo.CompatibleIds = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.CompatibleIds); deviceInfo.Driver = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Driver); @@ -236,11 +233,7 @@ private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo device 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.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.PhysicalDeviceObjectName); - + deviceInfo.Service = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Service); } @@ -248,6 +241,8 @@ private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo device [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.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class); deviceInfo.DeviceDescription = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceDescription); @@ -255,6 +250,10 @@ private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo //deviceInfo.DeviceType = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceType); deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); + + deviceInfo.Manufacturer = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Manufacturer); + + deviceInfo.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.PhysicalDeviceObjectName); } diff --git a/AlphaFS/Device/Device.InvokeDeviceIoData.cs b/AlphaFS/Device/Device.InvokeDeviceIoData.cs index 95d398130..e1ca99abe 100644 --- a/AlphaFS/Device/Device.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Device.InvokeDeviceIoData.cs @@ -52,6 +52,10 @@ private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle return safeBuffer; + if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_INVALID_PARAMETER) + return null; + + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs index abc071baa..ddb612a57 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs @@ -33,34 +33,36 @@ public static partial class Device [SecurityCritical] public static IEnumerable EnumeratePhysicalDrives() { - return EnumeratePhysicalDrives(Security.ProcessContext.IsElevatedProcess); + return EnumeratePhysicalDrivesCore(Security.ProcessContext.IsElevatedProcess); } + + /// [AlphaFS] Enumerates the physical drives on the Computer, populated with volume- and logical drive information. /// An collection that represents the physical drives on the Computer. [SecurityCritical] - internal static IEnumerable EnumeratePhysicalDrives(bool isElevated) + internal static IEnumerable EnumeratePhysicalDrivesCore(bool isElevated) { - var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(isElevated, null, null, deviceInfo, true)).Where(physicalDrive => null != physicalDrive).ToArray(); - - var pVolumes = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(isElevated, null, volumeGuid, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); + var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(isElevated, null, null, deviceInfo)).Where(physicalDrive => null != physicalDrive).ToArray(); - var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(isElevated, null, driveName, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); + var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(false, null, volumeGuid, null)).Where(physicalDrive => null != physicalDrive).ToArray(); + + var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(false, null, driveName, null)).Where(physicalDrive => null != physicalDrive).ToArray(); foreach (var pDrive in physicalDrives) - yield return PopulatePhysicalDrive(pDrive, pVolumes, pLogicalDrives); + yield return PopulatePhysicalDrive(pDrive, pVolumeGuids, pLogicalDrives); // Windows Disk Management shows CD-ROM so mimic that behaviour. - var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => GetPhysicalDriveInfoCore(isElevated, null, null, deviceInfo, true)).Where(physicalDrive => null != physicalDrive).ToArray(); + var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => GetPhysicalDriveInfoCore(isElevated, null, null, deviceInfo)).Where(physicalDrive => null != physicalDrive).ToArray(); foreach (var pCdRom in cdRoms) - yield return PopulatePhysicalCDRom(pCdRom, pVolumes, pLogicalDrives); + yield return PopulatePhysicalCDRom(pCdRom, pVolumeGuids, pLogicalDrives); } @@ -77,12 +79,12 @@ private static void PopulateLogicalDriveDetails(PhysicalDriveInfo pDriveInfo, Ph private static void PopulateVolumeDetails(PhysicalDriveInfo pDriveInfo, PhysicalDriveInfo pVolume) { - // Add device volume labels. + //// Add device volume labels. - if (null == pDriveInfo.VolumeLabels) - pDriveInfo.VolumeLabels = new Collection(); + //if (null == pDriveInfo.VolumeLabels) + // pDriveInfo.VolumeLabels = new Collection(); - pDriveInfo.VolumeLabels.Add(pVolume.Name); + //pDriveInfo.VolumeLabels.Add(pVolume.Name); // Add device partition index numbers. diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index bdad46ec6..a5d156d25 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -55,7 +55,7 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); - var storageInfo = GetStorageDeviceInfoCore(isElevated, devicePath, false); + var storageInfo = GetStorageDeviceInfoCore(isElevated, devicePath); if (null == storageInfo) return null; @@ -70,13 +70,13 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) var pDriveInfo = isDeviceInfo - ? EnumeratePhysicalDrives(isElevated).FirstOrDefault(pDrive => pDrive.StorageDeviceInfo.DeviceNumber == storageInfo.DeviceNumber && pDrive.StorageDeviceInfo.PartitionNumber == storageInfo.PartitionNumber) + ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => pDrive.StorageDeviceInfo.DeviceNumber == storageInfo.DeviceNumber && pDrive.StorageDeviceInfo.PartitionNumber == storageInfo.PartitionNumber) : isVolume - ? EnumeratePhysicalDrives(isElevated).FirstOrDefault(pDrive => null != pDrive.VolumeGuids && pDrive.VolumeGuids.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) + ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => null != pDrive.VolumeGuids && pDrive.VolumeGuids.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) : isDrive - ? EnumeratePhysicalDrives(isElevated).FirstOrDefault(pDrive => null != pDrive.LogicalDrives && pDrive.LogicalDrives.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) + ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => null != pDrive.LogicalDrives && pDrive.LogicalDrives.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) : null; @@ -88,8 +88,6 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) } - - /// [AlphaFS] Retrieves the physical drive information such as DeviceType, DeviceNumber, PartitionNumber and the serial number and Product ID. /// A instance that represents the physical drive on the Computer or null on error/no data available. /// @@ -104,11 +102,10 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// A string (when is set to ). /// /// A instance. - /// /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, StorageDeviceInfo storageInfo, string devicePath, DeviceInfo deviceInfo, bool? getAllData) + internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, StorageDeviceInfo storageInfo, string devicePath, DeviceInfo deviceInfo) { var isDeviceInfo = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); @@ -117,7 +114,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, Stor if (null == storageInfo) - storageInfo = GetStorageDeviceInfoCore(isElevated, devicePath, false); + storageInfo = GetStorageDeviceInfoCore(isElevated, devicePath); if (null == storageInfo) return null; @@ -125,17 +122,21 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, Stor var pDriveInfo = new PhysicalDriveInfo(storageInfo) { + DevicePath = devicePath, + DeviceDescription = isDeviceInfo ? deviceInfo.DeviceDescription : null, - DevicePath = devicePath, + Manufacturer = isDeviceInfo ? deviceInfo.Manufacturer : null, // "FriendlyName" usually contains a more complete name, as seen in Windows Explorer. Name = isDeviceInfo ? deviceInfo.FriendlyName : null, + + PhysicalDeviceObjectName = isDeviceInfo ? deviceInfo.PhysicalDeviceObjectName : null }; - if (null != getAllData && isElevated) - PopulatePhysicalDriveInfo((bool) getAllData, devicePath, pDriveInfo); + if (isElevated) + PopulatePhysicalDriveInfo(devicePath, pDriveInfo); return pDriveInfo; @@ -143,50 +144,64 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, Stor /// Sets the physical drive properties such as FriendlyName, device size and serial number. Requires elevation. - private static void PopulatePhysicalDriveInfo(bool getAllData, string devicePath, PhysicalDriveInfo physicalDriveInfo) + private static void PopulatePhysicalDriveInfo(string devicePath, PhysicalDriveInfo physicalDriveInfo) { using (var safeHandle = OpenPhysicalDrive(devicePath, FileSystemRights.Read | FileSystemRights.Write)) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { - PropertyId = 0, // StorageDeviceProperty, from STORAGE_PROPERTY_ID enum. - QueryType = 0 // PropertyStandardQuery, from STORAGE_QUERY_TYPE enum + PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, + QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery }; + // Get storage adapter info. + + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, devicePath, NativeMethods.DefaultFileBufferSize / 4)) + { + if (null != safeBuffer) + physicalDriveInfo.StorageAdapterInfo = new StorageAdapterInfo(safeBuffer.PtrToStructure(0)); + } + + + // Get storage device info. + + storagePropertyQuery.PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageDeviceProperty; + + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, devicePath, NativeMethods.DefaultFileBufferSize / 2)) { - var storageDescriptor = safeBuffer.PtrToStructure(0); + if (null != safeBuffer) + { + var deviceDescriptor = safeBuffer.PtrToStructure(0); - physicalDriveInfo.StorageDeviceInfo.BusType = (StorageBusType) storageDescriptor.BusType; + physicalDriveInfo.StorageDeviceInfo.BusType = (StorageBusType) deviceDescriptor.BusType; - if (!getAllData) - return; + physicalDriveInfo.StorageDeviceInfo.CommandQueueing = deviceDescriptor.CommandQueueing; + physicalDriveInfo.StorageDeviceInfo.ProductId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductIdOffset).Trim(); - physicalDriveInfo.CommandQueueing = storageDescriptor.CommandQueueing; + physicalDriveInfo.StorageDeviceInfo.ProductRevision = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductRevisionOffset).Trim(); - physicalDriveInfo.ProductRevision = safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductRevisionOffset).Trim(); + physicalDriveInfo.StorageDeviceInfo.RemovableMedia = deviceDescriptor.RemovableMedia; - physicalDriveInfo.RemovableMedia = storageDescriptor.RemovableMedia; + physicalDriveInfo.StorageDeviceInfo.SerialNumber = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(); - if (Utils.IsNullOrWhiteSpace(physicalDriveInfo.Name)) - physicalDriveInfo.Name = safeBuffer.PtrToStringAnsi((int) storageDescriptor.ProductIdOffset).Trim(); - - - // Get the device hardware serial number. + var vendorId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.VendorIdOffset).Trim(); - physicalDriveInfo.SerialNumber = safeBuffer.PtrToStringAnsi((int) storageDescriptor.SerialNumberOffset).Trim(); - } + if (Utils.IsNullOrWhiteSpace(vendorId) || vendorId.Length == 1) + vendorId = null; + physicalDriveInfo.StorageDeviceInfo.VendorId = vendorId; + } + } - // Get the device size. using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, devicePath)) - physicalDriveInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; + physicalDriveInfo.StorageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs index 68b6d7773..baeb62cff 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs @@ -39,25 +39,7 @@ public static partial class Device /// public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { - return GetStorageDeviceInfoCore(Security.ProcessContext.IsElevatedProcess, devicePath, false); - } - - - /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . - /// A instance that represent the storage device on the Computer that is related to . - /// - /// - /// - /// - /// - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string (when is set to ). - /// - /// When true also get the which requires elevated rights. - public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath, bool getBusType) - { - return GetStorageDeviceInfoCore(Security.ProcessContext.IsElevatedProcess, devicePath, getBusType); + return GetStorageDeviceInfoCore(Security.ProcessContext.IsElevatedProcess, devicePath); } @@ -73,8 +55,7 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath, bool get /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// A string (when is set to ). /// - /// When true also get the which requires elevated rights. - internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, string devicePath, bool getBusType) + internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, string devicePath) { string logicalDrive; @@ -84,15 +65,15 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri return null; + StorageDeviceInfo storageDeviceInfo = null; + + StartGetData: // No elevation needed. using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) { - StorageDeviceInfo storageInfo = null; - - var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); if (null == safeBuffer) @@ -115,23 +96,21 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri else { using (safeBuffer) - { - storageInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure(0)); - + storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure(0)); + } + } - if (getBusType) - { - var pDriveInfo = GetPhysicalDriveInfoCore(isElevated, storageInfo, pathToDevice, null, false); - if (null != pDriveInfo) - storageInfo.BusType = pDriveInfo.StorageDeviceInfo.BusType; - } - } - } + if (isElevated) + { + var pDriveInfo = GetPhysicalDriveInfoCore(true, storageDeviceInfo, pathToDevice, null); - - return storageInfo; + if (null != pDriveInfo) + storageDeviceInfo = pDriveInfo.StorageDeviceInfo; } + + + return storageDeviceInfo; } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs index 869be77dd..53490bd25 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs @@ -21,7 +21,6 @@ using System; using System.Collections.ObjectModel; -using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Security; @@ -46,14 +45,14 @@ private PhysicalDriveInfo() /// Initializes a PhysicalDriveInfo instance. - public PhysicalDriveInfo(StorageDeviceInfo storageInfo) + public PhysicalDriveInfo(StorageDeviceInfo storageInfo) : this() { StorageDeviceInfo = storageInfo; } /// Initializes a PhysicalDriveInfo instance. - public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) + public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) : this() { CopyTo(physicalDriveInfo, this); } @@ -65,7 +64,7 @@ public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) /// The device description. public string DeviceDescription { get; internal set; } - + /// The path to the device. /// A string that represents the path to the device. @@ -78,17 +77,12 @@ public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) /// The logical drives that are located on the physical drive. public Collection LogicalDrives { get; internal set; } - - - /// Indicates if the physical drive supports multiple outstanding commands (SCSI tagged queuing or equivalent). When false the physical drive does not support SCSI-tagged queuing or the equivalent. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Queueing")] - public bool CommandQueueing { get; internal set; } - - - /// Indicates if the physical drive is removable. When true the physical drive's media (if any) is removable. If the device has no media, this member should be ignored. When false the physical drive's media is not removable. - public bool RemovableMedia { get; internal set; } + + /// The Manufacturer of the physical drive. + public string Manufacturer { get; internal set; } + /// The "FriendlyName" of the physical drive. public string Name { get; internal set; } @@ -100,35 +94,25 @@ public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) ///// The partitions that are located on the physical drive. //public string[] Partitions { get; internal set; } - /// The product revision of the physical drive. - public string ProductRevision { get; internal set; } + /// Encapsulates the physical device location (PDO) information provided by a device's firmware to Windows. + public string PhysicalDeviceObjectName { get; internal set; } - /// The storage device type and device- and partition number. - public StorageDeviceInfo StorageDeviceInfo { get; internal set; } + /// The storage adapter information, such as bus type. + public StorageAdapterInfo StorageAdapterInfo { get; internal set; } - /// The serial number of the physical drive. If the physical drive has no serial number or the session is not elevated -1 is returned. - public string SerialNumber { get; internal set; } - - - /// The total size of the physical drive. If the session is not elevated -1 is returned - public long TotalSize { get; internal set; } - - - /// The total size of the physical drive, formatted as a unit size. - public string TotalSizeUnitSize - { - get { return Utils.UnitSizeToText(TotalSize); } - } + /// The storage device information, such as device type and number. + public StorageDeviceInfo StorageDeviceInfo { get; internal set; } + /// A collection of volume GUID strings of volumes that are located on the physical drive. public Collection VolumeGuids { get; internal set; } - /// A collection of volume label strings of volumes that are located on the physical drive. - public Collection VolumeLabels { get; internal set; } + ///// A collection of volume label strings of volumes that are located on the physical drive. + //public Collection VolumeLabels { get; internal set; } #endregion // Properties diff --git a/AlphaFS/Device/StorageAdapterInfo.cs b/AlphaFS/Device/StorageAdapterInfo.cs new file mode 100644 index 000000000..d2df63b48 --- /dev/null +++ b/AlphaFS/Device/StorageAdapterInfo.cs @@ -0,0 +1,164 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace Alphaleonis.Win32.Filesystem +{ + /// Provides access to information of a device, on a local or remote host. + [Serializable] + [SecurityCritical] + public sealed class StorageAdapterInfo + { + #region Constructors + + /// Initializes a StorageAdapterInfo instance. + public StorageAdapterInfo() + { + BusType = StorageBusType.Unknown; + } + + + internal StorageAdapterInfo(NativeMethods.STORAGE_ADAPTER_DESCRIPTOR adapter) : this() + { + BusType = (StorageBusType) adapter.BusType; + + AcceleratedTransfer = adapter.AcceleratedTransfer; + + AdapterScansDown = adapter.AdapterScansDown; + + AdapterUsesPio = adapter.AdapterUsesPio; + + BusVersion = adapter.BusVersion; + + CommandQueueing = adapter.CommandQueueing; + + MaximumTransferBytes = (int) adapter.MaximumTransferLength; + } + + #endregion // Constructors + + + #region Properties + + /// When , the storage adapter supports synchronous transfers as a way of speeding up I/O. + public bool AcceleratedTransfer { get; internal set; } + + + /// When , the storage adapter scans down for BIOS devices, that is, the storage adapter begins scanning with the highest device number rather than the lowest. + public bool AdapterScansDown { get; internal set; } + + + /// When , the storage adapter uses programmed I/O (PIO). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pio")] + public bool AdapterUsesPio { get; internal set; } + + + /// The bus type of the storage adapter. + public StorageBusType BusType { get; internal set; } + + + /// The version number, if any, of the storage adapter. + public Version BusVersion { get; internal set; } + + + /// When , the storage adapter supports SCSI tagged queuing and/or per-logical-unit internal queues, or the non-SCSI equivalent. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Queueing")] + public bool CommandQueueing { get; internal set; } + + + /// Specifies the maximum number of bytes the storage adapter can transfer in a single operation. + public int MaximumTransferBytes { get; internal set; } + + + /// Specifies the maximum number of bytes the storage adapter can transfer in a single operation, formatted as a unit size. + public string MaximumTransferBytesUnitSize + { + get { return Utils.UnitSizeToText(MaximumTransferBytes); } + } + + #endregion // Properties + + + #region Methods + + /// Returns storage device as: "BusType MaximumTransferBytesUnitSize". + /// A string that represents this instance. + public override string ToString() + { + return string.Format(CultureInfo.CurrentCulture, "{0} {1}", BusType.ToString(), MaximumTransferBytesUnitSize); + } + + + /// Determines whether the specified Object is equal to the current Object. + /// Another object to compare to. + /// if the specified Object is equal to the current Object; otherwise, . + public override bool Equals(object obj) + { + if (null == obj || GetType() != obj.GetType()) + return false; + + var other = obj as StorageAdapterInfo; + + return null != other && + other.AcceleratedTransfer == AcceleratedTransfer && + other.AdapterScansDown == AdapterScansDown && + other.AdapterUsesPio == AdapterUsesPio && + other.CommandQueueing == CommandQueueing && + other.MaximumTransferBytes == MaximumTransferBytes && + other.BusVersion == BusVersion && + other.BusType == BusType; + } + + + /// Serves as a hash function for a particular type. + /// A hash code for the current Object. + public override int GetHashCode() + { + return MaximumTransferBytes + AcceleratedTransfer.GetHashCode() + BusVersion.GetHashCode() + BusType.GetHashCode(); + } + + + /// Implements the operator == + /// A. + /// B. + /// The result of the operator. + public static bool operator ==(StorageAdapterInfo left, StorageAdapterInfo right) + { + return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); + } + + + /// Implements the operator != + /// A. + /// B. + /// The result of the operator. + public static bool operator !=(StorageAdapterInfo left, StorageAdapterInfo right) + { + return !(left == right); + } + + #endregion // Methods + } +} diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs index f876fc6e7..0dc404f52 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -20,6 +20,7 @@ */ using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; @@ -35,7 +36,6 @@ public sealed class StorageDeviceInfo /// Initializes a StorageDeviceInfo instance. public StorageDeviceInfo() { - BusType = StorageBusType.Unknown; DeviceType = StorageDeviceType.Unknown; } @@ -43,20 +43,78 @@ public StorageDeviceInfo() internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() { DeviceType = device.DeviceType; + DeviceNumber = device.DeviceNumber; + PartitionNumber = device.PartitionNumber; } #endregion // Constructors + #region Properties + + /// The type of the bus to which the device is connected. + public StorageBusType BusType { get; internal set; } + + + /// Indicates if the physical drive supports multiple outstanding commands (SCSI tagged queuing or equivalent). When false the physical drive does not support SCSI-tagged queuing or the equivalent. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Queueing")] + public bool CommandQueueing { get; internal set; } + + + /// The storage device type. + public StorageDeviceType DeviceType { get; internal set; } + + + /// The device number of the storage device, starting at 0. + public int DeviceNumber { get; internal set; } + + + /// The partition number of the storage device, starting at 1. If the device cannot be partitioned, like a CDROM, -1 is returned. + public int PartitionNumber { get; internal set; } + + + /// The product ID of the physical drive. + public string ProductId { get; internal set; } + + + /// The product revision of the physical drive. + public string ProductRevision { get; internal set; } + + + /// Indicates if the physical drive is removable. When true the physical drive's media (if any) is removable. If the device has no media, this member should be ignored. When false the physical drive's media is not removable. + public bool RemovableMedia { get; internal set; } + + + /// The serial number of the physical drive. If the physical drive has no serial number or the session is not elevated -1 is returned. + public string SerialNumber { get; internal set; } + + + /// The total size of the physical drive. If the session is not elevated -1 is returned + public long TotalSize { get; internal set; } + + + /// The total size of the physical drive, formatted as a unit size. + public string TotalSizeUnitSize + { + get { return Utils.UnitSizeToText(TotalSize); } + } + + + /// The Vendor ID of the physical drive. + public string VendorId { get; internal set; } + + #endregion // Properties + + #region Methods - /// Returns storage device as: "DeviceNumber:PartitionNumber DeviceType/BusType". + /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". /// A string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "{0}:{1} {2}/{3}", DeviceNumber, PartitionNumber, DeviceType.ToString(), BusType.ToString()); + return string.Format(CultureInfo.CurrentCulture, "{0} {1} {2} {3}:{4}", VendorId, ProductId, DeviceType.ToString(), DeviceNumber, PartitionNumber).Trim(); } @@ -70,7 +128,12 @@ public override bool Equals(object obj) var other = obj as StorageDeviceInfo; - return null != other && other.DeviceType == DeviceType && other.DeviceNumber == DeviceNumber && other.PartitionNumber == PartitionNumber; + return null != other && + other.DeviceNumber == DeviceNumber && + other.PartitionNumber == PartitionNumber && + other.DeviceType == DeviceType && + other.BusType == BusType && + other.SerialNumber == SerialNumber; } @@ -78,7 +141,7 @@ public override bool Equals(object obj) /// A hash code for the current Object. public override int GetHashCode() { - return DeviceNumber + PartitionNumber + DeviceType.GetHashCode(); + return DeviceNumber + PartitionNumber + (null != SerialNumber ? SerialNumber.GetHashCode() : 0) + BusType.GetHashCode() + DeviceType.GetHashCode(); } @@ -100,27 +163,7 @@ public override int GetHashCode() { return !(left == right); } - - #endregion // Methods - - #region Properties - - /// The storage bus type. Requires elevated rights. - public StorageBusType BusType { get; internal set; } - - - /// The storage device type. - public StorageDeviceType DeviceType { get; internal set; } - - - /// The device number of the storage device, starting at 0. - public int DeviceNumber { get; internal set; } - - - /// The partition number of the storage device, starting at 1. If the device cannot be partitioned, like a CDROM, -1 is returned. - public int PartitionNumber { get; internal set; } - - #endregion // Properties + #endregion // Methods } } diff --git a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs index b6707eef1..b4195805b 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs @@ -37,7 +37,7 @@ internal struct DISK_GEOMETRY [MarshalAs(UnmanagedType.U8)] public long Cylinders; /// The type of media. - [MarshalAs(UnmanagedType.U4)] public MEDIA_TYPE MediaType; + [MarshalAs(UnmanagedType.U4)] public STORAGE_MEDIA_TYPE MediaType; /// The number of tracks per cylinder. [MarshalAs(UnmanagedType.U4)] public uint TracksPerCylinder; diff --git a/AlphaFS/Filesystem/Native Other/MEDIA_TYPE.cs b/AlphaFS/Filesystem/Native Other/MEDIA_TYPE.cs deleted file mode 100644 index 173f68a1d..000000000 --- a/AlphaFS/Filesystem/Native Other/MEDIA_TYPE.cs +++ /dev/null @@ -1,112 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 - { - /// Represents the various forms of device media. - /// - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// - internal enum MEDIA_TYPE - { - /// Format is unknown. - Unknown = 0, - - /// A 5.25" floppy, with 1.2MB and 512 bytes/sector. - F5_1Pt2_512 = 1, - - /// A 3.5" floppy, with 1.44MB and 512 bytes/sector. - F3_1Pt44_512 = 2, - - /// A 3.5" floppy, with 2.88MB and 512 bytes/sector. - F3_2Pt88_512 = 3, - - /// A 3.5" floppy, with 20.8MB and 512 bytes/sector. - F3_20Pt8_512 = 4, - - /// A 3.5" floppy, with 720KB and 512 bytes/sector. - F3_720_512 = 5, - - /// A 5.25" floppy, with 360KB and 512 bytes/sector. - F5_360_512 = 6, - - /// A 5.25" floppy, with 320KB and 512 bytes/sector. - F5_320_512 = 7, - - /// A 5.25" floppy, with 320KB and 1024 bytes/sector. - F5_320_1024 = 8, - - /// A 5.25" floppy, with 180KB and 512 bytes/sector. - F5_180_512 = 9, - - /// A 5.25" floppy, with 160KB and 512 bytes/sector. - F5_160_512 = 10, - - /// Removable media other than floppy. - RemovableMedia = 11, - - /// Fixed hard disk media. - FixedMedia = 12, - - /// A 3.5" floppy, with 120MB and 512 bytes/sector. - F3_120M_512 = 13, - - /// A 3.5" floppy, with 640KB and 512 bytes/sector. - F3_640_512 = 14, - - /// A 5.25" floppy, with 640KB and 512 bytes/sector. - F5_640_512 = 15, - - /// A 5.25" floppy, with 720KB and 512 bytes/sector. - F5_720_512 = 16, - - /// A 3.5" floppy, with 1.2MB and 512 bytes/sector. - F3_1Pt2_512 = 17, - - /// A 3.5" floppy, with 1.23MB and 1024 bytes/sector. - F3_1Pt23_1024 = 18, - - /// A 5.25" floppy, with 1.23MB and 1024 bytes/sector. - F5_1Pt23_1024 = 19, - - /// A 3.5" floppy, with 128MB and 512 bytes/sector. - F3_128Mb_512 = 20, - - /// A 3.5" floppy, with 230MB and 512 bytes/sector. - F3_230Mb_512 = 21, - - /// An 8" floppy, with 256KB and 128 bytes/sector. - F8_256_128 = 22, - - /// A 3.5" floppy, with 200MB and 512 bytes/sector. (HiFD). - F3_200Mb_512 = 23, - - /// A 3.5" floppy, with 240MB and 512 bytes/sector. (HiFD). - F3_240M_512 = 24, - - /// A 3.5" floppy, with 32MB and 512 bytes/sector. - F3_32M_512 = 25 - } - } -} diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs b/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs new file mode 100644 index 000000000..c15ee2072 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs @@ -0,0 +1,105 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace Alphaleonis.Win32.Filesystem +{ + internal static partial class NativeMethods + { + /// Used with the control code to retrieve the storage adapter descriptor data for a device. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct STORAGE_ADAPTER_DESCRIPTOR + { + /// Contains the size of this structure, in bytes. The value of this member will change as members are added to the structure. + [MarshalAs(UnmanagedType.U4)] public readonly uint Version; + + /// Specifies the total size of the data returned, in bytes. This may include data that follows this structure. + [MarshalAs(UnmanagedType.U4)] public readonly uint Size; + + /// Specifies the maximum number of bytes the storage adapter can transfer in a single operation. + [MarshalAs(UnmanagedType.U4)] public readonly uint MaximumTransferLength; + + /// Specifies the maximum number of discontinuous physical pages the storage adapter can manage in a single transfer (in other words, the extent of its scatter/gather support). + [MarshalAs(UnmanagedType.U4)] public readonly uint MaximumPhysicalPages; + + /// Specifies the storage adapter's alignment requirements for transfers. + /// The alignment mask indicates alignment restrictions for buffers required by the storage adapter for transfer operations. Valid mask values are also restricted by characteristics of the memory managers on different versions of Windows. + /// + /// 0 - Buffers must be aligned on BYTE boundaries. + /// 1 - Buffers must be aligned on WORD boundaries. + /// 3 - Buffers must be aligned on DWORD32 boundaries. + /// 7 - Buffers must be aligned on DWORD64 boundaries. + /// + [MarshalAs(UnmanagedType.U4)] public readonly uint AlignmentMask; + + /// If this member is TRUE, the storage adapter uses programmed I/O (PIO) and requires the use of system-space virtual addresses mapped to physical memory for data buffers. When this member is FALSE, the storage adapter does not use PIO. + [MarshalAs(UnmanagedType.U1)] public readonly bool AdapterUsesPio; + + /// If this member is TRUE, the storage adapter scans down for BIOS devices, that is, the storage adapter begins scanning with the highest device number rather than the lowest. When this member is FALSE, the storage adapter begins scanning with the lowest device number. + /// This member is reserved for legacy miniport drivers. + [MarshalAs(UnmanagedType.U1)] public readonly bool AdapterScansDown; + + /// If this member is TRUE, the storage adapter supports SCSI tagged queuing and/or per-logical-unit internal queues, or the non-SCSI equivalent. When this member is FALSE, the storage adapter neither supports SCSI-tagged queuing nor per-logical-unit internal queues. + [MarshalAs(UnmanagedType.U1)] public readonly bool CommandQueueing; + + /// If this member is TRUE, the storage adapter supports synchronous transfers as a way of speeding up I/O. When this member is FALSE, the storage adapter does not support synchronous transfers as a way of speeding up I/O. + [MarshalAs(UnmanagedType.U1)] public readonly bool AcceleratedTransfer; + + /// Specifies a value of type STORAGE_BUS_TYPE that indicates the type of the bus to which the device is connected. + [MarshalAs(UnmanagedType.U1)] private readonly byte busType; + + /// Specifies the major version number, if any, of the storage adapter. + [MarshalAs(UnmanagedType.U2)] public readonly ushort BusMajorVersion; + + /// Specifies the minor version number, if any, of the storage adapter. + [MarshalAs(UnmanagedType.U2)] public readonly ushort BusMinorVersion; + + /// Specifies the SCSI request block (SRB) type used by the HBA. + /// SRB_TYPE_SCSI_REQUEST_BLOCK: The HBA uses SCSI request blocks. + /// SRB_TYPE_STORAGE_REQUEST_BLOCK: The HBA uses extended SCSI request blocks. + /// + [MarshalAs(UnmanagedType.U1)] private readonly byte SrbType; + + /// Specifies the address type of the HBA. + /// STORAGE_ADDRESS_TYPE_BTL8: The HBA uses 8-bit bus, target, and LUN addressing. + /// + [MarshalAs(UnmanagedType.U1)] private readonly byte AddressType; + + /// Specifies the version number, if any, of the storage adapter. + public Version BusVersion + { + get { return new Version(BusMajorVersion, BusMinorVersion); } + } + + /// Specifies a value of type STORAGE_BUS_TYPE that indicates the type of the bus to which the device is connected. + public STORAGE_BUS_TYPE BusType + { + get { return (STORAGE_BUS_TYPE) busType; } + } + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs index 603609d25..c98d67a69 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs @@ -24,6 +24,10 @@ namespace Alphaleonis.Win32.Filesystem internal static partial class NativeMethods { /// Provides a symbolic means of representing storage bus types. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// internal enum STORAGE_BUS_TYPE { /// Indicates an unknown bus type. diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs index a6811087c..1be023720 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs @@ -30,16 +30,16 @@ internal static partial class NativeMethods internal struct STORAGE_DEVICE_DESCRIPTOR { /// Contains the size of this structure, in bytes. The value of this member will change as members are added to the structure. - public readonly uint Version; + [MarshalAs(UnmanagedType.U4)] public readonly uint Version; /// Specifies the total size of the descriptor, in bytes, which may include vendor ID, product ID, product revision, device serial number strings and bus-specific data which are appended to the structure. - public readonly uint Size; + [MarshalAs(UnmanagedType.U4)] public readonly uint Size; /// Specifies the device type as defined by the Small Computer Systems Interface (SCSI) specification. - public readonly byte DeviceType; + [MarshalAs(UnmanagedType.I1)] public readonly byte DeviceType; /// Specifies the device type modifier, if any, as defined by the SCSI specification. If no device type modifier exists, this member is zero. - public readonly byte DeviceTypeModifier; + [MarshalAs(UnmanagedType.I1)] public readonly byte DeviceTypeModifier; /// Indicates when TRUE that the device's media (if any) is removable. If the device has no media, this member should be ignored. When FALSE the device's media is not removable. [MarshalAs(UnmanagedType.I1)] public readonly bool RemovableMedia; @@ -48,22 +48,22 @@ internal struct STORAGE_DEVICE_DESCRIPTOR [MarshalAs(UnmanagedType.I1)] public readonly bool CommandQueueing; /// Specifies the byte offset from the beginning of the structure to a null-terminated ASCII string that contains the device's vendor ID. If the device has no vendor ID, this member is zero. - public readonly uint VendorIdOffset; + [MarshalAs(UnmanagedType.U4)] public readonly uint VendorIdOffset; /// Specifies the byte offset from the beginning of the structure to a null-terminated ASCII string that contains the device's product ID. If the device has no product ID, this member is zero. - public readonly uint ProductIdOffset; + [MarshalAs(UnmanagedType.U4)] public readonly uint ProductIdOffset; /// Specifies the byte offset from the beginning of the structure to a null-terminated ASCII string that contains the device's product revision string. If the device has no product revision string, this member is zero. - public readonly uint ProductRevisionOffset; + [MarshalAs(UnmanagedType.U4)] public readonly uint ProductRevisionOffset; /// Specifies the byte offset from the beginning of the structure to a null-terminated ASCII string that contains the device's serial number. If the device has no serial number, this member is zero. - public readonly uint SerialNumberOffset; + [MarshalAs(UnmanagedType.U4)] public readonly uint SerialNumberOffset; /// Specifies an enumerator value of type STORAGE_BUS_TYPE that indicates the type of bus to which the device is connected. This should be used to interpret the raw device properties at the end of this structure (if any). - public readonly STORAGE_BUS_TYPE BusType; + [MarshalAs(UnmanagedType.U4)] public readonly STORAGE_BUS_TYPE BusType; /// Indicates the number of bytes of bus-specific data that have been appended to this descriptor. - public readonly uint RawPropertiesLength; + [MarshalAs(UnmanagedType.U4)] public readonly uint RawPropertiesLength; /// Contains an array of length one that serves as a place holder for the first byte of the bus specific property data. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 22)] public readonly byte[] RawDeviceProperties; diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs new file mode 100644 index 000000000..c362aeec5 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs @@ -0,0 +1,303 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Specifies various types of storage media. Parameters and members of type STORAGE_MEDIA_TYPE also accept values from the MEDIA_TYPE enumeration type. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + public enum STORAGE_MEDIA_TYPE + { + /// Format is unknown. + Unknown = 0, + + /// A 5.25" floppy, with 1.2MB and 512 bytes/sector. + F5_1Pt2_512 = 1, + + /// A 3.5" floppy, with 1.44MB and 512 bytes/sector. + F3_1Pt44_512 = 2, + + /// A 3.5" floppy, with 2.88MB and 512 bytes/sector. + F3_2Pt88_512 = 3, + + /// A 3.5" floppy, with 20.8MB and 512 bytes/sector. + F3_20Pt8_512 = 4, + + /// A 3.5" floppy, with 720KB and 512 bytes/sector. + F3_720_512 = 5, + + /// A 5.25" floppy, with 360KB and 512 bytes/sector. + F5_360_512 = 6, + + /// A 5.25" floppy, with 320KB and 512 bytes/sector. + F5_320_512 = 7, + + /// A 5.25" floppy, with 320KB and 1024 bytes/sector. + F5_320_1024 = 8, + + /// A 5.25" floppy, with 180KB and 512 bytes/sector. + F5_180_512 = 9, + + /// A 5.25" floppy, with 160KB and 512 bytes/sector. + F5_160_512 = 10, + + /// Removable media other than floppy. + RemovableMedia = 11, + + /// Fixed hard disk media. + FixedMedia = 12, + + /// A 3.5" floppy, with 120MB and 512 bytes/sector. + F3_120M_512 = 13, + + /// A 3.5" floppy, with 640KB and 512 bytes/sector. + F3_640_512 = 14, + + /// A 5.25" floppy, with 640KB and 512 bytes/sector. + F5_640_512 = 15, + + /// A 5.25" floppy, with 720KB and 512 bytes/sector. + F5_720_512 = 16, + + /// A 3.5" floppy, with 1.2MB and 512 bytes/sector. + F3_1Pt2_512 = 17, + + /// A 3.5" floppy, with 1.23MB and 1024 bytes/sector. + F3_1Pt23_1024 = 18, + + /// A 5.25" floppy, with 1.23MB and 1024 bytes/sector. + F5_1Pt23_1024 = 19, + + /// A 3.5" floppy, with 128MB and 512 bytes/sector. + F3_128Mb_512 = 20, + + /// A 3.5" floppy, with 230MB and 512 bytes/sector. + F3_230Mb_512 = 21, + + /// An 8" floppy, with 256KB and 128 bytes/sector. + F8_256_128 = 22, + + /// A 3.5" floppy, with 200MB and 512 bytes/sector. (HiFD). + F3_200Mb_512 = 23, + + /// A 3.5" floppy, with 240MB and 512 bytes/sector. (HiFD). + F3_240M_512 = 24, + + /// A 3.5" floppy, with 32MB and 512 bytes/sector. + F3_32M_512 = 25, + + /// One of the following tape types: DAT, DDS1, DDS2, and so on. + DDS_4mm = 32, + + /// MiniQIC tape. + MiniQic = 33, + + /// Travan tape (TR-1, TR-2, TR-3, and so on). + Travan = 34, + + /// QIC tape. + QIC = 35, + + /// An 8mm Exabyte metal particle tape. + MP_8mm = 36, + + /// An 8mm Exabyte advanced metal evaporative tape. + AME_8mm = 37, + + /// An 8mm Sony AIT1 tape. + AIT1_8mm = 38, + + /// DLT compact tape (IIIxt or IV). + DLT = 39, + + /// Philips NCTP tape. + NCTP = 40, + + /// IBM 3480 tape. + IBM_3480 = 41, + + /// IBM 3490E tape. + IBM_3490E = 42, + + /// IBM Magstar 3590 tape. + IBM_Magstar_3590 = 43, + + /// IBM Magstar MP tape. + IBM_Magstar_MP = 44, + + /// STK data D3 tape. + STK_DATA_D3 = 45, + + /// Sony DTF tape. + SONY_DTF = 46, + + /// A 6mm digital videotape. + DV_6mm = 47, + + /// Exabyte DMI tape (or compatible). + DMI = 48, + + /// Sony D2S or D2L tape. + SONY_D2 = 49, + + /// Cleaner (all drive types that support cleaners). + CLEANER_CARTRIDGE = 50, + + /// CD. + CD_ROM = 51, + + /// CD (write once). + CD_R = 52, + + /// CD (rewriteable). + CD_RW = 53, + + /// DVD. + DVD_ROM = 54, + + /// DVD (write once). + DVD_R = 55, + + /// DVD (rewriteable). + DVD_RW = 56, + + /// Magneto-optical 3.5" (rewriteable). + MO_3_RW = 57, + + /// Magneto-optical 5.25" (write once). + MO_5_WO = 58, + + /// Magneto-optical 5.25" (rewriteable; not LIMDOW). + MO_5_RW = 59, + + /// Magneto-optical 5.25" (rewriteable; LIMDOW). + MO_5_LIMDOW = 60, + + /// Phase change 5.25" (write once). + PC_5_WO = 61, + + /// Phase change 5.25" (rewriteable). + PC_5_RW = 62, + + /// Phase change dual (rewriteable). + PD_5_RW = 63, + + /// Ablative 5.25" (write once). + ABL_5_WO = 64, + + /// Pinnacle Apex 4.6GB (rewriteable) + PINNACLE_APEX_5_RW = 65, + + /// Sony 12" (write once). + SONY_12_WO = 66, + + /// Philips/LMS 12" (write once). + PHILIPS_12_WO = 67, + + /// Hitachi 12" (write once). + HITACHI_12_WO = 68, + + /// Cygnet/ATG 12" (write once). + CYGNET_12_WO = 69, + + /// Kodak 14" (write once). + KODAK_14_WO = 70, + + /// MO near field recording (Terastor). + MO_NFR_525 = 71, + + /// Nikon 12" (rewriteable). + NIKON_12_RW = 72, + + /// Iomega Zip. + IOMEGA_ZIP = 73, + + /// Iomega Jaz. + IOMEGA_JAZ = 74, + + /// Syquest EZ135. + SYQUEST_EZ135 = 75, + + /// Syquest EzFlyer. + SYQUEST_EZFLYER = 76, + + /// Syquest SyJet. + SYQUEST_SYJET = 77, + + /// Avatar 2.5" floppy. + AVATAR_F2 = 78, + + /// An 8mm Hitachi tape. + MP2_8mm = 79, + + /// Ampex DST small tape. + DST_S = 80, + + /// Ampex DST medium tape. + DST_M = 81, + + /// Ampex DST large tape. + DST_L = 82, + + /// Ecrix 8mm tape. + VXATape_1 = 83, + + /// Ecrix 8mm tape. + VXATape_2 = 84, + + /// STK 9840. + STK_9840 = 85, + + /// LTO Ultrium (IBM, HP, Seagate). + LTO_Ultrium = 86, + + /// LTO Accelis (IBM, HP, Seagate). + LTO_Accelis = 87, + + /// DVD-RAM. + DVD_RAM = 88, + + /// AIT tape (AIT2 or higher). + AIT_8mm = 89, + + /// OnStream ADR1. + ADR_1 = 90, + + /// OnStream ADR2. + ADR_2 = 91, + + /// STK 9940. + STK_9940 = 92, + + /// SAIT tape. + /// Windows Server 2003: This is not supported before Windows Server 2003 with SP1. + SAIT = 93, + + /// Exabyte VXA tape. + /// Windows Server 2008: This is not supported before Windows Server 2008. + VXATape = 94 + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs new file mode 100644 index 000000000..4f3bee286 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs @@ -0,0 +1,109 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Enumerates the possible values of the PropertyId member of the structure passed as input to the IOCTL_STORAGE_QUERY_PROPERTY request to retrieve the properties of a storage device or adapter. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + public enum STORAGE_PROPERTY_ID + { + /// Indicates that the caller is querying for the device descriptor, . + StorageDeviceProperty = 0, + + /// Indicates that the caller is querying for the adapter descriptor, . + StorageAdapterProperty, + + ///// Indicates that the caller is querying for the device identifiers provided with the SCSI vital product data pages. Data is returned using the structure. + //StorageDeviceIdProperty, + + ///// Indicates that the caller is querying for the unique device identifiers. Data is returned using the STORAGE_DEVICE_UNIQUE_IDENTIFIER structure. + //StorageDeviceUniqueIdProperty, + + ///// Indicates that the caller is querying for the write cache property. Data is returned using the STORAGE_WRITE_CACHE_PROPERTY structure. + //StorageDeviceWriteCacheProperty, + + ///// Reserved for system use. + //StorageMiniportProperty, + + ///// Indicates that the caller is querying for the access alignment descriptor, STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR. + //StorageAccessAlignmentProperty, + + ///// Indicates that the caller is querying for the seek penalty descriptor, DEVICE_SEEK_PENALTY_DESCRIPTOR. + //StorageDeviceSeekPenaltyProperty, + + ///// Indicates that the caller is querying for the trim descriptor, DEVICE_TRIM_DESCRIPTOR. + //StorageDeviceTrimProperty, + + ///// Reserved for system use. + //StorageDeviceWriteAggregationProperty, + + ///// Reserved for system use. + //StorageDeviceDeviceTelemetryProperty, + + ///// Indicates that the caller is querying for the logical block provisioning property. Data is returned using the DEVICE_LB_PROVISIONING_DESCRIPTOR structure. + //StorageDeviceLBProvisioningProperty, + + ///// Indicates that the caller is querying for the device power descriptor. Data is returned using the DEVICE_POWER_DESCRIPTOR structure. + //StorageDevicePowerProperty, + + ///// Indicates that the caller is querying for the copy offload parameters property. Data is returned using the DEVICE_COPY_OFFLOAD_DESCRIPTOR structure. + //StorageDeviceCopyOffloadProperty, + + ///// Reserved for system use. + //StorageDeviceResiliencyProperty, + + ///// Indicates that the caller is querying for the medium product type. Data is returned using the STORAGE_MEDIUM_PRODUCT_TYPE_DESCRIPTOR structure. + //StorageDeviceMediumProductType, + + ///// Reserved for system use. + //StorageAdapterCryptoProperty, + + ///// Indicates that the caller is querying for the device I/O capability property. Data is returned using the DEVICE_IO_CAPABILITY_DESCRIPTOR structure. + //StorageDeviceIoCapabilityProperty = 48, + + ///// Indicates that the caller is querying for protocol-specific data from the adapter. Data is returned using the STORAGE_PROTOCOL_DATA_DESCRIPTOR structure. See the remarks for more info. + //StorageAdapterProtocolSpecificProperty, + + ///// Indicates that the caller is querying for protocol-specific data from the device. Data is returned using the STORAGE_PROTOCOL_DATA_DESCRIPTOR structure. See the remarks for more info. + //StorageDeviceProtocolSpecificProperty, + + ///// Indicates that the caller is querying temperature data from the adapter. Data is returned using the STORAGE_TEMPERATURE_DATA_DESCRIPTOR structure. + //StorageAdapterTemperatureProperty, + + ///// Indicates that the caller is querying for temperature data from the device. Data is returned using the STORAGE_TEMPERATURE_DATA_DESCRIPTOR structure. + //StorageDeviceTemperatureProperty, + + ///// Indicates that the caller is querying for topology information from the adapter. Data is returned using the STORAGE_PHYSICAL_TOPOLOGY_DESCRIPTOR structure. + //StorageAdapterPhysicalTopologyProperty, + + ///// Indicates that the caller is querying for topology information from the device. Data is returned using the STORAGE_PHYSICAL_TOPOLOGY_DESCRIPTOR structure. + //StorageDevicePhysicalTopologyProperty, + + ///// Indicates that the caller is querying for attributes information from the device. Data is returned using the STORAGE_DEVICE_ATTRIBUTES_DESCRIPTOR structure. + //StorageDeviceAttributesProperty + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs index cadf7799d..27aa7692d 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs @@ -32,13 +32,13 @@ public struct STORAGE_PROPERTY_QUERY /// Indicates whether the caller is requesting a device descriptor, an adapter descriptor, a write cache property, a device unique ID (DUID), /// or the device identifiers provided in the device's SCSI vital product data (VPD) page. For a list of the property IDs that can be assigned to this member, see STORAGE_PROPERTY_ID. /// - public uint PropertyId; + [MarshalAs(UnmanagedType.U4)] public STORAGE_PROPERTY_ID PropertyId; /// Contains flags indicating the type of query to be performed as enumerated by the STORAGE_QUERY_TYPE enumeration. /// PropertyStandardQuery = 0: Instructs the port driver to report a device descriptor, an adapter descriptor or a unique hardware device ID(DUID). /// PropertyExistsQuery = 1: Instructs the port driver to report whether the descriptor is supported. /// - public uint QueryType; + [MarshalAs(UnmanagedType.U4)] public STORAGE_QUERY_TYPE QueryType; /// Contains an array of bytes that can be used to retrieve additional parameters for specific queries. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs new file mode 100644 index 000000000..d027feed6 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs @@ -0,0 +1,46 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// Used by the structure passed to the IOCTL_STORAGE_QUERY_PROPERTY control code to indicate what information is returned about a property of a storage device or adapter. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + public enum STORAGE_QUERY_TYPE + { + /// Instructs the driver to return an appropriate descriptor. + PropertyStandardQuery = 0, + + ///// Instructs the driver to report whether the descriptor is supported. + //PropertyExistsQuery = 1, + + ///// Not currently supported. Do not use. + //PropertyMaskQuery = 2, + + ///// Specifies the upper limit of the list of query types. This is used to validate the query type. + //PropertyQueryMaxDefined = 3 + } + } +} diff --git a/AlphaFS/Safe Handles/SafeTokenHandle.cs b/AlphaFS/Safe Handles/SafeTokenHandle.cs index 0272d34a3..51f4be74d 100644 --- a/AlphaFS/Safe Handles/SafeTokenHandle.cs +++ b/AlphaFS/Safe Handles/SafeTokenHandle.cs @@ -26,6 +26,7 @@ namespace Alphaleonis.Win32 { + /// Represents a wrapper class for a handle used by the Token Win32 API functions. [SecurityCritical] public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid { diff --git a/AlphaFS/Security/ProcessContext.cs b/AlphaFS/Security/ProcessContext.cs index 16ea084b7..aca8c54cb 100644 --- a/AlphaFS/Security/ProcessContext.cs +++ b/AlphaFS/Security/ProcessContext.cs @@ -116,6 +116,8 @@ private static WindowsPrincipal GetWindowsPrincipal(out WindowsIdentity windowsI /// [AlphaFS] Retrieves the elevation type of the current process. /// A value. + [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "OpenProcessToken")] + [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "GetTokenInformation")] private static NativeMethods.TOKEN_ELEVATION_TYPE GetProcessElevationType() { SafeTokenHandle tokenHandle; From 563736cc6bbe7313a458155c7f7f258787768341 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 19 Feb 2018 11:00:00 +0100 Subject: [PATCH 051/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumerateDevices.cs | 2 +- AlphaFS/AlphaFS.csproj | 3 +- AlphaFS/Device/Device.EnumerateDevices.cs | 154 +++++++---- AlphaFS/Device/DeviceInfo.cs | 34 +-- .../Device.EnumeratePhysicalDrives.cs | 4 +- .../Device.GetPhysicalDriveInfo.cs | 28 +- .../Device.GetStorageDeviceInfo.cs | 2 +- .../PhysicalDriveInfo/PhysicalDriveInfo.cs | 4 - AlphaFS/Device/StorageAdapterInfo.cs | 7 +- .../Native Methods/NativeMethods.Constants.cs | 2 +- .../NativeMethods.DeviceManagement.cs | 68 ++++- AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs | 250 ++++++++++++++++++ .../Structures, Enumerations/DeviceGuid.cs | 203 ++------------ ...DeviceRegistryPropertyEnum.cs => SPDRP.cs} | 10 +- 14 files changed, 480 insertions(+), 291 deletions(-) create mode 100644 AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs rename AlphaFS/Filesystem/Structures, Enumerations/{SetupDiGetDeviceRegistryPropertyEnum.cs => SPDRP.cs} (96%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs index 4fab7742e..d0dde0b84 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs @@ -50,7 +50,7 @@ public void AlphaFS_Device_EnumerateDevices_Local_Success() foreach (var device in Alphaleonis.Win32.Filesystem.Device.EnumerateDevices(host, deviceClass)) - UnitTestConstants.Dump(device, -24); + UnitTestConstants.Dump(device, -28); } diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 0d59fc0d5..c1557d739 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -320,6 +320,7 @@ + @@ -388,7 +389,6 @@ - @@ -488,6 +488,7 @@ + diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Device.EnumerateDevices.cs index ead4d5a95..f5a911111 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -24,6 +24,7 @@ using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; +using System.Text; namespace Alphaleonis.Win32.Filesystem { @@ -54,7 +55,7 @@ public static IEnumerable EnumerateDevices(string hostName, DeviceGu /// [AlphaFS] Enumerates all available devices on the local or remote host. [SecurityCritical] - internal static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid interfaceGuid, bool getAllProperties) + internal static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid deviceGuid, bool getAllProperties) { if (Utils.IsNullOrWhiteSpace(hostName)) hostName = Environment.MachineName; @@ -73,13 +74,13 @@ internal static IEnumerable EnumerateDevicesCore(string hostName, De NativeMethods.IsValidHandle(safeMachineHandle, lastError); - var deviceGuid = new Guid(Utils.GetEnumDescription(interfaceGuid)); + 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 deviceGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.SetupDiGetClassDevsExFlags.Present | NativeMethods.SetupDiGetClassDevsExFlags.DeviceInterface, IntPtr.Zero, hostName, IntPtr.Zero)) + 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()); @@ -94,9 +95,10 @@ internal static IEnumerable EnumerateDevicesCore(string hostName, De { var interfaceData = new NativeMethods.SP_DEVICE_INTERFACE_DATA {cbSize = interfaceStructSize}; - var success = NativeMethods.SetupDiEnumDeviceInterfaces(safeHandle, IntPtr.Zero, ref deviceGuid, memberInterfaceIndex++, ref interfaceData); + 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) @@ -110,16 +112,15 @@ internal static IEnumerable EnumerateDevicesCore(string hostName, De var diData = new NativeMethods.SP_DEVINFO_DATA {cbSize = dataStructSize}; - var deviceInfo = new DeviceInfo(hostName) - { - ClassGuid = deviceGuid, - DevicePath = GetDeviceInterfaceDetail(safeHandle, ref interfaceData, ref diData).DevicePath, - InstanceId = GetDeviceInstanceId(safeMachineHandle, hostName, diData) - }; + 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); @@ -136,12 +137,6 @@ internal static IEnumerable EnumerateDevicesCore(string hostName, De [SecurityCritical] private static string GetDeviceInstanceId(SafeCmConnectMachineHandle safeMachineHandle, string hostName, NativeMethods.SP_DEVINFO_DATA diData) { - // CM_Get_Parent_Ex() - // Note: Using this function to access remote machines is not supported - // beginning with Windows 8 and Windows Server 2012, as this functionality has been removed. - // http://msdn.microsoft.com/en-us/library/windows/hardware/ff538615%28v=vs.85%29.aspx - - uint ptrPrevious; var lastError = NativeMethods.CM_Get_Parent_Ex(out ptrPrevious, diData.DevInst, 0, safeMachineHandle); @@ -150,21 +145,15 @@ private static string GetDeviceInstanceId(SafeCmConnectMachineHandle safeMachine NativeError.ThrowException(lastError, hostName); - // Now we get the InstanceID of the USB level device. - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize / 4)) + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize / 8)) // 512 { - // CM_Get_Device_ID_Ex() - // Note: Using this function to access remote machines is not supported beginning with Windows 8 and Windows Server 2012, - // as this functionality has been removed. - // http://msdn.microsoft.com/en-us/library/windows/hardware/ff538411%28v=vs.85%29.aspx - 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. + // 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(); } @@ -189,10 +178,68 @@ private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetDeviceInterfaceD } +// private static Guid? GetDeviceBusTypeGuid(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData) +// { +// var bufferSize = NativeMethods.DefaultFileBufferSize / 32; // 128 + +// string guidText = null; +// var descriptionBuffer = new byte[bufferSize]; +// ulong propertyType = 0; +// var requiredSize = 0; + +// var success = NativeMethods.SetupDiGetDeviceProperty(safeHandle, ref infoData, ref NativeMethods.DEVPROPKEYS.DeviceBusTypeGuid, ref propertyType, descriptionBuffer, bufferSize, ref requiredSize, 0); + +// var lastError = Marshal.GetLastWin32Error(); + +// if (success) +// { +// var value = Encoding.Unicode.GetString(descriptionBuffer); + +// var result = value.Remove(value.IndexOf((char)0)); + +// guidText = !Utils.IsNullOrWhiteSpace(result) ? result.Trim() : null; +// } + + +//#if NET35 +// return !Utils.IsNullOrWhiteSpace(guidText) ? new Guid(guidText) : (Guid?) null; +//#else +// Guid guid; +// return Guid.TryParse(guidText, out guid) ? (Guid?) guid : null; +//#endif +// } + + + private static string GetDeviceBusReportedDeviceDescription(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData) + { + var bufferSize = NativeMethods.DefaultFileBufferSize / 32; // 128 + + var descriptionBuffer = new byte[bufferSize]; + ulong propertyType = 0; + var requiredSize = 0; + + + var success = NativeMethods.SetupDiGetDeviceProperty(safeHandle, ref infoData, ref NativeMethods.DEVPROPKEYS.DeviceBusReportedDeviceDesc, ref propertyType, descriptionBuffer, descriptionBuffer.Length, ref requiredSize, 0); + + var lastError = Marshal.GetLastWin32Error(); + + if (success) + { + var value = Encoding.Unicode.GetString(descriptionBuffer); + + var result = value.Remove(value.IndexOf((char) 0)); + + return !Utils.IsNullOrWhiteSpace(result) ? result.Trim() : null; + } + + return null; + } + + [SecurityCritical] - private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum property) + private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData, NativeMethods.SPDRP property) { - var bufferSize = NativeMethods.DefaultFileBufferSize / 8; + var bufferSize = NativeMethods.DefaultFileBufferSize / 8; // 512 while (true) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) @@ -201,9 +248,13 @@ private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMet var lastError = Marshal.GetLastWin32Error(); - if (success) - return safeBuffer.PtrToStringUni(); + { + 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. @@ -222,45 +273,48 @@ private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo device { SetMinimalDeviceProperties(safeHandle, deviceInfo, infoData); - deviceInfo.CompatibleIds = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.CompatibleIds); + //var guid = GetDeviceBusTypeGuid(safeHandle, infoData); + + //if (null != guid) + // deviceInfo.BusTypeGuid = (Guid)guid; + + - deviceInfo.Driver = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Driver); + deviceInfo.CompatibleIds = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.CompatibleIds); - deviceInfo.EnumeratorName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.EnumeratorName); + deviceInfo.DeviceDriver = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.Driver); - deviceInfo.HardwareId = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.HardwareId); + deviceInfo.EnumeratorName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.EnumeratorName); - deviceInfo.LocationInformation = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.LocationInformation); + deviceInfo.HardwareId = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.HardwareId); - deviceInfo.LocationPaths = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.LocationPaths); - - deviceInfo.Service = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Service); + deviceInfo.LocationInformation = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.LocationInformation); + + deviceInfo.LocationPaths = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.LocationPaths); + + deviceInfo.Manufacturer = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.Manufacturer); + + deviceInfo.Service = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.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.BusReportedDeviceDescription = GetDeviceBusReportedDeviceDescription(safeHandle, infoData); - deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Class); - deviceInfo.DeviceDescription = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceDescription); + deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.BaseContainerId)); - //deviceInfo.DeviceType = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.DeviceType); + deviceInfo.ClassGuid = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.ClassGuid)); - deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.FriendlyName); + deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.Class); - deviceInfo.Manufacturer = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.Manufacturer); + deviceInfo.DeviceDescription = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.DeviceDescription); - deviceInfo.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SetupDiGetDeviceRegistryPropertyEnum.PhysicalDeviceObjectName); + deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.FriendlyName); + + deviceInfo.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.PhysicalDeviceObjectName); } - - - //private static uint IOCTL_STORAGE_QUERY_PROPERTY = CTL_CODE((uint) NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE, 0x500, 0,0); - //private static uint CTL_CODE(uint deviceType, uint function, uint method, uint access) - //{ - // return (deviceType << 16) | (access << 14) | (function << 2) | method; - //} } } diff --git a/AlphaFS/Device/DeviceInfo.cs b/AlphaFS/Device/DeviceInfo.cs index 61c57368e..d25731e0b 100644 --- a/AlphaFS/Device/DeviceInfo.cs +++ b/AlphaFS/Device/DeviceInfo.cs @@ -21,14 +21,12 @@ using Alphaleonis.Win32.Network; using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem { /// Provides access to information of a device, on a local or remote host. - [SerializableAttribute] + [Serializable] [SecurityCritical] public sealed class DeviceInfo { @@ -52,38 +50,28 @@ public DeviceInfo(string host) #endregion // Constructors - #region Methods - - /// Enumerates all available devices on the local host. - /// One of the devices. - /// instances of type from the local host. - [SecurityCritical] - public IEnumerable EnumerateDevices(DeviceGuid deviceGuid) - { - return Device.EnumerateDevicesCore(HostName, deviceGuid, true); - } - - #endregion // Methods - - #region Properties /// Represents the value of the base container identifier (ID) .The Windows Plug and Play (PnP) manager assigns this value to the device node (devnode). public Guid BaseContainerId { get; internal set; } - /// Represents the name of the device setup class that a device instance belongs to. - public string DeviceClass { get; internal set; } + /// Represents a description of a device instance as identified by the bus. + public string BusReportedDeviceDescription { get; internal set; } /// Represents the of the device setup class that a device instance belongs to. public Guid ClassGuid { get; internal set; } - + /// Represents the list of compatible identifiers for a device instance. public string CompatibleIds { get; internal set; } + /// Represents the name of the device setup class that a device instance belongs to. + public string DeviceClass { get; internal set; } + + /// Represents a description of a device instance. public string DeviceDescription { get; internal set; } @@ -92,12 +80,8 @@ public IEnumerable EnumerateDevices(DeviceGuid deviceGuid) public string DevicePath { get; internal set; } - ///// The device type of a device instance. - //public string DeviceType { get; internal set; } - - /// Represents the registry entry name of the driver key for a device instance. - public string Driver { get; internal set; } + public string DeviceDriver { get; internal set; } /// Represents the name of the enumerator for a device instance. diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs index ddb612a57..fe69b08a3 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs @@ -46,9 +46,9 @@ internal static IEnumerable EnumeratePhysicalDrivesCore(bool { var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(isElevated, null, null, deviceInfo)).Where(physicalDrive => null != physicalDrive).ToArray(); - var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(false, null, volumeGuid, null)).Where(physicalDrive => null != physicalDrive).ToArray(); + var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(false, volumeGuid, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); - var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(false, null, driveName, null)).Where(physicalDrive => null != physicalDrive).ToArray(); + var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(false, driveName, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); foreach (var pDrive in physicalDrives) diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index a5d156d25..276940517 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -95,17 +95,17 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// /// /// indicates the current process is in an elevated state, allowing to retrieve more data. - /// A instance. /// /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// A string (when is set to ). /// + /// A instance. /// A instance. /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, StorageDeviceInfo storageInfo, string devicePath, DeviceInfo deviceInfo) + internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, string devicePath, StorageDeviceInfo storageInfo, DeviceInfo deviceInfo) { var isDeviceInfo = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); @@ -126,17 +126,18 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, Stor DeviceDescription = isDeviceInfo ? deviceInfo.DeviceDescription : null, - Manufacturer = isDeviceInfo ? deviceInfo.Manufacturer : null, - // "FriendlyName" usually contains a more complete name, as seen in Windows Explorer. Name = isDeviceInfo ? deviceInfo.FriendlyName : null, - PhysicalDeviceObjectName = isDeviceInfo ? deviceInfo.PhysicalDeviceObjectName : null + PhysicalDeviceObjectName = isDeviceInfo ? deviceInfo.PhysicalDeviceObjectName : null, + + + StorageAdapterInfo = isDeviceInfo ? new StorageAdapterInfo{BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription} : null }; if (isElevated) - PopulatePhysicalDriveInfo(devicePath, pDriveInfo); + PopulatePhysicalDriveInfo(devicePath, deviceInfo, pDriveInfo); return pDriveInfo; @@ -144,7 +145,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, Stor /// Sets the physical drive properties such as FriendlyName, device size and serial number. Requires elevation. - private static void PopulatePhysicalDriveInfo(string devicePath, PhysicalDriveInfo physicalDriveInfo) + private static void PopulatePhysicalDriveInfo(string devicePath, DeviceInfo deviceInfo, PhysicalDriveInfo physicalDriveInfo) { using (var safeHandle = OpenPhysicalDrive(devicePath, FileSystemRights.Read | FileSystemRights.Write)) { @@ -160,7 +161,12 @@ private static void PopulatePhysicalDriveInfo(string devicePath, PhysicalDriveIn using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, devicePath, NativeMethods.DefaultFileBufferSize / 4)) { if (null != safeBuffer) + { physicalDriveInfo.StorageAdapterInfo = new StorageAdapterInfo(safeBuffer.PtrToStructure(0)); + + if (null != deviceInfo) + physicalDriveInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; + } } @@ -186,7 +192,13 @@ private static void PopulatePhysicalDriveInfo(string devicePath, PhysicalDriveIn physicalDriveInfo.StorageDeviceInfo.RemovableMedia = deviceDescriptor.RemovableMedia; - physicalDriveInfo.StorageDeviceInfo.SerialNumber = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(); + + var serial = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(); + + if (Utils.IsNullOrWhiteSpace(serial) || serial.Length == 1) + serial = null; + + physicalDriveInfo.StorageDeviceInfo.SerialNumber = serial; var vendorId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.VendorIdOffset).Trim(); diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs index baeb62cff..6d8ae1c26 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs @@ -103,7 +103,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri if (isElevated) { - var pDriveInfo = GetPhysicalDriveInfoCore(true, storageDeviceInfo, pathToDevice, null); + var pDriveInfo = GetPhysicalDriveInfoCore(true, pathToDevice, storageDeviceInfo, null); if (null != pDriveInfo) storageDeviceInfo = pDriveInfo.StorageDeviceInfo; diff --git a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs index 53490bd25..5852b4679 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs @@ -79,10 +79,6 @@ public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) : this() public Collection LogicalDrives { get; internal set; } - /// The Manufacturer of the physical drive. - public string Manufacturer { get; internal set; } - - /// The "FriendlyName" of the physical drive. public string Name { get; internal set; } diff --git a/AlphaFS/Device/StorageAdapterInfo.cs b/AlphaFS/Device/StorageAdapterInfo.cs index d2df63b48..7c09d28c4 100644 --- a/AlphaFS/Device/StorageAdapterInfo.cs +++ b/AlphaFS/Device/StorageAdapterInfo.cs @@ -79,6 +79,9 @@ internal StorageAdapterInfo(NativeMethods.STORAGE_ADAPTER_DESCRIPTOR adapter) : public StorageBusType BusType { get; internal set; } + /// Represents a description of a device instance as identified by the bus. + public string BusReportedDeviceDescription { get; internal set; } + /// The version number, if any, of the storage adapter. public Version BusVersion { get; internal set; } @@ -107,7 +110,7 @@ public string MaximumTransferBytesUnitSize /// A string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "{0} {1}", BusType.ToString(), MaximumTransferBytesUnitSize); + return string.Format(CultureInfo.CurrentCulture, "{0} {1} {2}", BusReportedDeviceDescription, BusType.ToString(), MaximumTransferBytesUnitSize.ToString()); } @@ -136,7 +139,7 @@ public override bool Equals(object obj) /// A hash code for the current Object. public override int GetHashCode() { - return MaximumTransferBytes + AcceleratedTransfer.GetHashCode() + BusVersion.GetHashCode() + BusType.GetHashCode(); + return MaximumTransferBytes + AcceleratedTransfer.GetHashCode() + (null != BusVersion ? BusVersion.GetHashCode() : 0) + BusType.GetHashCode(); } diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs index 3f2a27347..c769d194a 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs @@ -68,6 +68,6 @@ internal static partial class NativeMethods /// Invalid FileAttributes = -1 - internal const FileAttributes InvalidFileAttributes = (FileAttributes)(-1); + internal const FileAttributes InvalidFileAttributes = (FileAttributes) (-1); } } diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs index bbb1b74d5..73d28a037 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs @@ -187,8 +187,7 @@ internal static partial class NativeMethods /// /// /// SetupDiEnumDeviceInterfaces returns TRUE if the function completed without error. - /// If the function completed with an error, FALSE is returned and the error code for the failure can be retrieved by calling - /// GetLastError. + /// If the function completed with an error, FALSE is returned and the error code for the failure can be retrieved by calling GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] @@ -202,8 +201,7 @@ internal static partial class NativeMethods /// /// /// - /// If the operation succeeds, SetupDiGetClassDevsEx returns a handle to a device information set that contains all installed - /// devices that matched the supplied parameters. + /// If the operation succeeds, SetupDiGetClassDevsEx returns a handle to a device information set that contains all installed devices that matched the supplied parameters. /// If the operation fails, the function returns INVALID_HANDLE_VALUE. To get extended error information, call GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] @@ -215,13 +213,13 @@ internal static partial class NativeMethods /// /// Available in Microsoft Windows 2000 and later versions of Windows. ///   - /// The interface detail returned by this function consists of a device path that can be passed to Win32 functions such as CreateFile. Do not attempt to parse the device path symbolic name. The device path can be reused across system starts. + /// The interface detail returned by this function consists of a device path that can be passed to Win32 functions such as CreateFile. + /// Do not attempt to parse the device path symbolic name. The device path can be reused across system starts. /// /// /// /// SetupDiGetDeviceInterfaceDetail returns TRUE if the function completed without error. - /// If the function completed with an error, FALSE is returned and the error code for the failure can be retrieved by calling - /// GetLastError. + /// If the function completed with an error, FALSE is returned and the error code for the failure can be retrieved by calling GetLastError. /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] @@ -229,6 +227,60 @@ internal static partial class NativeMethods internal static extern bool SetupDiGetDeviceInterfaceDetail(SafeHandle hDevInfo, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData, [MarshalAs(UnmanagedType.U4)] uint deviceInterfaceDetailDataSize, IntPtr requiredSize, ref SP_DEVINFO_DATA deviceInfoData); + + /// The SetupDiGetDeviceProperty function retrieves a device instance property. + /// + /// Available in Windows Vista and later versions of Windows. + /// + /// + /// + /// SetupDiGetDeviceProperty returns TRUE if it is successful. + /// Otherwise, it returns FALSE, and the logged error can be retrieved by calling GetLastError. + /// + [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetupDiGetDevicePropertyW"), SuppressUnmanagedCodeSecurity] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetupDiGetDeviceProperty(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, ref DEVPROPKEY propkey, [MarshalAs(UnmanagedType.U8)] ref ulong propertyDataType, byte[] propertyBuffer, int propertyBufferSize, ref int requiredSize, uint flags); + + + + [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetupDiGetDevicePropertyW"), SuppressUnmanagedCodeSecurity] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetupDiGetDeviceProperty3(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, ref DEVPROPKEY propkey, [MarshalAs(UnmanagedType.U8)] ref ulong propertyDataType, Guid propertyBuffer, int propertyBufferSize, ref int requiredSize, uint flags); + + + /// The SetupDiGetDeviceProperty function retrieves a device instance property. + /// + /// Available in Windows Vista and later versions of Windows. + /// + /// + /// + /// SetupDiGetDeviceProperty returns TRUE if it is successful. + /// Otherwise, it returns FALSE, and the logged error can be retrieved by calling GetLastError. + /// + [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetupDiGetDevicePropertyW"), SuppressUnmanagedCodeSecurity] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetupDiGetDeviceProperty2(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, ref DEVPROPKEY propkey, [MarshalAs(UnmanagedType.U8)] ref ulong propertyDataType, SafeGlobalMemoryBufferHandle propertyBuffer, int propertyBufferSize, ref int requiredSize, [MarshalAs(UnmanagedType.U4)] uint flags); + + + /// The SetupDiGetDeviceRegistryProperty function retrieves a specified Plug and Play device property. + /// + /// Available in Microsoft Windows 2000 and later versions of Windows. + /// + /// + /// + /// SetupDiGetDeviceRegistryProperty returns TRUE if the call was successful. + /// Otherwise, it returns FALSE and the logged error can be retrieved by making a call to GetLastError. + /// SetupDiGetDeviceRegistryProperty returns the ERROR_INVALID_DATA error code if the requested property does not exist for a device or if the property data is not valid. + /// + [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetupDiGetDeviceRegistryProperty(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, SPDRP property, ref int propertyRegDataType, byte[] propertyBuffer, [MarshalAs(UnmanagedType.U4)] uint propertyBufferSize, ref int requiredSize); + + /// The SetupDiGetDeviceRegistryProperty function retrieves a specified Plug and Play device property. /// /// Available in Microsoft Windows 2000 and later versions of Windows. @@ -242,7 +294,7 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SetupDiGetDeviceRegistryProperty(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, SetupDiGetDeviceRegistryPropertyEnum property, IntPtr propertyRegDataType, SafeGlobalMemoryBufferHandle propertyBuffer, [MarshalAs(UnmanagedType.U4)] uint propertyBufferSize, IntPtr requiredSize); + internal static extern bool SetupDiGetDeviceRegistryProperty(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, SPDRP property, IntPtr propertyRegDataType, SafeGlobalMemoryBufferHandle propertyBuffer, [MarshalAs(UnmanagedType.U4)] uint propertyBufferSize, IntPtr requiredSize); #endregion // SetupDiXxx } diff --git a/AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs b/AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs new file mode 100644 index 000000000..370f595ba --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs @@ -0,0 +1,250 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace Alphaleonis.Win32.Filesystem +{ + internal static partial class NativeMethods + { + /// In Windows Vista and later versions of Windows, the DEVPROPKEY structure represents a device property key for a device property in the unified device property model. + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct DEVPROPKEY + { + /// A globally unique ID (GUID) for the device property. + public Guid fmtid; + + /// A value that identifies the device property. + public ulong pid; + } + + + + private static class ClassCategories + { + //public static readonly Guid Name = CreateGuid(0xb725f130, 0x47ef, 0x101a, 0xa5, 0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac); + public static readonly Guid Device1 = CreateGuid(0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0); + //public static readonly Guid Device2 = CreateGuid(0x4340a6c5, 0x93fa, 0x4706, 0x97, 0x2c, 0x7b, 0x64, 0x80, 0x08, 0xa5, 0xa7); + //public static readonly Guid Device3 = CreateGuid(0x80497100, 0x8c73, 0x48b9, 0xaa, 0xd9, 0xce, 0x38, 0x7e, 0x19, 0xc5, 0x6e); + //public static readonly Guid Device4 = CreateGuid(0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57); + //public static readonly Guid Device5 = CreateGuid(0x8c7ed206, 0x3f8a, 0x4827, 0xb3, 0xab, 0xae, 0x9e, 0x1f, 0xae, 0xfc, 0x6c); + //public static readonly Guid Device6 = CreateGuid(0x80d81ea6, 0x7473, 0x4b0c, 0x82, 0x16, 0xef, 0xc1, 0x1a, 0x2c, 0x4c, 0x8b); + public static readonly Guid Numa = CreateGuid(0x540b947e, 0x8b40, 0x45bc, 0xa8, 0xa2, 0x6a, 0x0b, 0x89, 0x4c, 0xbd, 0xa2); + //public static readonly Guid Device7 = CreateGuid(0x83da6326, 0x97a6, 0x4088, 0x94, 0x53, 0xa1, 0x92, 0x3f, 0x57, 0x3b, 0x29); + //public static readonly Guid Device8 = CreateGuid(0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6); + //public static readonly Guid DeviceSafeRemovel = CreateGuid(0xafd97640, 0x86a3, 0x4210, 0xb6, 0x7c, 0x28, 0x9c, 0x41, 0xaa, 0xbe, 0x55); + //public static readonly Guid DriverPackage = CreateGuid(0xcf73bb51, 0x3abf, 0x44a2, 0x85, 0xe0, 0x9a, 0x3d, 0xc7, 0xa1, 0x21, 0x32); + //public static readonly Guid DeviceClass1 = CreateGuid(0x4321918b, 0xf69e, 0x470d, 0xa5, 0xde, 0x4d, 0x88, 0xc7, 0x5a, 0xd2, 0x4b); + //public static readonly Guid DeviceClass2 = CreateGuid(0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66); + //public static readonly Guid DeviceClass3 = CreateGuid(0x713d1703, 0xa2e2, 0x49f5, 0x92, 0x14, 0x56, 0x47, 0x2e, 0xf3, 0xda, 0x5c); + //public static readonly Guid DeviceInterface = CreateGuid(0x026e516e, 0xb814, 0x414b, 0x83, 0xcd, 0x85, 0x6d, 0x6f, 0xef, 0x48, 0x22); + //public static readonly Guid DeviceInterfaceClass = CreateGuid(0x14c83a99, 0x0b3f, 0x44b7, 0xbe, 0x4c, 0xa1, 0x78, 0xd3, 0x99, 0x05, 0x64); + //public static readonly Guid AudioEndpoint = CreateGuid(0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e); + //public static readonly Guid AudioEngine1 = CreateGuid(0xf19f064d, 0x82c, 0x4e27, 0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c); + //public static readonly Guid AudioEngine2 = CreateGuid(0xe4870e26, 0x3cc5, 0x4cd2, 0xba, 0x46, 0xca, 0xa, 0x9a, 0x70, 0xed, 0x4); + + + // Needed for .NET Standard 1.0 compliance . + private static Guid CreateGuid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) + { + return new Guid(unchecked((int)a), unchecked((short)b), unchecked((short)c), d, e, f, g, h, i, j, k); + } + } + + + public class DEVPROPKEYS + { + //public static DEVPROPKEY Name = new DEVPROPKEY {fmtid = ClassCategories.Name, pid = 10 }; // DEVPROP_TYPE_STRING + + // Device properties. These correspond to the old setupapi SPDRP_XXX properties. + + //public static DEVPROPKEY DeviceDeviceDesc = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 2}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceHardwareIds = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 3}; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceCompatibleIds = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 4 }; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceService = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 6 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceClass = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 9 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceClassGuid = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 10 }; // DEVPROP_TYPE_GUID + //public static DEVPROPKEY DeviceDriver = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 11 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceConfigFlags = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 12 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceManufacturer = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 13 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceFriendlyName = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 14 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceLocationInfo = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 15 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DevicePdoName = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 16 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceCapabilities = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 17 }; // DEVPROP_TYPE_UNINT32 + //public static DEVPROPKEY DeviceUiNumber = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 18 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceUpperFilters = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 19 }; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceLowerFilters = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 20 }; // DEVPROP_TYPE_STRING_LIST + public static DEVPROPKEY DeviceBusTypeGuid = new DEVPROPKEY { fmtid = ClassCategories.Device1, pid = 21 }; // DEVPROP_TYPE_GUID + //public static DEVPROPKEY DeviceLegacyBusType = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 22 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceBusNumber = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 23 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceEnumeratorName = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 24 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceSecurity = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 25 }; // DEVPROP_TYPE_SECURITY_DESCRIPTOR + //public static DEVPROPKEY DeviceSecuritySds = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 26 }; // DEVPROP_TYPE_SECURITY_DESCRIPTOR_STRING + //public static DEVPROPKEY DeviceDevType = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 27 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceExclusive = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 28 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceCharacteristics = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 29 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceAddress = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 30 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceUiNumberDescFormat = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 31 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DevicePowerData = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 32 }; // DEVPROP_TYPE_BINARY + //public static DEVPROPKEY DeviceRemovalPolicy = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 33 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceRemovalPolicyDefault = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 34 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceRemovalPolicyOverride = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 35 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceInstallState = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 36 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceLocationPaths = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 37 }; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceBaseContainerId = new DEVPROPKEY {fmtid = ClassCategories.Device1, pid = 38 }; // DEVPROP_TYPE_GUID + + + // Device properties. These correspond to a device's status and problem code. + + //public static DEVPROPKEY DeviceDevNodeStatus = new DEVPROPKEY {fmtid = ClassCategories.Device2, pid = 2 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceProblemCode = new DEVPROPKEY {fmtid = ClassCategories.Device2, pid = 3 }; // DEVPROP_TYPE_UINT32 + + + // Device properties. These correspond to device relations. + + //public static DEVPROPKEY DeviceEjectionRelations = new DEVPROPKEY {fmtid = ClassCategories.Device2, pid = 4 }; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceRemovalRelations = new DEVPROPKEY {fmtid = ClassCategories.Device2, pid = 5 }; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DevicePowerRelations = new DEVPROPKEY {fmtid = ClassCategories.Device2, pid = 6 }; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceBusRelationsn = new DEVPROPKEY {fmtid = ClassCategories.Device2, pid = 7 }; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceParent = new DEVPROPKEY {fmtid = ClassCategories.Device2, pid = 8 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceChildren = new DEVPROPKEY {fmtid = ClassCategories.Device2, pid = 9 }; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceSiblings = new DEVPROPKEY {fmtid = ClassCategories.Device2, pid = 10 }; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceTransportRelations = new DEVPROPKEY {fmtid = ClassCategories.Device2, pid = 11 }; // DEVPROP_TYPE_STRING_LIST + + + // Other Device properties. + + //public static DEVPROPKEY DeviceReported = new DEVPROPKEY {fmtid = ClassCategories.Device3, pid = 2}; // DEVPROP_TYPE_BOOLEAN + //public static DEVPROPKEY DeviceLegacy = new DEVPROPKEY {fmtid = ClassCategories.Device3, pid = 3}; // DEVPROP_TYPE_BOOLEAN + + //public static DEVPROPKEY DeviceInstanceId = new DEVPROPKEY {fmtid = ClassCategories.Device4, pid = 256 }; // DEVPROP_TYPE_STRING + + //public static DEVPROPKEY DeviceContainerId = new DEVPROPKEY {fmtid = ClassCategories.Device5, pid = 2 }; // DEVPROP_TYPE_GUID + + //public static DEVPROPKEY DeviceModelId = new DEVPROPKEY {fmtid = ClassCategories.Device6, pid = 2 }; // DEVPROP_TYPE_GUID + //public static DEVPROPKEY DeviceFriendlyNameAttributes = new DEVPROPKEY {fmtid = ClassCategories.Device6, pid = 3 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceManufacturerAttributes = new DEVPROPKEY {fmtid = ClassCategories.Device6, pid = 4 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DevicePresenceNotForDeviceb = new DEVPROPKEY {fmtid = ClassCategories.Device6, pid = 5 }; // DEVPROP_TYPE_BOOLEAN + //public static DEVPROPKEY DeviceSignalStrength = new DEVPROPKEY {fmtid = ClassCategories.Device6, pid = 6 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceIsAssociateableByUserAction = new DEVPROPKEY {fmtid = ClassCategories.Device6, pid = 7 }; // DEVPROP_TYPE_BOOLEAN + + //public static DEVPROPKEY DeviceInstallInProgress = new DEVPROPKEY { fmtid = ClassCategories.Device7, pid = 9 }; // DEVPROP_TYPE_BOOLEAN + + //public static DEVPROPKEY NumaProximityDomain = new DEVPROPKEY {fmtid = ClassCategories.Numa, pid = 1 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceDhpRebalancePolicy = new DEVPROPKEY {fmtid = ClassCategories.Numa, pid = 2 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceNumaNode = new DEVPROPKEY {fmtid = ClassCategories.Numa, pid = 3}; // DEVPROP_TYPE_UINT32 + public static DEVPROPKEY DeviceBusReportedDeviceDesc = new DEVPROPKEY { fmtid = ClassCategories.Numa, pid = 4 }; // DEVPROP_TYPE_STRING + + + // Device driver properties. + + //public static DEVPROPKEY DeviceDriverDate = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 2 }; // DEVPROP_TYPE_FILETIME + //public static DEVPROPKEY DeviceDriverVersion = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 3 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceDriverDesc = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 4}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceDriverInfPath = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 5}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceDriverInfSection = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 6}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceDriverInfSectionExt = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 7}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceMatchingDeviceId = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 8}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceDriverProvider = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 9}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceDriverPropPageProvider = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 10 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceDriverCoInstallers = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 11 }; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceResourcePickerTags = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 12 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceResourcePickerExceptions = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 13 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceDriverRank = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 14 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceDriverLogoLevel = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 15 }; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceNoConnectSound = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 17 }; // DEVPROP_TYPE_BOOLEAN + //public static DEVPROPKEY DeviceGenericDriverInstalled = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 18 }; // DEVPROP_TYPE_BOOLEAN + //public static DEVPROPKEY DeviceAdditionalSoftwareRequested = new DEVPROPKEY {fmtid = ClassCategories.Device8, pid = 19 }; // DEVPROP_TYPE_BOOLEAN + + + // Device safe-removal properties. + + //public static DEVPROPKEY DeviceSafeRemovalRequired = new DEVPROPKEY {fmtid = ClassCategories.DeviceSafeRemovel, pid = 2 }; // DEVPROP_TYPE_BOOLEAN + //public static DEVPROPKEY DeviceSafeRemovalRequiredOverride = new DEVPROPKEY {fmtid = ClassCategories.DeviceSafeRemovel, pid = 3 }; // DEVPROP_TYPE_BOOLEAN + + + // Device properties that were set by the driver package that was installed on the device. + + //public static DEVPROPKEY DrvPkgModel = new DEVPROPKEY {fmtid = ClassCategories.DriverPackage, pid = 2}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DrvPkgVendorWebSite = new DEVPROPKEY {fmtid = ClassCategories.DriverPackage, pid = 3}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DrvPkgDetailedDescription = new DEVPROPKEY {fmtid = ClassCategories.DriverPackage, pid = 4}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DrvPkgDocumentationLink = new DEVPROPKEY {fmtid = ClassCategories.DriverPackage, pid = 5}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DrvPkgIcon = new DEVPROPKEY {fmtid = ClassCategories.DriverPackage, pid = 6}; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DrvPkgBrandingIcon = new DEVPROPKEY {fmtid = ClassCategories.DriverPackage, pid = 7}; // DEVPROP_TYPE_STRING_LIST + + + // Device setup class properties. These correspond to the old setupapi SPCRP_XXX properties. + + //public static DEVPROPKEY DeviceClassUpperFilters = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass1, pid = 19}; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceClassLowerFilters = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass1, pid = 20}; // DEVPROP_TYPE_STRING_LIST + //public static DEVPROPKEY DeviceClassSecurity = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass1, pid = 25}; // DEVPROP_TYPE_SECURITY_DESCRIPTOR + //public static DEVPROPKEY DeviceClassSecuritySds = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass1, pid = 26}; // DEVPROP_TYPE_SECURITY_DESCRIPTOR_STRING + //public static DEVPROPKEY DeviceClassDevType = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass1, pid = 27}; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceClassExclusive = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass1, pid = 28}; // DEVPROP_TYPE_UINT32 + //public static DEVPROPKEY DeviceClassCharacteristics = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass1, pid = 29}; // DEVPROP_TYPE_UINT32 + + + // Device setup class properties. These correspond to registry values under the device class GUID key. + + //public static DEVPROPKEY DeviceClassName = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass2, pid = 2 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceClassClassName = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass2, pid = 3}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceClassIcon = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass2, pid = 4}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceClassClassInstaller = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass2, pid = 5}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceClassPropPageProvider = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass2, pid = 6}; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceClassNoInstallClass = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass2, pid = 7}; // DEVPROP_TYPE_BOOLEAN + //public static DEVPROPKEY DeviceClassNoDisplayClass = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass2, pid = 8}; // DEVPROP_TYPE_BOOLEAN + //public static DEVPROPKEY DeviceClassSilentInstall = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass2, pid = 9}; // DEVPROP_TYPE_BOOLEAN + //public static DEVPROPKEY DeviceClassNoUseClass = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass2, pid = 10 }; // DEVPROP_TYPE_BOOLEAN + //public static DEVPROPKEY DeviceClassDefaultService = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass2, pid = 11 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceClassIconPath = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass2, pid = 12 }; // DEVPROP_TYPE_STRING_LIST + + + // Other Device setup class properties. + + //public static DEVPROPKEY DeviceClassClassCoInstallers = new DEVPROPKEY {fmtid = ClassCategories.DeviceClass3, pid = 2 }; // DEVPROP_TYPE_STRING_LIST + + + // Device interface properties. + + //public static DEVPROPKEY DeviceInterfaceFriendlyName = new DEVPROPKEY {fmtid = ClassCategories.DeviceInterface, pid = 2 }; // DEVPROP_TYPE_STRING + //public static DEVPROPKEY DeviceInterfaceEnabled = new DEVPROPKEY {fmtid = ClassCategories.DeviceInterface, pid = 3 }; // DEVPROP_TYPE_BOOLEAN + //public static DEVPROPKEY DeviceInterfaceClassGuid = new DEVPROPKEY {fmtid = ClassCategories.DeviceInterface, pid = 4 }; // DEVPROP_TYPE_GUID + + + // Device interface class properties. + + //public static DEVPROPKEY DeviceInterfaceClassDefaultInterface = new DEVPROPKEY {fmtid = ClassCategories.DeviceInterfaceClass, pid = 2}; // DEVPROP_TYPE_STRING + + //public static DEVPROPKEY AudioEndpointFormFactor = new DEVPROPKEY {fmtid = ClassCategories.AudioEndpoint, pid = 0}; + //public static DEVPROPKEY AudioEndpointControlPanelPageProvider = new DEVPROPKEY {fmtid = ClassCategories.AudioEndpoint, pid = 1}; + //public static DEVPROPKEY AudioEndpointAssociation = new DEVPROPKEY {fmtid = ClassCategories.AudioEndpoint, pid = 2}; + //public static DEVPROPKEY AudioEndpointPhysicalSpeakers = new DEVPROPKEY {fmtid = ClassCategories.AudioEndpoint, pid = 3}; + //public static DEVPROPKEY AudioEndpointGuid = new DEVPROPKEY {fmtid = ClassCategories.AudioEndpoint, pid = 4}; + //public static DEVPROPKEY AudioEndpointDisableSysFx = new DEVPROPKEY {fmtid = ClassCategories.AudioEndpoint, pid = 5}; + //public static DEVPROPKEY AudioEndpointFullRangeSpeakers = new DEVPROPKEY {fmtid = ClassCategories.AudioEndpoint, pid = 6}; + //public static DEVPROPKEY AudioEndpointSupportsEventDrivenMode = new DEVPROPKEY {fmtid = ClassCategories.AudioEndpoint, pid = 7}; + //public static DEVPROPKEY AudioEndpointJackSubType = new DEVPROPKEY {fmtid = ClassCategories.AudioEndpoint, pid = 8}; + //public static DEVPROPKEY AudioEngineDeviceFormat = new DEVPROPKEY {fmtid = ClassCategories.AudioEngine1, pid = 0}; + //public static DEVPROPKEY AudioEngineOemFormat = new DEVPROPKEY {fmtid = ClassCategories.AudioEngine2, pid = 3}; + } + } +} diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs index e98404555..8e5f714d7 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs @@ -24,184 +24,6 @@ namespace Alphaleonis.Win32.Filesystem { - ///// System-Defined Device Interface Classes - ///// http://msdn.microsoft.com/en-us/library/windows/hardware/ff541389%28v=vs.85%29.aspx - //public static class DeviceGuids - //{ - // #region 1394 and 61883 Devices - - // /// The BUS1394_CLASS_GUID device interface class is defined for 1394 bus devices. - // public static Guid Bus1394 = new Guid("6BDD1FC1-810F-11d0-BEC7-08002BE2092F"); - - // /// The GUID_61883_CLASS device interface class is defined for devices in the 61883 device setup class. - // public static Guid Guid61883 = new Guid("7EBEFBC0-3200-11d2-B4C2-00A0C9697D07"); - - // #endregion // 1394 and 61883 Devices - - - // #region Battery and ACPI devices - - // /// The GUID_DEVICE_APPLICATIONLAUNCH_BUTTON device interface class is defined for Advanced Configuration and Power Interface (ACPI) application start buttons. - // public static Guid ApplicationLaunchButton = new Guid("629758EE-986E-4D9E-8E47-DE27F8AB054D"); - - // /// The GUID_DEVICE_BATTERY device interface class is defined for battery devices. - // public static Guid Battery = new Guid("72631E54-78A4-11D0-BCF7-00AA00B7B32A"); - - // /// The GUID_DEVICE_LID device interface class is defined for Advanced Configuration and Power Interface (ACPI) lid devices. - // public static Guid Lid = new Guid("4AFA3D52-74A7-11d0-be5e-00A0C9062857"); - - // /// The GUID_DEVICE_MEMORY device interface class is defined for Advanced Configuration and Power Interface (ACPI) memory devices. - // public static Guid Memory = new Guid("3FD0F03D-92E0-45FB-B75C-5ED8FFB01021"); - - // /// The GUID_DEVICE_MESSAGE_INDICATOR device interface class is defined for Advanced Configuration and Power Interface (ACPI) message indicator devices. - // public static Guid MessageIndicator = new Guid("CD48A365-FA94-4CE2-A232-A1B764E5D8B4"); - - // /// The GUID_DEVICE_PROCESSOR device interface class is defined for Advanced Configuration and Power Interface (ACPI) processor devices. - // public static Guid Processor = new Guid("97FADB10-4E33-40AE-359C-8BEF029DBDD0"); - - // /// The GUID_DEVICE_SYS_BUTTON device interface classis defined for Advanced Configuration and Power Interface (ACPI) system power button devices. - // public static Guid SysButton = new Guid("4AFA3D53-74A7-11d0-be5e-00A0C9062857"); - - // /// The GUID_DEVICE_THERMAL_ZONE device interface class is defined for Advanced Configuration and Power Interface (ACPI) thermal zone devices. - // public static Guid ThermalZone = new Guid("4AFA3D51-74A7-11d0-be5e-00A0C9062857"); - - // #endregion // Battery and ACPI devices - - - // #region Bluetooth Devices - - // /// The GUID_BTHPORT_DEVICE_INTERFACE device interface class is defined for Bluetooth radios. - // public static Guid Bluetooth = new Guid("0850302A-B344-4fda-9BE9-90576B8D46F0"); - - // #endregion // Bluetooth Devices - - - // #region Display and Image Devices - - // /// 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. - // public static Guid Brightness = new Guid("FDE5BBA4-B3F9-46FB-BDAA-0728CE3100B4"); - - // /// The GUID_DEVINTERFACE_DISPLAY_ADAPTER device interface class is defined for display views that are supported by display adapters. - // public static Guid DisplayAdapter = new Guid("5B45201D-F2F2-4F3B-85BB-30FF1F953599"); - - // /// 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. - // public static Guid I2C = new Guid("2564AA4F-DDDB-4495-B497-6AD4A84163D7"); - - // /// The GUID_DEVINTERFACE_IMAGE device interface class is defined for WIA devices and Still Image (STI) devices, including digital cameras and scanners. - // public static Guid StillImage = new Guid("6BDD1FC6-810F-11D0-BEC7-08002BE2092F"); - - // /// The GUID_DEVINTERFACE_MONITOR device interface class is defined for monitor devices. - // public static Guid Monitor = new Guid("E6F07B5F-EE97-4a90-B076-33F57BF4EAA7"); - - // /// 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. - // public static Guid OutputProtectionManagement = new Guid("BF4672DE-6B4E-4BE4-A325-68A91EA49C09"); - - // /// The GUID_DEVINTERFACE_VIDEO_OUTPUT_ARRIVAL device interface class is defined for child devices of display devices. - // public static Guid VideoOutputArrival = new Guid("1AD9E4F0-F88D-4360-BAB9-4C2D55E564CD"); - - // /// The GUID_DISPLAY_DEVICE_ARRIVAL device interface class is defined for display adapters. - // public static Guid DisplayDeviceArrival = new Guid("1CA05180-A699-450A-9A0C-DE4FBE3DDD89"); - - // #endregion // Display and Image Devices - - - // #region Interactive Input Devices - - // /// The GUID_DEVINTERFACE_HID device interface class is defined for HID collections. - // public static Guid Hid = new Guid("4D1E55B2-F16F-11CF-88CB-001111000030"); - - // /// The GUID_DEVINTERFACE_KEYBOARD device interface class is defined for keyboard devices. - // public static Guid Keyboard = new Guid("4D1E55B2-F16F-11CF-88CB-001111000030"); - - // /// The GUID_DEVINTERFACE_MOUSE device interface class is defined for mouse devices. - // public static Guid Mouse = new Guid("378DE44C-56EF-11D1-BC8C-00A0C91405DD"); - - // #endregion // Interactive Input Devices - - - // #region Modem Devices - - // /// The GUID_DEVINTERFACE_MODEM device interface class is defined for modem devices. - // public static Guid Modem = new Guid("2C7089AA-2E0E-11D1-B114-00C04FC2AAE4"); - - // #endregion // Modem Devices - - - // #region Network Devices - - // /// The GUID_DEVINTERFACE_NET device interface class is defined for network devices. - // public static Guid Network = new Guid("CAC88484-7515-4C03-82E6-71A87ABAC361"); - - // #endregion // Network Devices - - - // #region Serial and Parallel Port Devices - - // /// The GUID_DEVINTERFACE_COMPORT device interface class is defined for COM ports. - // public static Guid ComPort = new Guid("86E0D1E0-8089-11D0-9CE4-08003E301F73"); - - // /// The GUID_DEVINTERFACE_PARALLEL device interface class is defined for parallel ports that support an IEEE 1284-compatible hardware interface. - // public static Guid Parallel = new Guid("97F76EF0-F883-11D0-AF1F-0000F800845C"); - - // /// The GUID_DEVINTERFACE_PARCLASS device interface class is defined for devices that are attached to a parallel port. - // public static Guid ParallelClass = new Guid("97F76EF0-F883-11D0-AF1F-0000F800845C"); - - // /// The GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR device interface class is defined for Plug and Play (PnP) serial ports. - // public static Guid SerialEnumBusEnumerator = new Guid("4D36E978-E325-11CE-BFC1-08002BE10318"); - - // #endregion // Serial and Parallel Port Devices - - - // #region Storage Devices - - // /// The GUID_DEVINTERFACE_CDCHANGER device interface class is defined for CD-ROM changer devices. - // public static Guid CDChanger = new Guid("53F56312-B6BF-11D0-94F2-00A0C91EFB8B"); - - // /// The GUID_DEVINTERFACE_CDROM device interface class is defined for CD-ROM storage devices. - // public static Guid CDRom = new Guid("53F56308-B6BF-11D0-94F2-00A0C91EFB8B"); - - // /// The GUID_DEVINTERFACE_DISK device interface class is defined for hard disk storage devices. - // public static Guid Disk = new Guid("53F56307-B6BF-11D0-94F2-00A0C91EFB8B"); - - // /// The GUID_DEVINTERFACE_FLOPPY device interface class is defined for floppy disk storage devices. - // public static Guid Floppy = new Guid("53F56311-B6BF-11D0-94F2-00A0C91EFB8B"); - - // /// The GUID_DEVINTERFACE_MEDIUMCHANGER device interface class is defined for medium changer devices. - // public static Guid MediumChanger = new Guid("53F56310-B6BF-11D0-94F2-00A0C91EFB8B"); - - // /// The GUID_DEVINTERFACE_PARTITION device interface class is defined for partition devices. - // public static Guid Partition = new Guid("53F5630A-B6BF-11D0-94F2-00A0C91EFB8B"); - - // /// The GUID_DEVINTERFACE_STORAGEPORT device interface class is defined for storage port devices. - // public static Guid StoragePort = new Guid("2ACCFE60-C130-11D2-B082-00A0C91EFB8B"); - - // /// The GUID_DEVINTERFACE_TAPE device interface class is defined for tape storage devices. - // public static Guid Tape = new Guid("53F5630B-B6BF-11D0-94F2-00A0C91EFB8B"); - - // /// The GUID_DEVINTERFACE_VOLUME device interface class is defined for volume devices. - // public static Guid Volume = new Guid("53F5630D-B6BF-11D0-94F2-00A0C91EFB8B"); - - // /// The GUID_DEVINTERFACE_WRITEONCEDISK device interface class is defined for write-once disk devices. - // public static Guid WriteOnceDisk = new Guid("53F5630C-B6BF-11D0-94F2-00A0C91EFB8B"); - - // #endregion // Storage Devices - - - // #region USB Devices - - // /// The GUID_DEVINTERFACE_USB_DEVICE device interface class is defined for USB devices that are attached to a USB hub. - // public static Guid UsbDevice = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED"); - - // /// The GUID_DEVINTERFACE_USB_HOST_CONTROLLER device interface class is defined for USB host controller devices. - // public static Guid UsbHostController = new Guid("3ABF6F2D-71C4-462A-8A92-1E6861E6AF27"); - - // /// The GUID_DEVINTERFACE_USB_HUB device interface class is defined for USB hub devices. - // public static Guid UsbHub = new Guid("F18A0E88-C30C-11D0-8815-00A0C906BED8"); - - // #endregion // USB Devices - //} - - /// System-Defined Device Interface Classes /// http://msdn.microsoft.com/en-us/library/windows/hardware/ff541389%28v=vs.85%29.aspx public enum DeviceGuid @@ -281,7 +103,7 @@ public enum DeviceGuid /// The GUID_DEVINTERFACE_IMAGE device interface class is defined for WIA devices and Still Image (STI) devices, including digital cameras and scanners. [Description("6BDD1FC6-810F-11D0-BEC7-08002BE2092F")] - StillImage, + Image, /// The GUID_DEVINTERFACE_MONITOR device interface class is defined for monitor devices. [Description("E6F07B5F-EE97-4a90-B076-33F57BF4EAA7")] @@ -358,7 +180,7 @@ public enum DeviceGuid #endregion // Serial and Parallel Port Devices - + #region Storage Devices /// The GUID_DEVINTERFACE_CDCHANGER device interface class is defined for CD-ROM changer devices. @@ -368,7 +190,7 @@ public enum DeviceGuid /// The GUID_DEVINTERFACE_CDROM device interface class is defined for CD-ROM storage devices. [Description("53F56308-B6BF-11D0-94F2-00A0C91EFB8B")] CDRom, - + /// The GUID_DEVINTERFACE_DISK device interface class is defined for hard disk storage devices. [Description("53F56307-B6BF-11D0-94F2-00A0C91EFB8B")] Disk, @@ -401,9 +223,9 @@ public enum DeviceGuid [Description("53F5630C-B6BF-11D0-94F2-00A0C91EFB8B")] WriteOnceDisk, - #endregion // Storage Devices + #region USB Devices /// The GUID_DEVINTERFACE_USB_DEVICE device interface class is defined for USB devices that are attached to a USB hub. @@ -419,8 +241,23 @@ public enum DeviceGuid /// The GUID_DEVINTERFACE_USB_HUB device interface class is defined for USB hub devices. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] [Description("F18A0E88-C30C-11D0-8815-00A0C906BED8")] - UsbHub + UsbHub, #endregion // USB Devices + + + #region Windows Portable devices + + /// The GUID_DEVINTERFACE_WPD device interface class is defined for Windows Portable Devices (WPD). + /// Available in Windows Vista, Windows XP, and later versions of Windows. + [Description("6AC27878-A6FA-4155-BA85-F98F491D4F33")] + Wpd, + + /// The GUID_DEVINTERFACE_WPD_PRIVATE device interface class is defined for specialized Windows Portable Devices (WPD). + /// Available in Windows Vista, Windows XP, and later versions of Windows. + [Description("BA0C718F-4DED-49B7-BDD3-FABE28661211")] + WpdPrivate + + #endregion // Windows Portable devices } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs b/AlphaFS/Filesystem/Structures, Enumerations/SPDRP.cs similarity index 96% rename from AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs rename to AlphaFS/Filesystem/Structures, Enumerations/SPDRP.cs index 2d5a19f6f..ceff7a29f 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/SetupDiGetDeviceRegistryPropertyEnum.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/SPDRP.cs @@ -26,7 +26,7 @@ namespace Alphaleonis.Win32.Filesystem internal static partial class NativeMethods { /// Flags for SetupDiGetDeviceRegistryProperty(). - internal enum SetupDiGetDeviceRegistryPropertyEnum + internal enum SPDRP { /// SPDRP_DEVICEDESC /// Represents a description of a device instance. @@ -58,10 +58,10 @@ internal enum SetupDiGetDeviceRegistryPropertyEnum /// Class = 7, - ///// SPDRP_CLASSGUID - ///// Represents the of the device setup class that a device instance belongs to. - ///// - //ClassGuid = 8, + /// SPDRP_CLASSGUID + /// Represents the of the device setup class that a device instance belongs to. + /// + ClassGuid = 8, /// SPDRP_DRIVER /// Represents the registry entry name of the driver key for a device instance. From 9a7773c6369326560c2c4e63d9e1d672676816bc Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 19 Feb 2018 17:38:53 +0100 Subject: [PATCH 052/133] -Added method: Filesystem.Device.GetStorageAdapterInfo; -Code improvement, work in progress; --- ....GetStorageAdapterInfo_FromLogicalDrive.cs | 60 +++++++++ ...e.GetStorageDeviceInfo_FromLogicalDrive.cs | 14 +-- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 + AlphaFS/AlphaFS.csproj | 3 +- AlphaFS/Device/Device.EnumerateDevices.cs | 4 + AlphaFS/Device/Device.GetDeviceIoData.cs | 4 +- AlphaFS/Device/Device.InvokeDeviceIoData.cs | 2 +- .../Device.GetPhysicalDriveInfo.cs | 44 +++---- .../Device.GetStorageAdapterInfo.cs | 119 ++++++++++++++++++ .../Device.GetStorageDeviceInfo.cs | 14 ++- .../PhysicalDriveInfo/PhysicalDriveInfo.cs | 4 +- AlphaFS/Device/StorageAdapterInfo.cs | 2 +- AlphaFS/Device/StorageDeviceInfo.cs | 4 +- AlphaFS/Win32Errors.cs | 3 + 14 files changed, 235 insertions(+), 43 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs create mode 100644 AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs new file mode 100644 index 000000000..129e54de2 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs @@ -0,0 +1,60 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDriveInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrive_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + var gotDisk = false; + var driveCount = 0; + + + foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) + { + var storageAdapterInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageAdapterInfo(drive.Name); + + Console.WriteLine(); + Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, drive.Name, storageAdapterInfo.ToString()); + + UnitTestConstants.Dump(storageAdapterInfo, -28); + + + Assert.IsNotNull(storageAdapterInfo); + + gotDisk = true; + } + + + Assert.IsTrue(gotDisk); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index 2a8f20103..669f37590 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -40,26 +40,26 @@ public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { + var storageDeviceInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageDeviceInfo(drive.Name); + Console.WriteLine(); - Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]", ++driveCount, drive.Name); + Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, drive.Name, storageDeviceInfo.ToString()); - var storageInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageDeviceInfo(drive.Name); - - UnitTestConstants.Dump(storageInfo, -17); + UnitTestConstants.Dump(storageDeviceInfo, -17); - Assert.IsNotNull(storageInfo); + Assert.IsNotNull(storageDeviceInfo); if (drive.DriveType == System.IO.DriveType.Fixed) { gotDisk = true; - Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.Disk, storageInfo.DeviceType); + Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.Disk, storageDeviceInfo.DeviceType); } if (drive.DriveType == System.IO.DriveType.CDRom) - Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.CDRom, storageInfo.DeviceType); + Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.CDRom, storageDeviceInfo.DeviceType); } diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 9dfc79f48..da1599325 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -150,6 +150,7 @@ + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index c1557d739..1e162c73c 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -201,6 +201,7 @@ + @@ -693,7 +694,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Device.EnumerateDevices.cs index f5a911111..da7ce86e4 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -212,6 +212,10 @@ private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetDeviceInterfaceD private static string GetDeviceBusReportedDeviceDescription(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData) { + if (!OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows7)) + return null; + + var bufferSize = NativeMethods.DefaultFileBufferSize / 32; // 128 var descriptionBuffer = new byte[bufferSize]; diff --git a/AlphaFS/Device/Device.GetDeviceIoData.cs b/AlphaFS/Device/Device.GetDeviceIoData.cs index d4366e5a2..f75be46c4 100644 --- a/AlphaFS/Device/Device.GetDeviceIoData.cs +++ b/AlphaFS/Device/Device.GetDeviceIoData.cs @@ -52,9 +52,9 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa // Dynamic disk. - if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || + if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_NOT_READY || - // Request device number from a DeviceGuid.StillImage device. + // Request device number from a DeviceGuid.Image device. lastError == Win32Errors.ERROR_NOT_SUPPORTED) return null; diff --git a/AlphaFS/Device/Device.InvokeDeviceIoData.cs b/AlphaFS/Device/Device.InvokeDeviceIoData.cs index e1ca99abe..99f5e8ac5 100644 --- a/AlphaFS/Device/Device.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Device.InvokeDeviceIoData.cs @@ -52,7 +52,7 @@ private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle return safeBuffer; - if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_INVALID_PARAMETER) + if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_NOT_READY || lastError == Win32Errors.ERROR_INVALID_PARAMETER) return null; diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index 276940517..d1e2a250a 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -30,6 +30,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Device { /// [AlphaFS] Retrieves the physical drive on the Computer that is related to the logical drive name, volume GUID or . + /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. /// Do not call this method for every volume or logical drive on the system as each call queries all physical drives and associated volumes and logical drives. /// Instead, use method and property and/or . /// @@ -48,29 +49,27 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) bool isDrive; bool isVolume; bool isDeviceInfo; - string logicalDrive; - - + var isElevated = Security.ProcessContext.IsElevatedProcess; devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); - var storageInfo = GetStorageDeviceInfoCore(isElevated, devicePath); + + var sdi = GetStorageDeviceInfoCore(isElevated, devicePath); - if (null == storageInfo) + if (null == sdi) return null; + // Use logical drive path. + if (isDrive) - { - GetDevicePath(devicePath, out logicalDrive); - devicePath = logicalDrive; - } + GetDevicePath(devicePath, out devicePath); var pDriveInfo = isDeviceInfo - ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => pDrive.StorageDeviceInfo.DeviceNumber == storageInfo.DeviceNumber && pDrive.StorageDeviceInfo.PartitionNumber == storageInfo.PartitionNumber) + ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => pDrive.StorageDeviceInfo.DeviceNumber == sdi.DeviceNumber && pDrive.StorageDeviceInfo.PartitionNumber == sdi.PartitionNumber) : isVolume ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => null != pDrive.VolumeGuids && pDrive.VolumeGuids.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) @@ -80,15 +79,17 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) : null; - if (null != pDriveInfo) - pDriveInfo.StorageDeviceInfo.PartitionNumber = storageInfo.PartitionNumber; + if (null != pDriveInfo && null != pDriveInfo.StorageDeviceInfo) + pDriveInfo.StorageDeviceInfo.PartitionNumber = sdi.PartitionNumber; return pDriveInfo; } - /// [AlphaFS] Retrieves the physical drive information such as DeviceType, DeviceNumber, PartitionNumber and the serial number and Product ID. + /// [AlphaFS] Retrieves the physical drive on the Computer that is related to the logical drive name, volume GUID or . + /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. + /// /// A instance that represents the physical drive on the Computer or null on error/no data available. /// /// @@ -100,12 +101,12 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// A string (when is set to ). /// - /// A instance. + /// A instance. /// A instance. /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, string devicePath, StorageDeviceInfo storageInfo, DeviceInfo deviceInfo) + internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) { var isDeviceInfo = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); @@ -113,20 +114,19 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, stri devicePath = deviceInfo.DevicePath; - if (null == storageInfo) - storageInfo = GetStorageDeviceInfoCore(isElevated, devicePath); + if (null == storageDeviceInfo) + storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, devicePath); - if (null == storageInfo) + if (null == storageDeviceInfo) return null; - var pDriveInfo = new PhysicalDriveInfo(storageInfo) + var pDriveInfo = new PhysicalDriveInfo(storageDeviceInfo) { DevicePath = devicePath, DeviceDescription = isDeviceInfo ? deviceInfo.DeviceDescription : null, - - // "FriendlyName" usually contains a more complete name, as seen in Windows Explorer. + Name = isDeviceInfo ? deviceInfo.FriendlyName : null, PhysicalDeviceObjectName = isDeviceInfo ? deviceInfo.PhysicalDeviceObjectName : null, @@ -144,7 +144,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, stri } - /// Sets the physical drive properties such as FriendlyName, device size and serial number. Requires elevation. + /// Sets the physical drive properties such as FriendlyName, device size and serial number. private static void PopulatePhysicalDriveInfo(string devicePath, DeviceInfo deviceInfo, PhysicalDriveInfo physicalDriveInfo) { using (var safeHandle = OpenPhysicalDrive(devicePath, FileSystemRights.Read | FileSystemRights.Write)) diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs new file mode 100644 index 000000000..37642a6cb --- /dev/null +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs @@ -0,0 +1,119 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Security.AccessControl; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// Populating instance properties requires an elevated state. + /// + /// A instance that represent the storage device on the Computer that is related to . + /// + /// + /// + /// + /// + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string (when is set to ). + /// + public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) + { + return GetStorageAdapterInfoCore(devicePath); + } + + + + + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// Populating instance properties requires an elevated state. + /// + /// A instance that represent the storage device on the Computer that is related to . + /// + /// + /// + /// + /// + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string (when is set to ). + /// + internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath) + { + string logicalDrive; + + var pathToDevice = GetDevicePath(devicePath, out logicalDrive); + + if (Utils.IsNullOrWhiteSpace(pathToDevice)) + return null; + + + StorageAdapterInfo storageAdapterInfo = null; + + + StartGetData: + + using (var safeHandle = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read | FileSystemRights.Write)) + { + var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY + { + PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, + QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery + }; + + + // Get storage adapter info. + + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, devicePath, NativeMethods.DefaultFileBufferSize / 4)) + { + if (null == safeBuffer) + { + // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + + + var volDiskExtents = GetVolumeDiskExtents(safeHandle); + + if (volDiskExtents.HasValue) + { + // Use the first disk extent. + + pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); + + goto StartGetData; + } + } + + else + using (safeBuffer) + storageAdapterInfo = new StorageAdapterInfo(safeBuffer.PtrToStructure(0)); + } + } + + + return storageAdapterInfo; + } + } +} diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs index 6d8ae1c26..b5fb3ae77 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs @@ -26,7 +26,9 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// Most properties of the returned instance are meaningless unless this method is called from an elevated state. + /// /// A instance that represent the storage device on the Computer that is related to . /// /// @@ -43,7 +45,11 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) } - /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + + + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// Most properties of the returned instance are meaningless unless this method is called from an elevated state. + /// /// A instance that represent the storage device on the Computer that is related to . /// /// @@ -70,8 +76,6 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri StartGetData: - // No elevation needed. - using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) { var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); @@ -94,10 +98,8 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri } else - { using (safeBuffer) storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure(0)); - } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs index 5852b4679..4abc38158 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs @@ -45,9 +45,9 @@ private PhysicalDriveInfo() /// Initializes a PhysicalDriveInfo instance. - public PhysicalDriveInfo(StorageDeviceInfo storageInfo) : this() + public PhysicalDriveInfo(StorageDeviceInfo storageDeviceInfo) : this() { - StorageDeviceInfo = storageInfo; + StorageDeviceInfo = storageDeviceInfo; } diff --git a/AlphaFS/Device/StorageAdapterInfo.cs b/AlphaFS/Device/StorageAdapterInfo.cs index 7c09d28c4..e542cddb1 100644 --- a/AlphaFS/Device/StorageAdapterInfo.cs +++ b/AlphaFS/Device/StorageAdapterInfo.cs @@ -110,7 +110,7 @@ public string MaximumTransferBytesUnitSize /// A string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "{0} {1} {2}", BusReportedDeviceDescription, BusType.ToString(), MaximumTransferBytesUnitSize.ToString()); + return string.Format(CultureInfo.CurrentCulture, "{0} {1} {2}", BusType.ToString(), BusVersion.ToString(), MaximumTransferBytesUnitSize); } diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs index 0dc404f52..c3b93b1d8 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -114,7 +114,9 @@ public string TotalSizeUnitSize /// A string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "{0} {1} {2} {3}:{4}", VendorId, ProductId, DeviceType.ToString(), DeviceNumber, PartitionNumber).Trim(); + return string.Format(CultureInfo.CurrentCulture, "{0} {1}:{2} {3}", + + DeviceType.ToString(), DeviceNumber.ToString(), PartitionNumber.ToString(), (VendorId + " " + ProductId + " " + ProductRevision).Trim()) .Trim(); } diff --git a/AlphaFS/Win32Errors.cs b/AlphaFS/Win32Errors.cs index 4bc15d53a..ddea0c3f3 100644 --- a/AlphaFS/Win32Errors.cs +++ b/AlphaFS/Win32Errors.cs @@ -113,7 +113,10 @@ public static int GetHrFromWin32Error(uint errorCode) public const uint ERROR_HANDLE_EOF = 38; //public const uint ERROR_HANDLE_DISK_FULL = 39; + + /// (50) The request is not supported public const uint ERROR_NOT_SUPPORTED = 50; + //public const uint ERROR_REM_NOT_LIST = 51; //public const uint ERROR_DUP_NAME = 52; From cfe20298a66eb67ae484038e45212180ca43c2e4 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 19 Feb 2018 23:25:22 +0100 Subject: [PATCH 053/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 3 +- ...ice.GetPhysicalDriveInfo_FromDevicePath.cs | 2 +- ...e.GetPhysicalDriveInfo_FromLogicalDrive.cs | 2 +- ..._Device.GetPhysicalDriveInfo_FromVolume.cs | 2 +- ....GetStorageAdapterInfo_FromLogicalDrive.cs | 4 + .../Device.EnumeratePhysicalDrives.cs | 18 +-- .../Device.GetPhysicalDriveInfo.cs | 103 ++++------------ .../Device.GetStorageAdapterInfo.cs | 75 +++++++----- .../Device.GetStorageDeviceInfo.cs | 112 +++++++++++++++++- .../PhysicalDriveInfo/PhysicalDriveInfo.cs | 16 +-- AlphaFS/Device/StorageAdapterInfo.cs | 2 +- AlphaFS/Device/StorageDeviceInfo.cs | 8 +- .../NativeMethods.VolumeManagement.cs | 3 +- 13 files changed, 205 insertions(+), 145 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs index fc762b542..8283cce2e 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -42,8 +42,7 @@ public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() foreach (var pDrive in pDrives) { Console.WriteLine(); - Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]", ++pDriveCount, pDrive.StorageDeviceInfo.DeviceNumber); - + Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]\t\t{2}\t\t{3}", ++pDriveCount, pDrive.StorageDeviceInfo.DeviceNumber, pDrive.StorageAdapterInfo.ToString(), pDrive.StorageDeviceInfo.ToString()); UnitTestConstants.Dump(pDrive, -24); diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs index 74300f695..70e1a8533 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs @@ -45,7 +45,7 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromDevicePath_Success() Console.WriteLine(); - Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); + Console.WriteLine("#{0:000}\tInput Device Path: [{1}]\t\t{2}\t\t{3}", ++deviceCount, devicePath, pDrive.StorageAdapterInfo.ToString(), pDrive.StorageDeviceInfo.ToString()); UnitTestConstants.Dump(pDrive, -24); diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs index 47050153f..911c1b143 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs @@ -43,7 +43,7 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromLogicalDrive_Success() var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceDrive); Console.WriteLine(); - Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]", ++driveCount, sourceDrive); + Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}\t\t{3}", ++driveCount, sourceDrive, pDrive.StorageAdapterInfo.ToString(), pDrive.StorageDeviceInfo.ToString()); UnitTestConstants.Dump(pDrive, -24); diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs index abcb01e20..6f5de7d6c 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs @@ -48,7 +48,7 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromVolume_Success() Console.WriteLine(); - Console.WriteLine("#{0:000}\tInput Volume: [{1}]", ++volumeCount, sourceVolume); + Console.WriteLine("#{0:000}\tInput Volume: [{1}]\t\t{2}\t\t{3}", ++volumeCount, sourceVolume, pDrive.StorageAdapterInfo.ToString(), pDrive.StorageDeviceInfo.ToString()); UnitTestConstants.Dump(pDrive, -24); diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs index 129e54de2..4a4e8988d 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs @@ -34,6 +34,10 @@ public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); + if (!UnitTestConstants.IsAdmin()) + Assert.Inconclusive(); + + var gotDisk = false; var driveCount = 0; diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs index fe69b08a3..f61605da2 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs @@ -66,18 +66,18 @@ internal static IEnumerable EnumeratePhysicalDrivesCore(bool } - private static void PopulateLogicalDriveDetails(PhysicalDriveInfo pDriveInfo, PhysicalDriveInfo pLogicalDrive) + private static void PopulateLogicalDriveDetails(PhysicalDriveInfo pDriveInfo, string drivePath) { // Add device logical drive. if (null == pDriveInfo.LogicalDrives) pDriveInfo.LogicalDrives = new Collection(); - pDriveInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(pLogicalDrive.DevicePath)); + pDriveInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(drivePath)); } - private static void PopulateVolumeDetails(PhysicalDriveInfo pDriveInfo, PhysicalDriveInfo pVolume) + private static void PopulateVolumeDetails(PhysicalDriveInfo pDriveInfo, int partitionNumber, string volumeGuid) { //// Add device volume labels. @@ -92,7 +92,7 @@ private static void PopulateVolumeDetails(PhysicalDriveInfo pDriveInfo, Physical if (null == pDriveInfo.PartitionIndexes) pDriveInfo.PartitionIndexes = new Collection(); - pDriveInfo.PartitionIndexes.Add(pVolume.StorageDeviceInfo.PartitionNumber); + pDriveInfo.PartitionIndexes.Add(partitionNumber); // Add device volume GUIDs. @@ -100,7 +100,7 @@ private static void PopulateVolumeDetails(PhysicalDriveInfo pDriveInfo, Physical if (null == pDriveInfo.VolumeGuids) pDriveInfo.VolumeGuids = new Collection(); - pDriveInfo.VolumeGuids.Add(pVolume.DevicePath); + pDriveInfo.VolumeGuids.Add(volumeGuid); } @@ -115,7 +115,7 @@ private static PhysicalDriveInfo PopulatePhysicalCDRom(PhysicalDriveInfo pCdRom, if (null != pVolume) { - PopulateVolumeDetails(pDriveInfo, pVolume); + PopulateVolumeDetails(pDriveInfo, pVolume.StorageDeviceInfo.PartitionNumber, pVolume.DevicePath); // Get logical drive from CDRom matching DeviceNumber and PartitionNumber. @@ -123,7 +123,7 @@ private static PhysicalDriveInfo PopulatePhysicalCDRom(PhysicalDriveInfo pCdRom, var pLogicalDrive = pLogicalDrives.SingleOrDefault(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pVolume.StorageDeviceInfo.PartitionNumber); if (null != pLogicalDrive) - PopulateLogicalDriveDetails(pDriveInfo, pLogicalDrive); + PopulateLogicalDriveDetails(pDriveInfo, pLogicalDrive.DevicePath); } @@ -142,14 +142,14 @@ private static PhysicalDriveInfo PopulatePhysicalDrive(PhysicalDriveInfo pDrive, var volumePartitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; - PopulateVolumeDetails(pDriveInfo, pVolume); + PopulateVolumeDetails(pDriveInfo, pVolume.StorageDeviceInfo.PartitionNumber, pVolume.DevicePath); // Get logical drive from volume matching DeviceNumber and PartitionNumber. foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == volumeDriveNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == volumePartitionNumber)) - PopulateLogicalDriveDetails(pDriveInfo, pLogicalDrive); + PopulateLogicalDriveDetails(pDriveInfo, pLogicalDrive.DevicePath); } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index d1e2a250a..d844e7ba1 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -24,6 +24,7 @@ using System.Linq; using System.Security; using System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { @@ -55,9 +56,9 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); - var sdi = GetStorageDeviceInfoCore(isElevated, devicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, devicePath); - if (null == sdi) + if (null == storageDeviceInfo) return null; @@ -69,7 +70,7 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) var pDriveInfo = isDeviceInfo - ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => pDrive.StorageDeviceInfo.DeviceNumber == sdi.DeviceNumber && pDrive.StorageDeviceInfo.PartitionNumber == sdi.PartitionNumber) + ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => pDrive.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber && pDrive.StorageDeviceInfo.PartitionNumber == storageDeviceInfo.PartitionNumber) : isVolume ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => null != pDrive.VolumeGuids && pDrive.VolumeGuids.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) @@ -80,7 +81,7 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) if (null != pDriveInfo && null != pDriveInfo.StorageDeviceInfo) - pDriveInfo.StorageDeviceInfo.PartitionNumber = sdi.PartitionNumber; + pDriveInfo.StorageDeviceInfo.PartitionNumber = storageDeviceInfo.PartitionNumber; return pDriveInfo; @@ -115,106 +116,50 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, stri if (null == storageDeviceInfo) - storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, devicePath); + storageDeviceInfo = GetStorageDeviceInfoCore(false, devicePath); if (null == storageDeviceInfo) return null; - var pDriveInfo = new PhysicalDriveInfo(storageDeviceInfo) + var pDriveInfo = new PhysicalDriveInfo { DevicePath = devicePath, DeviceDescription = isDeviceInfo ? deviceInfo.DeviceDescription : null, - - Name = isDeviceInfo ? deviceInfo.FriendlyName : null, - - PhysicalDeviceObjectName = isDeviceInfo ? deviceInfo.PhysicalDeviceObjectName : null, + Name = isDeviceInfo ? deviceInfo.FriendlyName : null, - StorageAdapterInfo = isDeviceInfo ? new StorageAdapterInfo{BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription} : null + PhysicalDeviceObjectName = isDeviceInfo ? deviceInfo.PhysicalDeviceObjectName : null }; - if (isElevated) - PopulatePhysicalDriveInfo(devicePath, deviceInfo, pDriveInfo); - + // When elevated, get populated StorageAdapterInfo and StorageDeviceInfo instances. - return pDriveInfo; - } - - - /// Sets the physical drive properties such as FriendlyName, device size and serial number. - private static void PopulatePhysicalDriveInfo(string devicePath, DeviceInfo deviceInfo, PhysicalDriveInfo physicalDriveInfo) - { - using (var safeHandle = OpenPhysicalDrive(devicePath, FileSystemRights.Read | FileSystemRights.Write)) + if (isElevated) { - var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY - { - PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, - QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery - }; - - - // Get storage adapter info. - - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, devicePath, NativeMethods.DefaultFileBufferSize / 4)) + using (var safeHandle = OpenPhysicalDrive(devicePath, FileSystemRights.Read)) { - if (null != safeBuffer) - { - physicalDriveInfo.StorageAdapterInfo = new StorageAdapterInfo(safeBuffer.PtrToStructure(0)); + pDriveInfo.StorageAdapterInfo = GetStorageAdapterInfoNative(safeHandle, devicePath); - if (null != deviceInfo) - physicalDriveInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; - } + storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, devicePath, storageDeviceInfo); } + } - // Get storage device info. - - storagePropertyQuery.PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageDeviceProperty; - - - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, devicePath, NativeMethods.DefaultFileBufferSize / 2)) - { - if (null != safeBuffer) - { - var deviceDescriptor = safeBuffer.PtrToStructure(0); - - - physicalDriveInfo.StorageDeviceInfo.BusType = (StorageBusType) deviceDescriptor.BusType; - - physicalDriveInfo.StorageDeviceInfo.CommandQueueing = deviceDescriptor.CommandQueueing; - - physicalDriveInfo.StorageDeviceInfo.ProductId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductIdOffset).Trim(); - - physicalDriveInfo.StorageDeviceInfo.ProductRevision = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductRevisionOffset).Trim(); - - physicalDriveInfo.StorageDeviceInfo.RemovableMedia = deviceDescriptor.RemovableMedia; - - - var serial = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(); - - if (Utils.IsNullOrWhiteSpace(serial) || serial.Length == 1) - serial = null; - - physicalDriveInfo.StorageDeviceInfo.SerialNumber = serial; - - - var vendorId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.VendorIdOffset).Trim(); - - if (Utils.IsNullOrWhiteSpace(vendorId) || vendorId.Length == 1) - vendorId = null; - - physicalDriveInfo.StorageDeviceInfo.VendorId = vendorId; - } - } + pDriveInfo.StorageDeviceInfo = storageDeviceInfo; - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, devicePath)) + if (isDeviceInfo) + { + if (null == pDriveInfo.StorageAdapterInfo) + pDriveInfo.StorageAdapterInfo = new StorageAdapterInfo(); - physicalDriveInfo.StorageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; + pDriveInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; } + + + return pDriveInfo; } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs index 37642a6cb..0ed8c47ff 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs @@ -22,13 +22,14 @@ using System; using System.Globalization; using System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { public static partial class Device { /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . - /// Populating instance properties requires an elevated state. + /// Calling this method requires an elevated state. /// /// A instance that represent the storage device on the Computer that is related to . /// @@ -46,10 +47,10 @@ public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) } - - + + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . - /// Populating instance properties requires an elevated state. + /// Calling this method requires an elevated state. /// /// A instance that represent the storage device on the Computer that is related to . /// @@ -71,49 +72,65 @@ internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath) return null; - StorageAdapterInfo storageAdapterInfo = null; + using (var safeHandle = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read)) + + return GetStorageAdapterInfoNative(safeHandle, devicePath); + } + + + internal static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle safeHandle, string pathToDevice) + { + var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY + { + PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, + QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery + }; + + SafeFileHandle safeHandleRetry = null; + var isRetry = false; StartGetData: + + // Get storage adapter info. - using (var safeHandle = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read | FileSystemRights.Write)) + using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, NativeMethods.DefaultFileBufferSize / 4)) { - var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY + if (null == safeBuffer) { - PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, - QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery - }; + // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - // Get storage adapter info. + var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, devicePath, NativeMethods.DefaultFileBufferSize / 4)) - { - if (null == safeBuffer) + if (volDiskExtents.HasValue) { - // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + // Use the first disk extent. + pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - var volDiskExtents = GetVolumeDiskExtents(safeHandle); - if (volDiskExtents.HasValue) - { - // Use the first disk extent. + safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); - pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - - goto StartGetData; - } + isRetry = null != safeHandleRetry; } - else - using (safeBuffer) - storageAdapterInfo = new StorageAdapterInfo(safeBuffer.PtrToStructure(0)); + + if (isRetry) + goto StartGetData; + + return null; } - } - - return storageAdapterInfo; + + using (safeBuffer) + { + if (isRetry && !safeHandleRetry.IsClosed) + safeHandleRetry.Close(); + + return new StorageAdapterInfo(safeBuffer.PtrToStructure(0)); + } + } } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs index b5fb3ae77..4fed07bde 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs @@ -21,6 +21,9 @@ using System; using System.Globalization; +using System.Net; +using System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { @@ -103,15 +106,116 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri } - if (isElevated) + if (null != storageDeviceInfo && isElevated) { - var pDriveInfo = GetPhysicalDriveInfoCore(true, pathToDevice, storageDeviceInfo, null); + using (var safeHandle = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read)) - if (null != pDriveInfo) - storageDeviceInfo = pDriveInfo.StorageDeviceInfo; + storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, pathToDevice, storageDeviceInfo); } + return storageDeviceInfo; + } + + + /// Sets the physical drive properties such as FriendlyName, device size and serial number. + private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeHandle, string pathToDevice, StorageDeviceInfo storageDeviceInfo) + { + var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY + { + PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageDeviceProperty, + QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery + }; + + SafeFileHandle safeHandleRetry = null; + var isRetry = false; + + + StartGetData: + + // Get storage device info. + + using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, NativeMethods.DefaultFileBufferSize / 2)) + { + if (null == safeBuffer) + { + // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + + + var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); + + if (volDiskExtents.HasValue) + { + // Use the first disk extent. + + pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); + + + safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); + + isRetry = null != safeHandleRetry; + } + + + if (isRetry) + goto StartGetData; + + return null; + } + + + var deviceDescriptor = safeBuffer.PtrToStructure(0); + + + storageDeviceInfo = new StorageDeviceInfo + { + DeviceType = storageDeviceInfo.DeviceType, + + DeviceNumber = storageDeviceInfo.DeviceNumber, + + PartitionNumber = storageDeviceInfo.PartitionNumber, + + + BusType = (StorageBusType) deviceDescriptor.BusType, + + CommandQueueing = deviceDescriptor.CommandQueueing, + + ProductId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductIdOffset).Trim(), + + ProductRevision = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductRevisionOffset).Trim(), + + RemovableMedia = deviceDescriptor.RemovableMedia + }; + + + var serial = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(); + + if (Utils.IsNullOrWhiteSpace(serial) || serial.Length == 1) + serial = null; + + storageDeviceInfo.SerialNumber = serial; + + + var vendorId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.VendorIdOffset).Trim(); + + if (Utils.IsNullOrWhiteSpace(vendorId) || vendorId.Length == 1) + vendorId = null; + + storageDeviceInfo.VendorId = vendorId; + } + + + using (var safeBuffer = GetDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, pathToDevice)) + + storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; + + + + + if (isRetry && !safeHandleRetry.IsClosed) + safeHandleRetry.Close(); + + return storageDeviceInfo; } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs index 4abc38158..81e116252 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs @@ -34,25 +34,13 @@ public sealed class PhysicalDriveInfo #region Constructors /// Initializes a PhysicalDriveInfo instance. - private PhysicalDriveInfo() + public PhysicalDriveInfo() { - StorageDeviceInfo = new StorageDeviceInfo - { - DeviceNumber = -1, - PartitionNumber = -1 - }; - } - - - /// Initializes a PhysicalDriveInfo instance. - public PhysicalDriveInfo(StorageDeviceInfo storageDeviceInfo) : this() - { - StorageDeviceInfo = storageDeviceInfo; } /// Initializes a PhysicalDriveInfo instance. - public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) : this() + public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) { CopyTo(physicalDriveInfo, this); } diff --git a/AlphaFS/Device/StorageAdapterInfo.cs b/AlphaFS/Device/StorageAdapterInfo.cs index e542cddb1..618ed633b 100644 --- a/AlphaFS/Device/StorageAdapterInfo.cs +++ b/AlphaFS/Device/StorageAdapterInfo.cs @@ -110,7 +110,7 @@ public string MaximumTransferBytesUnitSize /// A string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "{0} {1} {2}", BusType.ToString(), BusVersion.ToString(), MaximumTransferBytesUnitSize); + return string.Format(CultureInfo.CurrentCulture, "{0} {1}", (BusType.ToString() + " " + (null != BusVersion ? BusVersion.ToString() : string.Empty)).Trim(), MaximumTransferBytesUnitSize); } diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs index c3b93b1d8..cb9893e90 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -37,6 +37,10 @@ public sealed class StorageDeviceInfo public StorageDeviceInfo() { DeviceType = StorageDeviceType.Unknown; + + DeviceNumber = -1; + + PartitionNumber = -1; } @@ -70,9 +74,9 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() /// The device number of the storage device, starting at 0. public int DeviceNumber { get; internal set; } - + /// The partition number of the storage device, starting at 1. If the device cannot be partitioned, like a CDROM, -1 is returned. - public int PartitionNumber { get; internal set; } + public int PartitionNumber { get; internal set; } /// The product ID of the physical drive. diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs index 14e35236f..763cd0ad0 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs @@ -145,8 +145,7 @@ internal static partial class NativeMethods /// /// Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive. - /// To determine whether a drive is a USB-type drive, call and specify the - /// SPDRP_REMOVAL_POLICY property. + /// To determine whether a drive is a USB-type drive, SetupDiGetDeviceRegistryProperty and specify the SPDRP_REMOVAL_POLICY property. /// /// /// The return value specifies the type of drive, see . From 6fa6a15fc93fb75043bb1fdced8f9027466e4675 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 23 Feb 2018 14:11:57 +0100 Subject: [PATCH 054/133] Added instance class StoragePartitionInfo, work in progress. --- .../AlphaFS_DeviceTest.cs | 9 + .../AlphaFS_Device.EnumeratePhysicalDrives.cs | 3 + AlphaFS.UnitTest/UnitTest Utility/Dump.cs | 8 +- AlphaFS/AlphaFS.csproj | 14 +- AlphaFS/Device/Device.EnumerateDevices.cs | 32 - AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 17 +- .../Device.GetPartitionInfo.cs | 109 ++ .../Device.GetPhysicalDriveInfo.cs | 4 +- .../Device.GetStorageAdapterInfo.cs | 2 +- .../Device.GetStorageDeviceInfo.cs | 35 +- .../Device.GetStoragePartitionInfo.cs | 191 +++ .../PhysicalDriveInfo/PhysicalDriveInfo.cs | 12 +- AlphaFS/Device/StorageAdapterInfo.cs | 5 +- AlphaFS/Device/StorageDeviceInfo.cs | 9 +- AlphaFS/Device/StoragePartitionInfo.cs | 167 ++ AlphaFS/Device/StoragePartitionInfoGpt.cs | 136 ++ AlphaFS/Device/StoragePartitionInfoMbr.cs | 134 ++ AlphaFS/Device/Test.cs | 1362 +++++++++++++++++ AlphaFS/Device/Test2.cs | 252 +++ .../Native Other/DISK_GEOMETRY_EX.cs | 6 +- .../DRIVE_LAYOUT_INFORMATION_EX.cs | 30 +- .../DRIVE_LAYOUT_INFORMATION_GPT.cs | 6 +- .../DRIVE_LAYOUT_INFORMATION_MBR.cs | 4 +- .../Native Other/DiskPartitionTypes.cs | 72 - .../Native Other/PARTITION_INFORMATION_EX.cs | 32 +- .../Native Other/PARTITION_INFORMATION_GPT.cs | 17 +- .../Native Other/PARTITION_INFORMATION_MBR.cs | 12 +- ...onAttributes.cs => PartitionAttributes.cs} | 18 +- .../DiskPartitionTypes.cs | 74 + .../PartitionAttributes.cs | 49 + .../PartitionStyle.cs | 40 + .../PartitionType..cs | 229 +++ 32 files changed, 2872 insertions(+), 218 deletions(-) create mode 100644 AlphaFS/Device/PhysicalDriveInfo/Device.GetPartitionInfo.cs create mode 100644 AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs create mode 100644 AlphaFS/Device/StoragePartitionInfo.cs create mode 100644 AlphaFS/Device/StoragePartitionInfoGpt.cs create mode 100644 AlphaFS/Device/StoragePartitionInfoMbr.cs create mode 100644 AlphaFS/Device/Test.cs create mode 100644 AlphaFS/Device/Test2.cs delete mode 100644 AlphaFS/Filesystem/Native Other/DiskPartitionTypes.cs rename AlphaFS/Filesystem/Native Other/{EFIPartitionAttributes.cs => PartitionAttributes.cs} (69%) create mode 100644 AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionTypes.cs create mode 100644 AlphaFS/Filesystem/Structures, Enumerations/PartitionAttributes.cs create mode 100644 AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs create mode 100644 AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs index 7c3e6dd41..f9be2ca00 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using Alphaleonis.Win32.Filesystem; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -27,5 +28,13 @@ namespace AlphaFS.UnitTest [TestClass] public partial class AlphaFS_DeviceTest { + [TestMethod] + public void AlphaFS_Device_Test() + { + //var hw = new Hardware(); + + + IOCtl.Main(); + } } } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs index 8283cce2e..3ff615692 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs @@ -49,6 +49,9 @@ public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() UnitTestConstants.Dump(pDrive.StorageAdapterInfo, -28, true); UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -17, true); + + UnitTestConstants.Dump(pDrive.StoragePartitionInfo, -17, true); + Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/UnitTest Utility/Dump.cs b/AlphaFS.UnitTest/UnitTest Utility/Dump.cs index 114ea2167..c5afed939 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/Dump.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/Dump.cs @@ -35,21 +35,21 @@ public static partial class UnitTestConstants public static bool Dump(object obj, int width = -35, bool indent = false) { var cnt = 0; - const string nulll = "\t\tNULL"; var template = "\t{0}#{1:000}\t{2, " + width + "} = [{3}]"; if (obj == null) { - Console.WriteLine(nulll); + Console.WriteLine("\n\t\tNothing to dump because the instance is null."); return false; } Console.WriteLine("\n\t{0}Instance: [{1}]\n", indent ? "\t" : "", obj.GetType().FullName); var loopOk = false; - foreach (var descriptor in TypeDescriptor.GetProperties(obj).Sort().Cast().Where(descriptor => descriptor != null)) + foreach (var descriptor in TypeDescriptor.GetProperties(obj).Sort().Cast().Where(descriptor => null != descriptor)) { string propValue = null; + try { var value = descriptor.GetValue(obj); @@ -109,7 +109,7 @@ public static bool Dump(object obj, int width = -35, bool indent = false) if (null == propValue) propValue = "NULL"; - Console.WriteLine(template, indent ? "\t" : "", ++cnt, descriptor.Name, propValue); + Console.WriteLine(template, indent ? "\t" : string.Empty, ++cnt, descriptor.Name, propValue); } return loopOk; diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 0a1c6af5c..fdac310b3 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -196,6 +196,13 @@ True + + + + + + + @@ -319,7 +326,8 @@ - + + @@ -328,7 +336,7 @@ - + @@ -350,6 +358,8 @@ + + diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Device.EnumerateDevices.cs index da7ce86e4..483e132e8 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -178,38 +178,6 @@ private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetDeviceInterfaceD } -// private static Guid? GetDeviceBusTypeGuid(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData) -// { -// var bufferSize = NativeMethods.DefaultFileBufferSize / 32; // 128 - -// string guidText = null; -// var descriptionBuffer = new byte[bufferSize]; -// ulong propertyType = 0; -// var requiredSize = 0; - -// var success = NativeMethods.SetupDiGetDeviceProperty(safeHandle, ref infoData, ref NativeMethods.DEVPROPKEYS.DeviceBusTypeGuid, ref propertyType, descriptionBuffer, bufferSize, ref requiredSize, 0); - -// var lastError = Marshal.GetLastWin32Error(); - -// if (success) -// { -// var value = Encoding.Unicode.GetString(descriptionBuffer); - -// var result = value.Remove(value.IndexOf((char)0)); - -// guidText = !Utils.IsNullOrWhiteSpace(result) ? result.Trim() : null; -// } - - -//#if NET35 -// return !Utils.IsNullOrWhiteSpace(guidText) ? new Guid(guidText) : (Guid?) null; -//#else -// Guid guid; -// return Guid.TryParse(guidText, out guid) ? (Guid?) guid : null; -//#endif -// } - - private static string GetDeviceBusReportedDeviceDescription(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData) { if (!OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows7)) diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index bf0c6d3cb..b9bdf6c87 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -95,18 +95,7 @@ public static partial class Device [SecurityCritical] internal static object GetDriveStuff(string logicalDrive) { - // FileSystemRights desiredAccess: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes - // without accessing that file or device, even if GENERIC_READ access would have been denied. - // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. - //const int desiredAccess = 0; - - // Requires elevation. - const FileSystemRights desiredAccess = FileSystemRights.Read | FileSystemRights.Write; - - //const bool elevatedAccess = (desiredAccess & FileSystemRights.Read) != 0 && (desiredAccess & FileSystemRights.Write) != 0; - - - using (var safeHandle = OpenPhysicalDrive(logicalDrive, desiredAccess)) + using (var safeHandle = OpenPhysicalDrive(logicalDrive, FileSystemRights.Read | FileSystemRights.Write)) { // DRIVE_LAYOUT_INFORMATION_EX @@ -116,10 +105,12 @@ internal static object GetDriveStuff(string logicalDrive) { var structure = safeBuffer.PtrToStructure(0); - //return structure; + return structure; } } + return null; + // DISK_GEOMETRY_EX diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPartitionInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPartitionInfo.cs new file mode 100644 index 000000000..7c8b4509d --- /dev/null +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPartitionInfo.cs @@ -0,0 +1,109 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + public static StorageAdapterInfo GetPartitionInfo(string devicePath) + { + return GetPartitionInfoCore(devicePath); + } + + + + + internal static StorageAdapterInfo GetPartitionInfoCore(string devicePath) + { + string logicalDrive; + + var pathToDevice = GetDevicePath(devicePath, out logicalDrive); + + if (Utils.IsNullOrWhiteSpace(pathToDevice)) + return null; + + + using (var safeHandle = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read)) + + return GetPartitionInfoNative(safeHandle, devicePath); + } + + + internal static StorageAdapterInfo GetPartitionInfoNative(SafeFileHandle safeHandle, string pathToDevice) + { + var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY + { + PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, + QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery + }; + + SafeFileHandle safeHandleRetry = null; + var isRetry = false; + + + StartGetData: + + // Get storage adapter info. + + using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, NativeMethods.DefaultFileBufferSize / 4)) + { + if (null == safeBuffer) + { + // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + + + var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); + + if (volDiskExtents.HasValue) + { + // Use the first disk extent. + + pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); + + + safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); + + isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; + } + + + if (isRetry) + goto StartGetData; + + return null; + } + + + using (safeBuffer) + { + if (isRetry && !safeHandleRetry.IsClosed) + safeHandleRetry.Close(); + + return new StorageAdapterInfo(safeBuffer.PtrToStructure(0)); + } + } + } + } +} diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index d844e7ba1..9923819ce 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -24,7 +24,6 @@ using System.Linq; using System.Security; using System.Security.AccessControl; -using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { @@ -138,6 +137,9 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, stri if (isElevated) { + GetDriveStuff(@"\\.\C:"); + + using (var safeHandle = OpenPhysicalDrive(devicePath, FileSystemRights.Read)) { pDriveInfo.StorageAdapterInfo = GetStorageAdapterInfoNative(safeHandle, devicePath); diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs index 0ed8c47ff..a5088ae95 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs @@ -112,7 +112,7 @@ internal static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle sa safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); - isRetry = null != safeHandleRetry; + isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs index 4fed07bde..4401f8a6f 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs @@ -21,7 +21,6 @@ using System; using System.Globalization; -using System.Net; using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; @@ -30,7 +29,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Device { /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . - /// Most properties of the returned instance are meaningless unless this method is called from an elevated state. + /// Properties of the returned instance are meaningless unless this method is called from an elevated state. /// /// A instance that represent the storage device on the Computer that is related to . /// @@ -48,10 +47,10 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) } - - + + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . - /// Most properties of the returned instance are meaningless unless this method is called from an elevated state. + /// Properties of the returned instance are meaningless unless this method is called from an elevated state. /// /// A instance that represent the storage device on the Computer that is related to . /// @@ -153,7 +152,7 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); - isRetry = null != safeHandleRetry; + isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; } @@ -184,24 +183,22 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH ProductRevision = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductRevisionOffset).Trim(), - RemovableMedia = deviceDescriptor.RemovableMedia - }; - + RemovableMedia = deviceDescriptor.RemovableMedia, - var serial = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(); - - if (Utils.IsNullOrWhiteSpace(serial) || serial.Length == 1) - serial = null; - - storageDeviceInfo.SerialNumber = serial; + SerialNumber = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(), + VendorId = safeBuffer.PtrToStringAnsi((int)deviceDescriptor.VendorIdOffset).Trim() + }; - var vendorId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.VendorIdOffset).Trim(); - if (Utils.IsNullOrWhiteSpace(vendorId) || vendorId.Length == 1) - vendorId = null; + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.ProductRevision) || storageDeviceInfo.ProductRevision.Length == 1) + storageDeviceInfo.ProductRevision = null; - storageDeviceInfo.VendorId = vendorId; + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.SerialNumber) || storageDeviceInfo.SerialNumber.Length == 1) + storageDeviceInfo.SerialNumber = null; + + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.VendorId) || storageDeviceInfo.VendorId.Length == 1) + storageDeviceInfo.VendorId = null; } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs new file mode 100644 index 000000000..569796325 --- /dev/null +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs @@ -0,0 +1,191 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + + public static StorageDeviceInfo GetStoragePartitionInfo(string devicePath) + { + return GetStorageDeviceInfoCore(Security.ProcessContext.IsElevatedProcess, devicePath); + } + + + + + internal static StorageDeviceInfo GetStoragePartitionInfoCore(bool isElevated, string devicePath) + { + string logicalDrive; + + var pathToDevice = GetDevicePath(devicePath, out logicalDrive); + + if (Utils.IsNullOrWhiteSpace(pathToDevice)) + return null; + + + StorageDeviceInfo storageDeviceInfo = null; + + + StartGetData: + + using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) + { + var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); + + if (null == safeBuffer) + { + // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + + + var volDiskExtents = GetVolumeDiskExtents(safeHandle); + + if (volDiskExtents.HasValue) + { + // Use the first disk extent. + + pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); + + goto StartGetData; + } + } + + else + using (safeBuffer) + storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure(0)); + } + + + if (null != storageDeviceInfo && isElevated) + { + using (var safeHandle = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read)) + + storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, pathToDevice, storageDeviceInfo); + } + + + return storageDeviceInfo; + } + + + private static StorageDeviceInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandle, string pathToDevice, StorageDeviceInfo storageDeviceInfo) + { + var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY + { + PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageDeviceProperty, + QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery + }; + + SafeFileHandle safeHandleRetry = null; + var isRetry = false; + + + StartGetData: + + // Get storage device info. + + using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, NativeMethods.DefaultFileBufferSize / 2)) + { + if (null == safeBuffer) + { + // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + + + var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); + + if (volDiskExtents.HasValue) + { + // Use the first disk extent. + + pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); + + + safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); + + isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; + } + + + if (isRetry) + goto StartGetData; + + return null; + } + + + var deviceDescriptor = safeBuffer.PtrToStructure(0); + + + storageDeviceInfo = new StorageDeviceInfo + { + DeviceType = storageDeviceInfo.DeviceType, + + DeviceNumber = storageDeviceInfo.DeviceNumber, + + PartitionNumber = storageDeviceInfo.PartitionNumber, + + + BusType = (StorageBusType) deviceDescriptor.BusType, + + CommandQueueing = deviceDescriptor.CommandQueueing, + + ProductId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductIdOffset).Trim(), + + ProductRevision = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductRevisionOffset).Trim(), + + RemovableMedia = deviceDescriptor.RemovableMedia, + + SerialNumber = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(), + + VendorId = safeBuffer.PtrToStringAnsi((int)deviceDescriptor.VendorIdOffset).Trim() + }; + + + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.ProductRevision) || storageDeviceInfo.ProductRevision.Length == 1) + storageDeviceInfo.ProductRevision = null; + + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.SerialNumber) || storageDeviceInfo.SerialNumber.Length == 1) + storageDeviceInfo.SerialNumber = null; + + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.VendorId) || storageDeviceInfo.VendorId.Length == 1) + storageDeviceInfo.VendorId = null; + } + + + using (var safeBuffer = GetDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, pathToDevice)) + + storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; + + + + + if (isRetry && !safeHandleRetry.IsClosed) + safeHandleRetry.Close(); + + + return storageDeviceInfo; + } + } +} diff --git a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs index 81e116252..2108a3c28 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs @@ -75,21 +75,21 @@ public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) public Collection PartitionIndexes { get; internal set; } - ///// The partitions that are located on the physical drive. - //public string[] Partitions { get; internal set; } - - /// Encapsulates the physical device location (PDO) information provided by a device's firmware to Windows. public string PhysicalDeviceObjectName { get; internal set; } - /// The storage adapter information, such as bus type. + /// The storage device adapter information. public StorageAdapterInfo StorageAdapterInfo { get; internal set; } - /// The storage device information, such as device type and number. + /// The storage device information. public StorageDeviceInfo StorageDeviceInfo { get; internal set; } + + /// The storage device partitiion information. + public StoragePartitionInfo StoragePartitionInfo { get; internal set; } + /// A collection of volume GUID strings of volumes that are located on the physical drive. public Collection VolumeGuids { get; internal set; } diff --git a/AlphaFS/Device/StorageAdapterInfo.cs b/AlphaFS/Device/StorageAdapterInfo.cs index 618ed633b..8ff23d838 100644 --- a/AlphaFS/Device/StorageAdapterInfo.cs +++ b/AlphaFS/Device/StorageAdapterInfo.cs @@ -139,7 +139,10 @@ public override bool Equals(object obj) /// A hash code for the current Object. public override int GetHashCode() { - return MaximumTransferBytes + AcceleratedTransfer.GetHashCode() + (null != BusVersion ? BusVersion.GetHashCode() : 0) + BusType.GetHashCode(); + unchecked + { + return MaximumTransferBytes + AcceleratedTransfer.GetHashCode() + (null != BusVersion ? BusVersion.GetHashCode() : 0) + BusType.GetHashCode(); + } } diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs index cb9893e90..d718812e9 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -95,7 +95,7 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public string SerialNumber { get; internal set; } - /// The total size of the physical drive. If the session is not elevated -1 is returned + /// The total size of the physical drive. public long TotalSize { get; internal set; } @@ -120,7 +120,7 @@ public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "{0} {1}:{2} {3}", - DeviceType.ToString(), DeviceNumber.ToString(), PartitionNumber.ToString(), (VendorId + " " + ProductId + " " + ProductRevision).Trim()) .Trim(); + DeviceType.ToString(), DeviceNumber.ToString(), PartitionNumber.ToString(), (VendorId + " " + ProductId + " " + ProductRevision).Trim()).Trim(); } @@ -147,7 +147,10 @@ public override bool Equals(object obj) /// A hash code for the current Object. public override int GetHashCode() { - return DeviceNumber + PartitionNumber + (null != SerialNumber ? SerialNumber.GetHashCode() : 0) + BusType.GetHashCode() + DeviceType.GetHashCode(); + unchecked + { + return DeviceNumber + PartitionNumber + (null != SerialNumber ? SerialNumber.GetHashCode() : 0) + BusType.GetHashCode() + DeviceType.GetHashCode(); + } } diff --git a/AlphaFS/Device/StoragePartitionInfo.cs b/AlphaFS/Device/StoragePartitionInfo.cs new file mode 100644 index 000000000..acf51d249 --- /dev/null +++ b/AlphaFS/Device/StoragePartitionInfo.cs @@ -0,0 +1,167 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + [Serializable] + [SecurityCritical] + public sealed class StoragePartitionInfo + { + #region Constructors + + /// Initializes a StoragePartitionInfo instance. + public StoragePartitionInfo() + { + DeviceNumber = -1; + + PartitionNumber = -1; + + PartitionStyle = PartitionStyle.Raw; + } + + + internal StoragePartitionInfo(NativeMethods.STORAGE_DEVICE_NUMBER device, NativeMethods.PARTITION_INFORMATION_EX partition) : this() + { + DeviceNumber = device.DeviceNumber; + + PartitionNumber = (int) partition.PartitionNumber; + + PartitionStyle = (PartitionStyle) partition.PartitionStyle; + + + RewritePartition = partition.RewritePartition; + + TotalSize = (long) partition.PartitionLength; + + GptPartitionInfo = new StoragePartitionInfoGpt(partition.Gpt); + + MbrPartitionInfo = new StoragePartitionInfoMbr(partition.Mbr); + } + + #endregion // Constructors + + + #region Properties + + /// The device number of the storage partition, starting at 0. + public int DeviceNumber { get; internal set; } + + + /// Contains GUID partition table (GPT) partition information. + public StoragePartitionInfoGpt GptPartitionInfo { get; internal set; } + + + /// Contains partition information specific to master boot record (MBR) disks. + public StoragePartitionInfoMbr MbrPartitionInfo { get; internal set; } + + + /// The storage partition number, starting at 1. + public int PartitionNumber { get; internal set; } + + + /// The format of the partition. For a list of values, see . + public PartitionStyle PartitionStyle { get; internal set; } + + + /// The rewritable status of the storage partition. + public bool RewritePartition { get; internal set; } + + + /// The total size of the storage partition. + public long TotalSize { get; internal set; } + + + /// The total size of the physical drive, formatted as a unit size. + public string TotalSizeUnitSize + { + get { return Utils.UnitSizeToText(TotalSize); } + } + + #endregion // Properties + + + #region Methods + + /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". + /// A string that represents this instance. + public override string ToString() + { + return string.Format(CultureInfo.CurrentCulture, "{0}:{1} {2} {3}", + + DeviceNumber.ToString(), PartitionNumber.ToString(), PartitionStyle.ToString(), TotalSizeUnitSize).Trim(); + } + + + /// Determines whether the specified Object is equal to the current Object. + /// Another object to compare to. + /// if the specified Object is equal to the current Object; otherwise, . + public override bool Equals(object obj) + { + if (null == obj || GetType() != obj.GetType()) + return false; + + var other = obj as StoragePartitionInfo; + + return null != other && + other.DeviceNumber == DeviceNumber && + other.PartitionNumber == PartitionNumber && + other.PartitionStyle == PartitionStyle && + other.TotalSize == TotalSize; + } + + + /// Serves as a hash function for a particular type. + /// A hash code for the current Object. + public override int GetHashCode() + { + unchecked + { + return DeviceNumber + PartitionNumber + PartitionStyle.GetHashCode() + TotalSize.GetHashCode(); + } + } + + + /// Implements the operator == + /// A. + /// B. + /// The result of the operator. + public static bool operator ==(StoragePartitionInfo left, StoragePartitionInfo right) + { + return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); + } + + + /// Implements the operator != + /// A. + /// B. + /// The result of the operator. + public static bool operator !=(StoragePartitionInfo left, StoragePartitionInfo right) + { + return !(left == right); + } + + #endregion // Methods + } +} diff --git a/AlphaFS/Device/StoragePartitionInfoGpt.cs b/AlphaFS/Device/StoragePartitionInfoGpt.cs new file mode 100644 index 000000000..530003ceb --- /dev/null +++ b/AlphaFS/Device/StoragePartitionInfoGpt.cs @@ -0,0 +1,136 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + [Serializable] + [SecurityCritical] + public sealed class StoragePartitionInfoGpt + { + #region Constructors + + /// Initializes a StoragePartitionInfoGpt instance. + public StoragePartitionInfoGpt() + { + } + + + internal StoragePartitionInfoGpt(NativeMethods.PARTITION_INFORMATION_GPT gptPartition) : this() + { + Attributes = (PartitionAttributes) gptPartition.Attributes; + + Id = gptPartition.PartitionId; + + Description = gptPartition.Name; + + Type = gptPartition.PartitionType; + } + + #endregion // Constructors + + + #region Properties + + /// The Extensible Firmware Interface (EFI) attributes of the partition. + public PartitionAttributes Attributes { get; internal set; } + + + /// The GUID of the partition. + public Guid Id { get; internal set; } + + + /// The description of the partition. + public string Description { get; internal set; } + + + /// The GUID of the partition that identifies the partition type. + /// Each partition type that the EFI specification supports is identified by its own GUID, which is published by the developer of the partition. + /// + public Guid Type { get; internal set; } + + #endregion // Properties + + + #region Methods + + /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". + /// A string that represents this instance. + public override string ToString() + { + return string.Format(CultureInfo.CurrentCulture, "{0} {1}", Description, Attributes.ToString()).Trim(); + } + + + /// Determines whether the specified Object is equal to the current Object. + /// Another object to compare to. + /// if the specified Object is equal to the current Object; otherwise, . + public override bool Equals(object obj) + { + if (null == obj || GetType() != obj.GetType()) + return false; + + var other = obj as StoragePartitionInfoGpt; + + return null != other && + other.Attributes == Attributes && + other.Id == Id && + other.Description == Description && + other.Type == Type; + } + + + /// Serves as a hash function for a particular type. + /// A hash code for the current Object. + public override int GetHashCode() + { + unchecked + { + return Attributes.GetHashCode() + Id.GetHashCode() + Description.GetHashCode() + Type.GetHashCode(); + } + } + + + /// Implements the operator == + /// A. + /// B. + /// The result of the operator. + public static bool operator ==(StoragePartitionInfoGpt left, StoragePartitionInfoGpt right) + { + return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); + } + + + /// Implements the operator != + /// A. + /// B. + /// The result of the operator. + public static bool operator !=(StoragePartitionInfoGpt left, StoragePartitionInfoGpt right) + { + return !(left == right); + } + + #endregion // Methods + } +} diff --git a/AlphaFS/Device/StoragePartitionInfoMbr.cs b/AlphaFS/Device/StoragePartitionInfoMbr.cs new file mode 100644 index 000000000..d96aa62ed --- /dev/null +++ b/AlphaFS/Device/StoragePartitionInfoMbr.cs @@ -0,0 +1,134 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + [Serializable] + [SecurityCritical] + public sealed class StoragePartitionInfoMbr + { + #region Constructors + + /// Initializes a StoragePartitionInfoMbr instance. + public StoragePartitionInfoMbr() + { + } + + + internal StoragePartitionInfoMbr(NativeMethods.PARTITION_INFORMATION_MBR gptPartition) : this() + { + BootIndicator = gptPartition.BootIndicator; + + HiddenSectors = (int) gptPartition.HiddenSectors; + + RecognizedPartition = gptPartition.RecognizedPartition; + + Type = gptPartition.PartitionType; + } + + #endregion // Constructors + + + #region Properties + + /// if the partition is a boot partition. + public bool BootIndicator { get; internal set; } + + + /// The number of hidden sectors to be allocated when the partition table is created. + public int HiddenSectors { get; internal set; } + + + /// if the partition is of a recognized type. + public bool RecognizedPartition { get; internal set; } + + + /// The type of the partition. + public DiskPartitionTypes Type { get; internal set; } + + #endregion // Properties + + + #region Methods + + /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". + /// A string that represents this instance. + public override string ToString() + { + return string.Format(CultureInfo.CurrentCulture, "BootIndicator {0}, Type: {1}, RecognizedPartition: {2}", BootIndicator.ToString(), Type.ToString(), RecognizedPartition.ToString()).Trim(); + } + + + /// Determines whether the specified Object is equal to the current Object. + /// Another object to compare to. + /// if the specified Object is equal to the current Object; otherwise, . + public override bool Equals(object obj) + { + if (null == obj || GetType() != obj.GetType()) + return false; + + var other = obj as StoragePartitionInfoMbr; + + return null != other && + other.BootIndicator == BootIndicator && + other.HiddenSectors == HiddenSectors && + other.RecognizedPartition == RecognizedPartition && + other.Type == Type; + } + + + /// Serves as a hash function for a particular type. + /// A hash code for the current Object. + public override int GetHashCode() + { + unchecked + { + return BootIndicator.GetHashCode() + HiddenSectors.GetHashCode() + RecognizedPartition.GetHashCode() + Type.GetHashCode(); + } + } + + + /// Implements the operator == + /// A. + /// B. + /// The result of the operator. + public static bool operator ==(StoragePartitionInfoMbr left, StoragePartitionInfoMbr right) + { + return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); + } + + + /// Implements the operator != + /// A. + /// B. + /// The result of the operator. + public static bool operator !=(StoragePartitionInfoMbr left, StoragePartitionInfoMbr right) + { + return !(left == right); + } + + #endregion // Methods + } +} diff --git a/AlphaFS/Device/Test.cs b/AlphaFS/Device/Test.cs new file mode 100644 index 000000000..f775d39d5 --- /dev/null +++ b/AlphaFS/Device/Test.cs @@ -0,0 +1,1362 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.IO; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using Microsoft.Win32; +using Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32.Filesystem +{ + #region Helper: Enum + + public static class EnumHelper + { + public static bool HasFlag(this Enum flags, T value) where T : struct + { + var iFlags = Convert.ToUInt64(flags); + var iValue = Convert.ToUInt64(value); + return ((iFlags & iValue) == iValue); + } + + public static T SetFlag(this Enum flags, T value, bool state = true) + { + if (!Enum.IsDefined(typeof(T), value)) throw new ArgumentException("Enum value and flags types don't match."); + if (state) return (T) Enum.ToObject(typeof(T), Convert.ToUInt64(flags) | Convert.ToUInt64(value)); + return (T) Enum.ToObject(typeof(T), Convert.ToUInt64(flags) & ~Convert.ToUInt64(value)); + } + } + + #endregion + + #region Helper: Byte[] + + public static class ByteHelper + { + public static int IndexOf(this byte[] bytes, byte value, int startIndex = 0) + { + while (startIndex < bytes.Length) + if (bytes[startIndex++] == value) + return startIndex - 1; + return -1; + } + + public static string GetString(this byte[] bytes, int offset) + { + string result = null; + var index = -1; + index = bytes.IndexOf(0, offset); + if (index >= 0) result = Encoding.ASCII.GetString(bytes, offset, index - offset); + return result; + } + + public static T ToStruct(this byte[] bytes, int start = 0) where T : struct + { + var result = new T(); + var size = Marshal.SizeOf(result); + var ptr = Marshal.AllocHGlobal(size); + Marshal.Copy(bytes, start, ptr, size); + result = (T) Marshal.PtrToStructure(ptr, result.GetType()); + Marshal.FreeHGlobal(ptr); + return result; + } + } + + #endregion + + public class Hardware + { + #region [extern] WindowsAPI + + [DllImport("USER32.DLL", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] + private static extern IntPtr CallWindowProcW([In] byte[] bytes, IntPtr hWnd, int msg, [In, Out] byte[] wParam, + IntPtr lParam); + + [DllImport("KERNEL32.DLL", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool VirtualProtect([In] byte[] bytes, IntPtr size, int newProtect, out int oldProtect); + + [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] + private static extern SafeFileHandle CreateFileW([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, + uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, + uint dwFlagsAndAttributes, IntPtr hTemplateFile); + + [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, + SetLastError = true)] + private static extern bool GetVolumeNameForVolumeMountPoint(string mountPoint, StringBuilder name, + uint bufferLength); + + [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] + private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, + STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_DEVICE_ID_DESCRIPTOR lpOutBuffer, + int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); + + [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] + private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, + STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_ADAPTER_DESCRIPTOR lpOutBuffer, + int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); + + [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] + private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, + STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_DEVICE_DESCRIPTOR lpOutBuffer, + int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); + + [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] + private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, + SENDCMDINPARAMS lpInBuffer, int lpInBufferSize, ref SENDCMDOUTPARAMS lpOutBuffer, int lpOutBufferSize, + ref uint lpBytesReturned, int lpOverlapped); + + [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] + private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, IntPtr lpInBuffer, + int lpInBufferSize, ref GETVERSIONOUTPARAMS lpOutBuffer, int lpOutBufferSize, ref uint lpBytesReturned, + int lpOverlapped); + + [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] + private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, IntPtr lpInBuffer, + int lpInBufferSize, ref VOLUMEDISKEXTENTS lpOutBuffer, int lpOutBufferSize, ref uint lpBytesReturned, + int lpOverlapped); + + [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall)] + private static extern int CloseHandle(int hObject); + + [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] + public static extern int EnumSystemFirmwareTables(BiosFirmwareTableProvider providerSignature, + IntPtr firmwareTableBuffer, int bufferSize); + + [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] + private static extern int GetSystemFirmwareTable(BiosFirmwareTableProvider providerSignature, + int dwFirmwareTableID, IntPtr lpTableBuffer, int dwBufferSize); + + [DllImport("USER32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] + private static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, + uint dwFlags); + + #endregion + + private static byte[] _MD5; + private static byte[] _SHA1; + private static byte[] _SHA256; + private static byte[] _SHA512; + + private static string GenerateDate = DateTime.Now.ToString("yyyyMMddHH"); + + // HDD // + + #region [constants] HDD + + private const int VER_PLATFORM_WIN32_NT = 2; + private const int IDENTIFY_BUFFER_SIZE = 512; + private const int CREATE_NEW = 0x1; + private const int OPEN_EXISTING = 0x3; + private const uint GENERIC_READ = 0x80000000; + private const uint GENERIC_WRITE = 0x40000000; + private const int FILE_SHARE_READ = 0x00000001; + private const int FILE_SHARE_WRITE = 0x00000002; + private const uint IDE_ATAPI_IDENTIFY = 0xA1; + private const uint IDE_ATA_IDENTIFY = 0xEC; + private const uint CAP_SMART_CMD = 0x04; + private const uint METHOD_BUFFERED = 0; + private const uint FILE_ANY_ACCESS = 0; + private const uint FILE_ATTRIBUTE_NORMAL = 0x00000080; + private const uint FILE_DEVICE_CONTROLLER = 0x00000004; + private const uint IOCTL_SCSI_BASE = FILE_DEVICE_CONTROLLER; + private const uint FILE_DEVICE_MASS_STORAGE = 0x0000002d; + private const uint IOCTL_STORAGE_BASE = FILE_DEVICE_MASS_STORAGE; + private const uint IOCTL_VOLUME_BASE = 0x00000056; + private const uint IOCTL_SCSI_PASS_THROUGH = 0x0004d004; + private const uint IOCTL_DISK_GET_DRIVE_GEOMETRY = 0x00070000; + private const uint IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = 0x000700a0; + private const uint DFP_GET_VERSION = 0x00074080; + private const uint DFP_SEND_DRIVE_COMMAND = 0x0007c084; + private const uint DFP_RECEIVE_DRIVE_DATA = 0x0007c088; + private const uint IOCTL_STORAGE_GET_DEVICE_NUMBER = 0x002d1080; + private const uint IOCTL_STORAGE_QUERY_PROPERTY = 0x002d1400; + + private const uint IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = 0x00560000; + + // PropertyId For DeviceIoControl // + private const uint StorageDeviceProperty = 0; + private const uint StorageAdapterProperty = 1; + private const uint StorageDeviceIdProperty = 2; + + private const uint StorageDeviceSeekPenaltyProperty = 7; + + // Query Type For DeviceIoControl // + private const uint PropertyStandardQuery = 0; + private const uint PropertyExistsQuery = 1; + + #endregion + + #region [enum] STORAGE_BUS_TYPE + + public enum STORAGE_BUS_TYPE : byte + { + BusTypeUnknown = 0x00, + BusTypeScsi = 0x01, + BusTypeAtapi = 0x02, + BusTypeAta = 0x03, + BusType1394 = 0x04, + BusTypeSsa = 0x05, + BusTypeFibre = 0x06, + BusTypeUsb = 0x07, + BusTypeRAID = 0x08, + BusTypeiScsi = 0x09, + BusTypeSas = 0x0A, + BusTypeSata = 0x0B, + BusTypeSd = 0x0C, + BusTypeMmc = 0x0D, + BusTypeVirtual = 0x0E, + BusTypeFileBackedVirtual = 0x0F, + BusTypeMax = 0x10, + BusTypeMaxReserved = 0x7F + } + + #endregion + + #region [struct] VOLUMEDISKEXTENTS + + [StructLayout(LayoutKind.Explicit)] + public struct VOLUMEDISKEXTENTS + { + [FieldOffset(0)] public uint numberOfDiskExtents; + [FieldOffset(8)] public uint diskNumber; + [FieldOffset(16)] public long startingOffset; + [FieldOffset(24)] public long extentLength; + } + + #endregion + + #region [struct] STORAGE_PROPERTY_QUERY + + [StructLayout(LayoutKind.Sequential)] + private struct STORAGE_PROPERTY_QUERY + { + public uint PropertyId; + public uint QueryType; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] + public byte[] AdditionalParameters; + } + + #endregion + + #region [struct] STORAGE_DEVICE_DESCRIPTOR + + [StructLayout(LayoutKind.Sequential)] + public struct STORAGE_DEVICE_DESCRIPTOR + { + public int Version; + public int Size; + public byte DeviceType; + public byte DeviceTypeModifier; + public byte RemovableMedia; + public byte CommandQueueing; + public int VendorIdOffset; + public int ProductIdOffset; + public int ProductRevisionOffset; + public int SerialNumberOffset; + public STORAGE_BUS_TYPE BusType; + public int RawPropertiesLength; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10240)] + public byte[] RawDeviceProperties; + } + + #endregion + + #region [struct] STORAGE_DEVICE_ID_DESCRIPTOR + + [StructLayout(LayoutKind.Sequential)] + public struct STORAGE_DEVICE_ID_DESCRIPTOR + { + public int Version; + public int Size; + public int NumberOfIdentifiers; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10240)] + public byte[] Identifiers; + } + + #endregion + + #region [struct] STORAGE_ADAPTER_DESCRIPTOR + + [StructLayout(LayoutKind.Sequential)] + public struct STORAGE_ADAPTER_DESCRIPTOR + { + public uint Version; + public uint Size; + public uint MaximumTransferLength; + public uint MaximumPhysicalPages; + public uint AlignmentMask; + public byte AdapterUsesPio; + public byte AdapterScansDown; + public byte CommandQueueing; + public byte AcceleratedTransfer; + public STORAGE_BUS_TYPE BusType; + public ushort BusMajorVersion; + public ushort BusMinorVersion; + public byte SrbType; + public byte AddressType; + } + + #endregion + + #region [struct] GETVERSIONOUTPARAMS + + [StructLayout(LayoutKind.Sequential)] + public struct GETVERSIONOUTPARAMS + { + public byte bVersion; + public byte bRevision; + public byte bReserved; + public byte bIDEDeviceMap; + public int fCapabilities; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] + public int[] dwReserved; + } + + #endregion + + #region [struct] IDEREGS + + [StructLayout(LayoutKind.Sequential, Size = 8)] + public struct IDEREGS + { + public byte Features; + public byte SectorCount; + public byte SectorNumber; + public byte CylinderLow; + public byte CylinderHigh; + public byte DriveHead; + public byte Command; + public byte Reserved; + } + + #endregion + + #region [struct] SENDCMDINPARAMS + + [StructLayout(LayoutKind.Sequential, Size = 32)] + public struct SENDCMDINPARAMS + { + public int BufferSize; + public IDEREGS DriveRegs; + public byte DriveNumber; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] + public byte[] bReserved; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] + public int[] dwReserved; + } + + #endregion + + #region [struct] DRIVERSTATUS + + [StructLayout(LayoutKind.Sequential, Size = 12)] + public struct DRIVERSTATUS + { + public byte DriveError; + public byte IDEStatus; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] + public byte[] bReserved; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] + public int[] dwReserved; + } + + #endregion + + #region [struct] IDSECTOR + + [StructLayout(LayoutKind.Sequential)] + public struct IDSECTOR + { + public short GenConfig; + public short NumberCylinders; + public short Reserved; + public short NumberHeads; + public short BytesPerTrack; + public short BytesPerSector; + public short SectorsPerTrack; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] + public short[] VendorUnique; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] + public byte[] SerialNumber; + + public short BufferClass; + public short BufferSize; + public short ECCSize; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] + public byte[] FirmwareRevision; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)] + public byte[] ModelNumber; + + public short MoreVendorUnique; + public short DoubleWordIO; + public short Capabilities; + public short Reserved1; + public short PIOTiming; + public short DMATiming; + public short BS; + public short NumberCurrentCyls; + public short NumberCurrentHeads; + public short NumberCurrentSectorsPerTrack; + public int CurrentSectorCapacity; + public short MultipleSectorCapacity; + public short MultipleSectorStuff; + public int TotalAddressableSectors; + public short SingleWordDMA; + public short MultiWordDMA; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 382)] + public byte[] bReserved; + } + + #endregion + + #region [struct] SENDCMDOUTPARAMS + + [StructLayout(LayoutKind.Sequential)] + public struct SENDCMDOUTPARAMS + { + public uint cBufferSize; + public DRIVERSTATUS Status; + public IDSECTOR IDS; + } + + #endregion + + [StructLayout(LayoutKind.Sequential)] + public struct PhysicalDisk + { + public byte Number; + public string Model; + public string Firmware; + public string SerialNumber; + public bool RemovableMedia; + public VOLUMEDISKEXTENTS Extents; + public STORAGE_DEVICE_DESCRIPTOR Device; + public STORAGE_DEVICE_ID_DESCRIPTOR DeviceID; + public STORAGE_ADAPTER_DESCRIPTOR Adapter; + public GETVERSIONOUTPARAMS Version; + public SENDCMDOUTPARAMS Params; + } + + #region CTL_CODE + + private uint CTL_CODE(uint DeviceType, uint Function, uint Method, uint Access) + { + return ((DeviceType << 16) | (Access << 14) | (Function << 2) | Method); + } + + #endregion + + #region [private] SwapChars + + private string SwapChars(char[] chars) + { + for (var i = 0; i <= chars.Length - 2; i += 2) + { + char T; + T = chars[i]; + chars[i] = chars[i + 1]; + chars[i + 1] = T; + } + + return new string(chars); + } + + #endregion + + #region [private] SwapBytes + + private string SwapBytes(byte[] bytes) + { + for (var i = 0; i <= bytes.Length - 2; i += 2) + { + byte T; + T = bytes[i]; + bytes[i] = bytes[i + 1]; + bytes[i + 1] = T; + } + + return Encoding.ASCII.GetString(bytes); + } + + #endregion + + #region [private] SwapRawString + + private string SwapRawString(string hexString) + { + var Result = new StringBuilder(); + for (var i = 0; i < hexString.Length; i += 4) + { + Result.Append(Convert.ToChar(Convert.ToByte(hexString.Substring(i + 2, 2), 16))); + Result.Append(Convert.ToChar(Convert.ToByte(hexString.Substring(i + 0, 2), 16))); + } + + return Result.ToString().Trim('\0', ' '); + } + + #endregion + + #region [private] GetPhysicalDisk + + private PhysicalDisk GetPhysicalDisk(string path) + { + var drive = System.IO.Path.GetPathRoot(path).TrimEnd('\\'); + + using (var hDisk = CreateFileW(@"\\.\" + drive, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero)) + { + var Result = new PhysicalDisk(); + uint iBytesReturned = 0; + Result.SerialNumber = string.Empty; + Result.Firmware = string.Empty; + Result.Model = string.Empty; + + var StoragePropertyQuery = new STORAGE_PROPERTY_QUERY(); + + Result.Extents = new VOLUMEDISKEXTENTS(); + Result.Adapter = new STORAGE_ADAPTER_DESCRIPTOR(); + Result.Device = new STORAGE_DEVICE_DESCRIPTOR(); + Result.DeviceID = new STORAGE_DEVICE_ID_DESCRIPTOR(); + Result.Version = new GETVERSIONOUTPARAMS(); + Result.Params = new SENDCMDOUTPARAMS(); + + var IOCMD = CTL_CODE(IOCTL_VOLUME_BASE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS); + if (DeviceIoControl(hDisk, IOCMD, IntPtr.Zero, 0, ref Result.Extents, Marshal.SizeOf(Result.Extents), ref iBytesReturned, 0)) + { + Console.ForegroundColor = ConsoleColor.DarkGray; + Console.WriteLine("Received: IOCTL_VOLUME_BASE"); + Result.Number = Convert.ToByte(Result.Extents.diskNumber); + } + + + + //StoragePropertyQuery.PropertyId = StorageAdapterProperty; + //StoragePropertyQuery.QueryType = PropertyStandardQuery; + + //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.Adapter, Marshal.SizeOf(Result.Adapter), ref iBytesReturned, 0)) + //{ + // Console.ForegroundColor = ConsoleColor.DarkGray; + // Console.WriteLine("Received: STORAGE_ADAPTER_DESCRIPTOR"); + // Console.WriteLine("> Version: "+Result.Adapter.Version+", Size: "+Result.Adapter.Size); + // Console.WriteLine("> MaximumPhysicalPages: "+Result.Adapter.MaximumPhysicalPages); + // Console.WriteLine("> MaximumTransferLength: "+Result.Adapter.MaximumTransferLength); + // Console.WriteLine("> CommandQueueing: "+Result.Adapter.CommandQueueing); + // Console.WriteLine("> BusMajorVersion: "+Result.Adapter.BusMajorVersion); + // Console.WriteLine("> BusMinorVersion: "+Result.Adapter.BusMinorVersion); + // Console.WriteLine("> BusType: "+Result.Adapter.BusType); + //} + + + + //StoragePropertyQuery.PropertyId = StorageDeviceIdProperty; + //StoragePropertyQuery.QueryType = PropertyStandardQuery; + //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.DeviceID, Marshal.SizeOf(Result.DeviceID), ref iBytesReturned, 0)) + //{ + // /File.WriteAllBytes("Hardware."+GenerateDate+".RAID-"+drive[0]+".bin", Result.DeviceID.Identifiers); + // Console.ForegroundColor = ConsoleColor.DarkGray; + // Console.WriteLine("Received: STORAGE_DEVICE_ID_DESCRIPTOR"); + // Console.WriteLine("> Version: "+Result.DeviceID.Version+", Size: "+Result.DeviceID.Size); + // Console.WriteLine("> NumberOfIdentifiers: "+Result.DeviceID.NumberOfIdentifiers); + //} + + + + //StoragePropertyQuery.PropertyId = StorageDeviceProperty; + //StoragePropertyQuery.QueryType = PropertyStandardQuery; + //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.Device, Marshal.SizeOf(Result.Device), ref iBytesReturned, 0)) + //{ + // /File.WriteAllBytes("Hardware."+GenerateDate+".HDD-"+drive[0]+".bin", Result.Device.RawDeviceProperties); + // Console.ForegroundColor = ConsoleColor.DarkGray; + // Console.WriteLine("Received: STORAGE_DEVICE_DESCRIPTOR"); + // Console.WriteLine("> RemovableMedia: "+Convert.ToBoolean(Result.Device.RemovableMedia)); + // Console.WriteLine("> DeviceType: "+Result.Device.DeviceType); + // Console.WriteLine("> BusType: "+Result.Device.BusType); + + // var buffer = Encoding.ASCII.GetString(Result.Device.RawDeviceProperties); + // var basepos = Marshal.SizeOf(Result.Device) - Result.Device.RawDeviceProperties.Length; + + // if (Result.Device.ProductIdOffset > 0) + // Result.Model = buffer.Substring(Result.Device.ProductIdOffset - basepos, 20).Trim('\0', ' '); + // if (Result.Device.ProductRevisionOffset > 0) + // Result.Firmware = buffer.Substring(Result.Device.ProductRevisionOffset - basepos, 8).Trim('\0', ' '); + // if (Result.Device.SerialNumberOffset > 0) + // Result.SerialNumber = + // buffer.Substring(Result.Device.SerialNumberOffset - basepos, 40).Trim('\0', ' '); + // if (Result.SerialNumber != null && Result.SerialNumber.Length == 40) + // Result.SerialNumber = SwapRawString(Result.SerialNumber); + + // Result.RemovableMedia = Convert.ToBoolean(Result.Device.RemovableMedia); + //} + + DeviceIoControl(hDisk, DFP_GET_VERSION, IntPtr.Zero, 0, ref Result.Version, Marshal.SizeOf(Result.Version), ref iBytesReturned, 0); + + if ((Result.Version.fCapabilities & CAP_SMART_CMD) > 0) + { + Console.ForegroundColor = ConsoleColor.DarkGray; + Console.WriteLine("Received: GETVERSIONOUTPARAMS"); + Console.WriteLine("> Version: "+Result.Version.bVersion+"."+Result.Version.bRevision); + var SCI = new SENDCMDINPARAMS + { + DriveRegs = {Command = (int) IDE_ATA_IDENTIFY}, + DriveNumber = Result.Number, + BufferSize = IDENTIFY_BUFFER_SIZE + }; + + if (DeviceIoControl(hDisk, DFP_RECEIVE_DRIVE_DATA, SCI, Marshal.SizeOf(SCI), ref Result.Params, Marshal.SizeOf(Result.Params), ref iBytesReturned, 0)) + { + Console.WriteLine("Received: SENDCMDOUTPARAMS"); + Console.WriteLine("> IDS.Capabilities: "+Result.Params.IDS.Capabilities); + Console.WriteLine("> IDS.BufferSize: "+Result.Params.IDS.BufferSize); + Console.WriteLine("> IDS.SectorsPerTrack: "+Result.Params.IDS.SectorsPerTrack); + Console.WriteLine("> IDS.NumberCylinders: "+Result.Params.IDS.NumberCylinders); + Console.WriteLine("> IDS.NumberHeads: "+Result.Params.IDS.NumberHeads); + + Result.Model = SwapBytes(Result.Params.IDS.ModelNumber).Trim(); + Result.Firmware = SwapBytes(Result.Params.IDS.FirmwareRevision).Trim(); + Result.SerialNumber = SwapBytes(Result.Params.IDS.SerialNumber).Trim(); + } + + } + + return Result; + } + + throw new Win32Exception(); + } + + #endregion + + // CPU // + + #region [enum] BiosFirmwareTableProvider + + public enum BiosFirmwareTableProvider + { + ACPI = (byte) 'A' << 24 | (byte) 'C' << 16 | (byte) 'P' << 8 | (byte) 'I', + FIRM = (byte) 'F' << 24 | (byte) 'I' << 16 | (byte) 'R' << 8 | (byte) 'M', + RSMB = (byte) 'R' << 24 | (byte) 'S' << 16 | (byte) 'M' << 8 | (byte) 'B' + } + + #endregion + + #region [enum] SMBIOSTableType + + public enum SMBIOSTableType : sbyte + { + BIOSInformation = 0, + SystemInformation = 1, + BaseBoardInformation = 2, + EnclosureInformation = 3, + ProcessorInformation = 4, + MemoryControllerInformation = 5, + MemoryModuleInformation = 6, + CacheInformation = 7, + PortConnectorInformation = 8, + SystemSlotsInformation = 9, + OnBoardDevicesInformation = 10, + OEMStrings = 11, + SystemConfigurationOptions = 12, + BIOSLanguageInformation = 13, + GroupAssociations = 14, + SystemEventLog = 15, + PhysicalMemoryArray = 16, + MemoryDevice = 17, + MemoryErrorInformation = 18, + MemoryArrayMappedAddress = 19, + MemoryDeviceMappedAddress = 20, + EndofTable = 127 + } + + #endregion + + #region [enum] SMBIOSTableEntry + + [StructLayout(LayoutKind.Sequential)] + public struct SMBIOSTableHeader + { + public SMBIOSTableType type; + public byte length; + public ushort Handle; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SMBIOSTableEntry + { + public SMBIOSTableHeader header; + public uint index; + } + + #endregion + + #region [enum] SMBIOSTableInfo + + [StructLayout(LayoutKind.Sequential)] + public struct SMBIOSTableBiosInfo + { + public SMBIOSTableHeader header; + public byte vendor; + public byte version; + public ushort startingSegment; + public byte releaseDate; + public byte biosRomSize; + public ulong characteristics; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] + public byte[] extensionBytes; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SMBIOSTableSystemInfo + { + public SMBIOSTableHeader header; + public byte manufacturer; + public byte productName; + public byte version; + public byte serialNumber; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] + public byte[] UUID; + + public byte wakeUpType; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SMBIOSTableBaseBoardInfo + { + public SMBIOSTableHeader header; + public byte manufacturer; + public byte productName; + public byte version; + public byte serialNumber; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SMBIOSTableEnclosureInfo + { + public SMBIOSTableHeader header; + public byte manufacturer; + public byte type; + public byte version; + public byte serialNumber; + public byte assetTagNumber; + public byte bootUpState; + public byte powerSupplyState; + public byte thermalState; + public byte securityStatus; + public long OEM_Defined; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SMBIOSTableProcessorInfo + { + public SMBIOSTableHeader header; + public byte socketDesignation; + public byte processorType; + public byte processorFamily; + public byte processorManufacturer; + public ulong processorID; + public byte processorVersion; + public byte processorVoltage; + public ushort externalClock; + public ushort maxSpeed; + public ushort currentSpeed; + public byte status; + public byte processorUpgrade; + public ushort L1CacheHandler; + public ushort L2CacheHandler; + public ushort L3CacheHandler; + public byte serialNumber; + public byte assetTag; + public byte partNumber; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SMBIOSTableCacheInfo + { + public SMBIOSTableHeader header; + public byte socketDesignation; + public long cacheConfiguration; + public ushort maximumCacheSize; + public ushort installedSize; + public ushort supportedSRAMType; + public ushort currentSRAMType; + public byte cacheSpeed; + public byte errorCorrectionType; + public byte systemCacheType; + public byte associativity; + } + + #endregion + + #region [struct] RawSMBIOSData + + [StructLayout(LayoutKind.Sequential)] + public struct RawSMBIOSData + { + public byte Used20CallingMethod; + public byte MajorVersion; + public byte MinorVersion; + public byte DmiRevision; + public uint Length; + public SMBIOSTableBiosInfo BiosInfo; + public SMBIOSTableSystemInfo SystemInfo; + public SMBIOSTableBaseBoardInfo BaseBoardInfo; + public SMBIOSTableEnclosureInfo EnclosureInfo; + public SMBIOSTableProcessorInfo ProcessorInfo; + public SMBIOSTableCacheInfo CacheInfo; + } + + #endregion + + #region [private] GetTable + + private static byte[] GetTable(BiosFirmwareTableProvider provider, string table) + { + var id = table[3] << 24 | table[2] << 16 | table[1] << 8 | table[0]; + return GetTable(provider, id); + } + + private static byte[] GetTable(BiosFirmwareTableProvider provider, int table) + { + var Result = new byte[0]; + try + { + var sizeNeeded = GetSystemFirmwareTable(provider, table, IntPtr.Zero, 0); + if (sizeNeeded > 0) + { + var bufferPtr = Marshal.AllocHGlobal(sizeNeeded); + GetSystemFirmwareTable(provider, table, bufferPtr, sizeNeeded); + if (Marshal.GetLastWin32Error() == 0) + { + Result = new byte[sizeNeeded]; + Marshal.Copy(bufferPtr, Result, 0, sizeNeeded); + } + + Marshal.FreeHGlobal(bufferPtr); + } + } + catch + { + } + + return Result; + } + + #endregion + + #region [private] EnumerateTables + + private static string[] EnumerateTables(BiosFirmwareTableProvider provider) + { + var Result = new string[0]; + try + { + var sizeNeeded = EnumSystemFirmwareTables(provider, IntPtr.Zero, 0); + if (sizeNeeded > 0) + { + var buffer = new byte[sizeNeeded]; + var bufferPtr = Marshal.AllocHGlobal(sizeNeeded); + EnumSystemFirmwareTables(provider, bufferPtr, sizeNeeded); + if (Marshal.GetLastWin32Error() == 0) + { + Result = new string[sizeNeeded / 4]; + Marshal.Copy(bufferPtr, buffer, 0, sizeNeeded); + for (var i = 0; i < Result.Length; i++) Result[i] = Encoding.ASCII.GetString(buffer, 4 * i, 4); + } + + Marshal.FreeHGlobal(bufferPtr); + } + } + catch + { + } + + return Result; + } + + #endregion + + #region [private] GetRawStrings + + private static string[] GetRawStrings(byte[] bytes, SMBIOSTableEntry entry, ref int pos) + { + var result = new List(); + pos += entry.header.length; + do + { + string s = bytes.GetString(pos); + result.Add(s); + pos += s.Length; + } while (bytes[++pos] != 0); + + pos++; + return result.ToArray(); + } + + #endregion + + // VIDEO // + + #region [enum] DisplayDeviceStateFlags + + public enum DisplayDeviceStateFlags + { + AttachedToDesktop = 0x0000001, + MultiDriver = 0x0000002, + PrimaryDevice = 0x0000004, + MirroringDriver = 0x0000008, + VGACompatible = 0x0000010, + Removable = 0x0000020, + ModesPruned = 0x8000000, + Remote = 0x4000000, + Disconnect = 0x2000000 + } + + #endregion + + #region [struct] DISPLAY_DEVICE + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct DISPLAY_DEVICE + { + [MarshalAs(UnmanagedType.U4)] public int structSize; + + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] + public string DeviceName; + + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] + public string DeviceString; + + [MarshalAs(UnmanagedType.U4)] public DisplayDeviceStateFlags StateFlags; + + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] + public string DeviceID; + + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] + public string DeviceKey; + } + + #endregion + + public Hardware() + { + using (var Binary = new BinaryWriter(new MemoryStream())) + { + + Console.WriteLine(); + + Console.ForegroundColor = ConsoleColor.White; + + Console.WriteLine("[SMBIOS]"); + + // Get BIOS Information // + var RSMB_Tables = EnumerateTables(BiosFirmwareTableProvider.RSMB); + if (RSMB_Tables.Length > 0) + { + var RSMB = GetTable(BiosFirmwareTableProvider.RSMB, RSMB_Tables[0]); + if (RSMB.Length > 0) + { + + File.WriteAllBytes("BIOS." + BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(RSMB), 0).Replace("-", "") + ".RSMB.bin", RSMB); + + Binary.Write(RSMB); + + var RawStrings = new string[0]; + RawSMBIOSData SMBIOS = RSMB.ToStruct(); + + if (SMBIOS.Length > 8) + { + var pos = 0x08; + while (pos < SMBIOS.Length) + { + + Console.ForegroundColor = ConsoleColor.Green; + SMBIOSTableEntry tableEntry = RSMB.ToStruct(pos); + switch (tableEntry.header.type) + { + case SMBIOSTableType.BIOSInformation: + SMBIOS.BiosInfo = RSMB.ToStruct(pos); + RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); + + Console.WriteLine("BIOSInformation"); + + Console.ForegroundColor = ConsoleColor.Yellow; + + if (SMBIOS.BiosInfo.vendor > 0 && SMBIOS.BiosInfo.vendor <= RawStrings.Length) + Console.WriteLine("Vendor: " + RawStrings[SMBIOS.BiosInfo.vendor - 1]); + + if (SMBIOS.BiosInfo.version > 0 && SMBIOS.BiosInfo.version <= RawStrings.Length) + Console.WriteLine("Version: " + RawStrings[SMBIOS.BiosInfo.version - 1]); + break; + case SMBIOSTableType.SystemInformation: + SMBIOS.SystemInfo = RSMB.ToStruct(pos); + RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); + + Console.WriteLine("SystemInformation"); + + Console.ForegroundColor = ConsoleColor.Yellow; + + if (SMBIOS.SystemInfo.manufacturer > 0 && + SMBIOS.SystemInfo.manufacturer <= RawStrings.Length) + Console.WriteLine("Manufacturer: " + RawStrings[SMBIOS.SystemInfo.manufacturer - 1]); + + if (SMBIOS.SystemInfo.productName > 0 && + SMBIOS.SystemInfo.productName <= RawStrings.Length) + Console.WriteLine("Product name: " + RawStrings[SMBIOS.SystemInfo.productName - 1]); + + if (SMBIOS.SystemInfo.version > 0 && SMBIOS.SystemInfo.version <= RawStrings.Length) + Console.WriteLine("Version: " + RawStrings[SMBIOS.SystemInfo.version - 1]); + + if (SMBIOS.SystemInfo.serialNumber > 0 && + SMBIOS.SystemInfo.serialNumber <= RawStrings.Length) + Console.WriteLine("Serial Number: " + RawStrings[SMBIOS.SystemInfo.serialNumber - 1]); + break; + case SMBIOSTableType.BaseBoardInformation: + SMBIOS.BaseBoardInfo = RSMB.ToStruct(pos); + RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); + + Console.WriteLine("BaseBoardInformation"); + + Console.ForegroundColor = ConsoleColor.Yellow; + + if (SMBIOS.BaseBoardInfo.manufacturer > 0 && + SMBIOS.BaseBoardInfo.manufacturer <= RawStrings.Length) + Console.WriteLine("Manufacturer: " + + RawStrings[SMBIOS.BaseBoardInfo.manufacturer - 1]); + + if (SMBIOS.BaseBoardInfo.productName > 0 && + SMBIOS.BaseBoardInfo.productName <= RawStrings.Length) + Console.WriteLine("Product name: " + RawStrings[SMBIOS.BaseBoardInfo.productName - 1]); + + if (SMBIOS.BaseBoardInfo.version > 0 && SMBIOS.BaseBoardInfo.version <= RawStrings.Length) + Console.WriteLine("Version: " + RawStrings[SMBIOS.BaseBoardInfo.version - 1]); + + if (SMBIOS.BaseBoardInfo.serialNumber > 0 && + SMBIOS.BaseBoardInfo.serialNumber <= RawStrings.Length) + Console.WriteLine( + "Serial Number: " + RawStrings[SMBIOS.BaseBoardInfo.serialNumber - 1]); + break; + case SMBIOSTableType.EnclosureInformation: + SMBIOS.EnclosureInfo = RSMB.ToStruct(pos); + RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); + + Console.WriteLine("EnclosureInformation"); + + Console.ForegroundColor = ConsoleColor.Yellow; + + if (SMBIOS.EnclosureInfo.manufacturer > 0 && + SMBIOS.EnclosureInfo.manufacturer <= RawStrings.Length) + Console.WriteLine("Manufacturer: " + + RawStrings[SMBIOS.EnclosureInfo.manufacturer - 1]); + + if (SMBIOS.EnclosureInfo.version > 0 && SMBIOS.EnclosureInfo.version <= RawStrings.Length) + Console.WriteLine("Version: " + RawStrings[SMBIOS.EnclosureInfo.version - 1]); + + if (SMBIOS.EnclosureInfo.serialNumber > 0 && + SMBIOS.EnclosureInfo.serialNumber <= RawStrings.Length) + Console.WriteLine( + "Serial Number: " + RawStrings[SMBIOS.EnclosureInfo.serialNumber - 1]); + + if (SMBIOS.EnclosureInfo.assetTagNumber > 0 && + SMBIOS.EnclosureInfo.assetTagNumber <= RawStrings.Length) + Console.WriteLine("Asset Tag Number: " + + RawStrings[SMBIOS.EnclosureInfo.assetTagNumber - 1]); + break; + case SMBIOSTableType.ProcessorInformation: + SMBIOS.ProcessorInfo = RSMB.ToStruct(pos); + RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); + + Console.WriteLine("ProcessorInformation"); + + Console.ForegroundColor = ConsoleColor.Yellow; + + if (SMBIOS.ProcessorInfo.processorManufacturer > 0 && + SMBIOS.ProcessorInfo.processorManufacturer <= RawStrings.Length) + Console.WriteLine("Manufacturer: " + + RawStrings[SMBIOS.ProcessorInfo.processorManufacturer - 1]); + + if (SMBIOS.ProcessorInfo.processorType > 0 && + SMBIOS.ProcessorInfo.processorType <= RawStrings.Length) + Console.WriteLine("Model: " + RawStrings[SMBIOS.ProcessorInfo.processorType - 1]); + + if (SMBIOS.ProcessorInfo.processorFamily > 0 && + SMBIOS.ProcessorInfo.processorFamily <= RawStrings.Length) + Console.WriteLine("Family: " + RawStrings[SMBIOS.ProcessorInfo.processorFamily - 1]); + + if (SMBIOS.ProcessorInfo.serialNumber > 0 && + SMBIOS.ProcessorInfo.serialNumber <= RawStrings.Length) + Console.WriteLine( + "Serial Number: " + RawStrings[SMBIOS.ProcessorInfo.serialNumber - 1]); + + if (SMBIOS.ProcessorInfo.assetTag > 0 && + SMBIOS.ProcessorInfo.assetTag <= RawStrings.Length) + Console.WriteLine("Asset Tag: " + RawStrings[SMBIOS.ProcessorInfo.assetTag - 1]); + break; + case SMBIOSTableType.CacheInformation: + SMBIOS.CacheInfo = RSMB.ToStruct(pos); + RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); + + Console.WriteLine("CacheInformation [" + RawStrings[0] + "]"); + + Console.ForegroundColor = ConsoleColor.Yellow; + + Console.WriteLine("Installed Size: " + SMBIOS.CacheInfo.installedSize); + + Console.WriteLine("Maximum CacheSize: " + SMBIOS.CacheInfo.maximumCacheSize); + break; + default: + Console.WriteLine(tableEntry.header.type); + RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); + break; + } + } + } + } + } + + var tableIndex = 0; + foreach (var biosTable in EnumerateTables(BiosFirmwareTableProvider.FIRM)) + { + var FIRM = GetTable(BiosFirmwareTableProvider.FIRM, biosTable); + + File.WriteAllBytes("BIOS." + BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(FIRM), 0).Replace("-", "") + ".FIRM" + (tableIndex++) + ".bin", FIRM); + + } + + + Console.WriteLine(); + + Console.ForegroundColor = ConsoleColor.White; + + Console.WriteLine("[CPU]"); + + // Get CPU Information (Count, ID) // + byte[] code_x86 = { + 0x55, 0x89, 0xe5, 0x57, 0x8b, 0x7d, 0x10, 0x6a, 0x01, 0x58, 0x53, 0x0f, 0xa2, 0x89, 0x07, 0x89, 0x57, + 0x04, 0x5b, 0x5f, 0x89, 0xec, 0x5d, 0xc2, 0x10, 0x00 + }; + byte[] code_x64 = { + 0x53, 0x48, 0xc7, 0xc0, 0x01, 0x00, 0x00, 0x00, 0x0f, 0xa2, 0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, + 0x5b, 0xc3 + }; + var CPUID = new byte[8]; + byte[] asmCode; + int protect; + if (IntPtr.Size == 8) asmCode = code_x64; + else asmCode = code_x86; + var asmSize = new IntPtr(asmCode.Length); + if (!VirtualProtect(asmCode, asmSize, 0x40, out protect)) + Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); + asmSize = new IntPtr(CPUID.Length); + if (CallWindowProcW(asmCode, IntPtr.Zero, 0, CPUID, asmSize) == IntPtr.Zero) return; + var RegKey = + Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor"); + var ProcessorName = RegKey.OpenSubKey("0").GetValue("ProcessorNameString").ToString(); + var CPUIdentifier = RegKey.OpenSubKey("0").GetValue("Identifier").ToString(); + var ProcessorCores = RegKey.GetSubKeyNames(); + + + Console.ForegroundColor = ConsoleColor.Green; + + Console.WriteLine(ProcessorName + ", " + CPUIdentifier); + + Console.ForegroundColor = ConsoleColor.Yellow; + + Console.WriteLine("> Processor Cores: " + ProcessorCores.Length); + + Console.WriteLine("> ID: " + BitConverter.ToString(CPUID, 0).Replace("-", "")); + + Binary.Write(ProcessorName); + Binary.Write(CPUIdentifier); + Binary.Write(ProcessorCores.Length); + Binary.Write(CPUID); + + + Console.WriteLine(); + + Console.ForegroundColor = ConsoleColor.White; + + Console.WriteLine("[DRIVES]"); + + // Get HDD Information // + foreach (var drive in Environment.GetLogicalDrives()) + { + var disk = GetPhysicalDisk(drive); + if (disk.RemovableMedia) continue; + + Console.ForegroundColor = ConsoleColor.Green; + + Console.WriteLine("Disk: " + drive); + + Console.ForegroundColor = ConsoleColor.Yellow; + + Console.WriteLine("> Model: " + disk.Model + ", Firmware: " + disk.Firmware + "\n> Serial: " + + disk.SerialNumber); + if (string.IsNullOrEmpty(disk.Model) || string.IsNullOrEmpty(disk.Firmware)) continue; + Binary.Write(disk.Model); + Binary.Write(disk.Firmware); + Binary.Write(disk.SerialNumber); + } + + + Console.WriteLine(); + + Console.ForegroundColor = ConsoleColor.White; + + Console.WriteLine("[VIDEO]"); + + // Get VIDEO Information // + try + { + var display = new DISPLAY_DEVICE(); + display.structSize = Marshal.SizeOf(display); + for (uint i = 0; EnumDisplayDevices(null, i, ref display, 0); i++) + { + if (display.DeviceString == null) continue; + if (display.StateFlags.HasFlag(DisplayDeviceStateFlags.PrimaryDevice)) + { + + Console.ForegroundColor = ConsoleColor.Green; + + Console.WriteLine(display.DeviceString); + + Console.ForegroundColor = ConsoleColor.Yellow; + + Console.WriteLine("DeviceID: " + display.DeviceID); + + Console.WriteLine("State Flags: " + display.StateFlags); + Binary.Write(display.DeviceString); + if (display.DeviceID != null) Binary.Write(display.DeviceID); + } + } + } + catch (Exception) + { + /* Ignore all exceptions of detecting video */ + } + + // Seek Stream Origin To Beginning and Compute Binary Buffer to MD5 // + Binary.BaseStream.Seek(0, SeekOrigin.Begin); + _MD5 = new MD5CryptoServiceProvider().ComputeHash(Binary.BaseStream); + // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA1 // + Binary.BaseStream.Seek(0, SeekOrigin.Begin); + _SHA1 = new SHA1CryptoServiceProvider().ComputeHash(Binary.BaseStream); + // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA256 // + Binary.BaseStream.Seek(0, SeekOrigin.Begin); + _SHA256 = new SHA256CryptoServiceProvider().ComputeHash(Binary.BaseStream); + // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA512 // + Binary.BaseStream.Seek(0, SeekOrigin.Begin); + _SHA512 = new SHA512CryptoServiceProvider().ComputeHash(Binary.BaseStream); + } + + Console.ResetColor(); + } + + public byte[] MD5 + { + get + { + if (_MD5 == null || _MD5.Length < 16) return new byte[0]; + return _MD5; + } + } + + public byte[] SHA1 + { + get + { + if (_SHA1 == null || _SHA1.Length < 16) return new byte[0]; + return _SHA1; + } + } + + public byte[] SHA256 + { + get + { + if (_SHA256 == null || _SHA256.Length < 16) return new byte[0]; + return _SHA256; + } + } + + public byte[] SHA512 + { + get + { + if (_SHA512 == null || _SHA512.Length < 16) return new byte[0]; + return _SHA512; + } + } + + public string MD5String + { + get + { + if (_MD5 == null || _MD5.Length < 16) return ""; + return BitConverter.ToString(_MD5, 0).Replace("-", ""); + } + } + + public string SHA1String + { + get + { + if (_SHA1 == null || _SHA1.Length < 16) return ""; + return BitConverter.ToString(_SHA1, 0).Replace("-", ""); + } + } + + public string SHA256String + { + get + { + if (_SHA256 == null || _SHA256.Length < 16) return ""; + return BitConverter.ToString(_SHA256, 0).Replace("-", ""); + } + } + + public string SHA512String + { + get + { + if (_SHA512 == null || _SHA512.Length < 16) return ""; + return BitConverter.ToString(_SHA512, 0).Replace("-", ""); + } + } + } +} diff --git a/AlphaFS/Device/Test2.cs b/AlphaFS/Device/Test2.cs new file mode 100644 index 000000000..306b7c121 --- /dev/null +++ b/AlphaFS/Device/Test2.cs @@ -0,0 +1,252 @@ +//using Microsoft.VisualBasic; + +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Security; +using Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32.Filesystem +{ + public static class IOCtl + { + private const int GENERIC_READ = unchecked((int) 0x80000000); + private const int FILE_SHARE_READ = 1; + private const int FILE_SHARE_WRITE = 2; + private const int OPEN_EXISTING = 3; + + //private enum Partition : byte + //{ + // ENTRY_UNUSED = 0, + // FAT_12 = 1, + // XENIX_1 = 2, + // XENIX_2 = 3, + // FAT_16 = 4, + // EXTENDED = 5, + // HUGE = 6, + // IFS = 7, + // OS2BOOTMGR = 0xa, + // FAT32 = 0xb, + // FAT32_XINT13 = 0xc, + // XINT13 = 0xe, + // XINT13_EXTENDED = 0xf, + // PREP = 0x41, + // LDM = 0x42, + // UNIX = 0x63 + //} + + [SuppressUnmanagedCodeSecurity] + private class NativeMethods + { + + [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern SafeFileHandle CreateFile( + string fileName, + int desiredAccess, + int shareMode, + IntPtr securityAttributes, + int creationDisposition, + int flagsAndAttributes, + IntPtr hTemplateFile); + + [DllImport("kernel32", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool DeviceIoControl( + SafeFileHandle hVol, + Filesystem.NativeMethods.IoControlCode controlCode, + IntPtr inBuffer, + uint inBufferSize, + IntPtr outBuffer, + uint outBufferSize, + ref uint bytesReturned, + IntPtr overlapped); + + } + + + + + + + + + public static void Main() + { + SendIoCtlDiskGetDriveLayoutEx(0); + SendIoCtlDiskGetDriveLayoutEx(1); + //SendIoCtlDiskGetDriveLayoutEx(2); + } + + + private static void SendIoCtlDiskGetDriveLayoutEx(int PhysicalDrive) + { + + var lie = default(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX); + + Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies = null; + + using (var hDevice = NativeMethods.CreateFile("\\\\.\\PHYSICALDRIVE" + PhysicalDrive, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero)) + { + if (hDevice.IsInvalid) + throw new Win32Exception(); + + + // We don't know how many partitions there are, so we have to use a blob of memory... + var numPartitions = 1; + var done = false; + + do + { + // 48 = the number of bytes in DRIVE_LAYOUT_INFORMATION_EX up to + // the first PARTITION_INFORMATION_EX in the array. + // And each PARTITION_INFORMATION_EX is 144 bytes. + var outBufferSize = 48 + numPartitions * 144; + var blob = default(IntPtr); + uint bytesReturned = 0; + + try + { + blob = Marshal.AllocHGlobal(outBufferSize); + + var result = NativeMethods.DeviceIoControl(hDevice, Filesystem.NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, blob, (uint) outBufferSize, ref bytesReturned, IntPtr.Zero); + + // We expect that we might not have enough room in the output buffer. + if (result == false) + { + // If the buffer wasn't too small, then something else went wrong. + if (Marshal.GetLastWin32Error() != Win32Errors.ERROR_INSUFFICIENT_BUFFER) + throw new Win32Exception(); + // We need more space on the next loop. + numPartitions += 1; + } + else + { + // We got the size right, so stop looping. + done = true; + + // Do something with the data here - we'll free the memory before we leave the loop. + // First we grab the DRIVE_LAYOUT_INFORMATION_EX, it's at the start of the blob of memory: + lie = (Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX) Marshal.PtrToStructure(blob, typeof(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); + + // Then loop and add the PARTITION_INFORMATION_EX structures to an array. + pies = new Filesystem.NativeMethods.PARTITION_INFORMATION_EX[lie.PartitionCount]; + + for (var i = 0; i <= lie.PartitionCount - 1; i++) + { + // Where is this structure in the blob of memory? + var offset = new IntPtr(blob.ToInt64() + 48 + i * 144); + + pies[i] = (Filesystem.NativeMethods.PARTITION_INFORMATION_EX) Marshal.PtrToStructure(offset, typeof(Filesystem.NativeMethods.PARTITION_INFORMATION_EX)); + } + } + } + finally + { + Marshal.FreeHGlobal(blob); + } + } while (!done); + } + + + DumpInfo(lie, pies); + } + + + private static bool IsPart0Aligned(Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies) + { + try + { + return pies[0].StartingOffset % 4096 == 0; + } + catch + { + return false; + } + } + + + private static void DumpInfo(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX lie, Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies) + { + //var aaa = new PartitionTypeGuid(PartitionType.LdmMetaDataGuid); + + + Console.WriteLine("\n\nPart 0 aligned:" + IsPart0Aligned(pies)); + + + Console.WriteLine("Partition Style: {0}", lie.PartitionStyle); + Console.WriteLine("Partition Count: {0}", lie.PartitionCount); + + switch (lie.PartitionStyle) + { + case PartitionStyle.Mbr: + Console.WriteLine("Mbr Signature: {0}", lie.Mbr.Signature); + break; + case PartitionStyle.Gpt: + Console.WriteLine("Gpt DiskId : {0}", lie.Gpt.DiskId); + Console.WriteLine("Gpt StartingUsableOffset: {0}", lie.Gpt.StartingUsableOffset); + Console.WriteLine("Gpt UsableLength : {0}", lie.Gpt.UsableLength); + Console.WriteLine("Gpt UsableLength : {0}", Utils.UnitSizeToText(lie.Gpt.UsableLength)); + Console.WriteLine("Gpt MaxPartitionCount : {0}", lie.Gpt.MaxPartitionCount); + break; + + default: + Console.WriteLine("RAW!"); + break; + } + + + + + for (var i = 0; i <= lie.PartitionCount - 1; i++) + { + var storagePartitionInfo = new StoragePartitionInfo(); + + Console.WriteLine(); + Console.WriteLine(); + Console.WriteLine("Partition {0} info...", i + 1); + Console.WriteLine("-------------------"); + + + var _with1 = pies[i]; + Console.WriteLine("Partition style : {0}", (PartitionStyle) _with1.PartitionStyle); + Console.WriteLine("Starting offset : {0}", _with1.StartingOffset); + Console.WriteLine("Partition length : {0}", _with1.PartitionLength); + Console.WriteLine("Partition length : {0}", Utils.UnitSizeToText(_with1.PartitionLength)); + Console.WriteLine("Partition number : {0}", _with1.PartitionNumber); + Console.WriteLine("Rewrite partition: {0}", _with1.RewritePartition); + + + switch ((PartitionStyle) _with1.PartitionStyle) + { + case PartitionStyle.Mbr: + var _with2 = _with1.Mbr; + Console.WriteLine("Mbr PartitionType - raw value: {0}", _with2.PartitionType); + + //Console.WriteLine("Mbr PartitionType - validNTFT: {0}", _with2.IsValidNTFT()); + + //if (_with2.IsValidNTFT()) + // Console.WriteLine("Mbr PartitionType - ntft: {0}", _with2.IsNTFT()); + + //Console.WriteLine("Mbr PartitionType - decoded: {0}", _with2.GetPartition()); + + Console.WriteLine("Mbr BootIndicator : {0}", _with2.BootIndicator); + Console.WriteLine("Mbr RecognizedPartition: {0}", _with2.RecognizedPartition); + Console.WriteLine("Mbr HiddenSectors : {0}", _with2.HiddenSectors); + break; + + case PartitionStyle.Gpt: + var _with3 = _with1.Gpt; + Console.WriteLine("Gpt PartitionType: {0}", _with3.PartitionType); + Console.WriteLine("Gpt PartitionId : {0}", _with3.PartitionId); + Console.WriteLine("Gpt Attributes : {0}", (PartitionAttributes) _with3.Attributes); + Console.WriteLine("Gpt Name : {0}", _with3.Name); + break; + + case PartitionStyle.Raw: + Console.WriteLine("RAW!"); + break; + } + } + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs index 23ef6c2e7..69f436f46 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs @@ -31,16 +31,16 @@ internal static partial class NativeMethods /// Minimum supported server: Windows Server 2003 [desktop apps only] /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct DISK_GEOMETRY_EX + public struct DISK_GEOMETRY_EX { /// A structure. public DISK_GEOMETRY Geometry; /// The disk size, in bytes. - [MarshalAs(UnmanagedType.U8)] public ulong DiskSize; + [MarshalAs(UnmanagedType.U8)] public readonly ulong DiskSize; /// Any additional data. - [MarshalAs(UnmanagedType.I1)] public byte Data; + [MarshalAs(UnmanagedType.I1)] public readonly byte Data; } } } diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs index 703a31efc..6160bc574 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs @@ -25,39 +25,25 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - public const int PartitionEntriesCount = 10; - - /// Contains extended information about a drive's partitions. /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] internal struct DRIVE_LAYOUT_INFORMATION_EX { - /// The style of the partitions on the drive enumerated by the enumeration. - public readonly PARTITION_STYLE PartitionStyle; + /// The style of the partitions on the drive enumerated by the enumeration. + [FieldOffset(0)] [MarshalAs(UnmanagedType.U4)] + public readonly PartitionStyle PartitionStyle; /// The number of partitions on the drive. On hard disks with the MBR layout, this value will always be a multiple of 4. - [MarshalAs(UnmanagedType.U4)] public readonly uint PartitionCount; + [FieldOffset(4)] [MarshalAs(UnmanagedType.U4)] + public readonly uint PartitionCount; - public DRIVE_LAYOUT_INFORMATION_UNION DriveLayoutInformation; - - /// A variable-sized array of structures, one structure for each partition on the drive. - [MarshalAs(UnmanagedType.ByValArray, SizeConst = PartitionEntriesCount)] - public readonly PARTITION_INFORMATION_EX[] PartitionEntry; - } - - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct DRIVE_LAYOUT_INFORMATION_UNION - { - /// A structure containing information about the master boot record type partitioning on the drive. - public DRIVE_LAYOUT_INFORMATION_MBR Mbr; + [FieldOffset(8)] public DRIVE_LAYOUT_INFORMATION_MBR Mbr; - /// A structure containing information about the GUID disk partition type partitioning on the drive. - public DRIVE_LAYOUT_INFORMATION_GPT Gpt; + [FieldOffset(8)] public DRIVE_LAYOUT_INFORMATION_GPT Gpt; } } } diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs index b784e557d..72be49f56 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs @@ -38,13 +38,13 @@ internal struct DRIVE_LAYOUT_INFORMATION_GPT public Guid DiskId; /// The starting byte offset of the first usable block. - [MarshalAs(UnmanagedType.U8)] public ulong StartingUsableOffset; + [MarshalAs(UnmanagedType.U8)] public readonly ulong StartingUsableOffset; /// The size of the usable blocks on the disk, in bytes. - [MarshalAs(UnmanagedType.U8)] public ulong UsableLength; + [MarshalAs(UnmanagedType.U8)] public readonly ulong UsableLength; /// The maximum number of partitions that can be defined in the usable block. - [MarshalAs(UnmanagedType.U4)] public uint MaxPartitionCount; + [MarshalAs(UnmanagedType.U4)] public readonly uint MaxPartitionCount; } } } diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs index 139ba3ebe..8ece0fcaf 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs @@ -31,10 +31,10 @@ internal static partial class NativeMethods /// Minimum supported server: Windows Server 2003 [desktop apps only] /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct DRIVE_LAYOUT_INFORMATION_MBR + internal struct DRIVE_LAYOUT_INFORMATION_MBR { /// The signature of the drive. - [MarshalAs(UnmanagedType.U8)] public ulong Signature; + [MarshalAs(UnmanagedType.U8)] public readonly ulong Signature; } } } diff --git a/AlphaFS/Filesystem/Native Other/DiskPartitionTypes.cs b/AlphaFS/Filesystem/Native Other/DiskPartitionTypes.cs deleted file mode 100644 index d99e3f8c9..000000000 --- a/AlphaFS/Filesystem/Native Other/DiskPartitionTypes.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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.Filesystem -{ - internal static partial class NativeMethods - { - /// The following table identifies the valid partition types that are used by disk drivers. - /// - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// - internal enum DiskPartitionTypes - { - /// An unused entry partition. - PARTITION_ENTRY_UNUSED = 0, - - /// A FAT12 file system partition. - PARTITION_FAT_12 = 1, - - PARTITION_XENIX_1 = 2, - PARTITION_XENIX_2 = 3, - - /// A FAT16 file system partition. - PARTITION_FAT_16 = 4, - - /// An extended partition. - PARTITION_EXTENDED = 5, - - PARTITION_HUGE = 6, - - /// An IFS partition. - PARTITION_IFS = 7, - - /// A FAT32 file system partition. - PARTITION_FAT32 = 11, - - PARTITION_FAT32_XINT13 = 12, - PARTITION_XINT13 = 14, - PARTITION_XINT13_EXTENDED = 15, - PARTITION_PREP = 65, - - /// A logical disk manager (LDM) partition. - PARTITION_LDM = 66, - - PARTITION_UNIX = 99, - - /// An NTFT partition. - PARTITION_NTFT = 128, - } - } -} diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs index ac59c8690..509ef156d 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs @@ -30,33 +30,33 @@ internal static partial class NativeMethods /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] internal struct PARTITION_INFORMATION_EX { - /// The format of the partition. - public PARTITION_STYLE PartitionStyle; + /// The format of the partition. For a list of values, see . + [FieldOffset(0)] public readonly PARTITION_STYLE PartitionStyle; /// The starting offset of the partition. - [MarshalAs(UnmanagedType.U8)] public long StartingOffset; + [FieldOffset(8)] [MarshalAs(UnmanagedType.U8)] + public readonly ulong StartingOffset; - /// The size of the partition, in bytes. - [MarshalAs(UnmanagedType.U8)] public long PartitionLength; + /// The starting offset of the partition. + [FieldOffset(16)] [MarshalAs(UnmanagedType.U8)] + public readonly ulong PartitionLength; /// The number of the partition (1-based). - [MarshalAs(UnmanagedType.U4)] public uint PartitionNumber; + [FieldOffset(24)] [MarshalAs(UnmanagedType.U4)] + public readonly uint PartitionNumber; /// If this member is TRUE, the partition is rewritable. The value of this parameter should be set to TRUE. - [MarshalAs(UnmanagedType.Bool)] public bool RewritePartition; - - //public PARTITION_INFORMATION_UNION PartitionInformation; - } + [FieldOffset(28)] [MarshalAs(UnmanagedType.U1)] + public readonly bool RewritePartition; + /// A structure that specifies partition information specific to master boot record (MBR) disks. The MBR partition format is the standard AT-style format. + [FieldOffset(32)] public readonly PARTITION_INFORMATION_MBR Mbr; - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct PARTITION_INFORMATION_UNION - { - public PARTITION_INFORMATION_MBR Mbr; - public PARTITION_INFORMATION_GPT Gpt; + /// A structure that specifies partition information specific to GUID partition table (GPT) disks. The GPT format corresponds to the EFI partition format. + [FieldOffset(32)] public readonly PARTITION_INFORMATION_GPT Gpt; } } } diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs index 5280cacd4..1626c7bdb 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs @@ -31,21 +31,24 @@ internal static partial class NativeMethods /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] internal struct PARTITION_INFORMATION_GPT { - /// A GUID that identifies the partition type. - public Guid PartitionType; + /// A GUID that identifies the partition type. + /// Each partition type that the EFI specification supports is identified by its own GUID, which is published by the developer of the partition. + /// + [FieldOffset(0)] public readonly Guid PartitionType; /// The GUID of the partition. - public Guid PartitionId; + [FieldOffset(16)] public readonly Guid PartitionId; /// The Extensible Firmware Interface (EFI) attributes of the partition. - [MarshalAs(UnmanagedType.U8)] public EFIPartitionAttributes Attributes; + [FieldOffset(32)] [MarshalAs(UnmanagedType.U8)] + public readonly PartitionAttributes Attributes; /// A wide-character string that describes the partition. - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] - public string Name; + [FieldOffset(40)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] + public readonly string Name; } } } diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs index b2c0dbf86..798f1efc8 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs @@ -31,19 +31,19 @@ internal static partial class NativeMethods /// Minimum supported server: Windows Server 2003 [desktop apps only] /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct PARTITION_INFORMATION_MBR + internal struct PARTITION_INFORMATION_MBR { - /// The type of partition. - [MarshalAs(UnmanagedType.I1)] public DiskPartitionTypes PartitionType; + /// The type of partition. For a list of values, see . + [MarshalAs(UnmanagedType.U1)] public readonly DiskPartitionTypes PartitionType; /// If the member is TRUE, the partition is a boot partition. When this structure is used with the IOCTL_DISK_SET_PARTITION_INFO_EX control code, the value of this parameter is ignored. - [MarshalAs(UnmanagedType.Bool)] public bool BootIndicator; + [MarshalAs(UnmanagedType.Bool)] public readonly bool BootIndicator; /// If this member is TRUE, the partition is of a recognized type. When this structure is used with the IOCTL_DISK_SET_PARTITION_INFO_EX control code, the value of this parameter is ignored. - [MarshalAs(UnmanagedType.Bool)] public bool RecognizedPartition; + [MarshalAs(UnmanagedType.Bool)] public readonly bool RecognizedPartition; /// The number of hidden sectors to be allocated when the partition table is created. - [MarshalAs(UnmanagedType.U4)] public uint HiddenSectors; + [MarshalAs(UnmanagedType.U4)] public readonly uint HiddenSectors; } } } diff --git a/AlphaFS/Filesystem/Native Other/EFIPartitionAttributes.cs b/AlphaFS/Filesystem/Native Other/PartitionAttributes.cs similarity index 69% rename from AlphaFS/Filesystem/Native Other/EFIPartitionAttributes.cs rename to AlphaFS/Filesystem/Native Other/PartitionAttributes.cs index 14729d911..227226052 100644 --- a/AlphaFS/Filesystem/Native Other/EFIPartitionAttributes.cs +++ b/AlphaFS/Filesystem/Native Other/PartitionAttributes.cs @@ -26,14 +26,22 @@ namespace Alphaleonis.Win32.Filesystem internal static partial class NativeMethods { [Flags] - public enum EFIPartitionAttributes : ulong + public enum PartitionAttributes : ulong { + /// If this attribute is set, the partition is required by a Computer to function properly. GPT_ATTRIBUTE_PLATFORM_REQUIRED = 0x0000000000000001, - LegacyBIOSBootable = 0x0000000000000004, - GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER = 0x8000000000000000, - GPT_BASIC_DATA_ATTRIBUTE_HIDDEN = 0x4000000000000000, + + /// If this attribute is set, the partition is read-only. + GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY = 0x1000000000000000, + + /// If this attribute is set, the partition is a shadow copy of another partition. GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY = 0x2000000000000000, - GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY = 0x1000000000000000 + + /// If this attribute is set, the partition is not detected by the Mount Manager. + GPT_BASIC_DATA_ATTRIBUTE_HIDDEN = 0x4000000000000000, + + /// If this attribute is set, the partition does not receive a drive letter by default when the disk is moved to another Computer or when the disk is seen for the first time by a Computer. + GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER = 0x8000000000000000 } } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionTypes.cs b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionTypes.cs new file mode 100644 index 000000000..98781175a --- /dev/null +++ b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionTypes.cs @@ -0,0 +1,74 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// The following table identifies the valid partition types that are used by disk drivers. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + public enum DiskPartitionTypes : byte + { + /// An unused entry partition. + UnusedEntry = 0, + + /// A FAT12 file system partition. + FAT12 = 1, + + XENIX1 = 2, + XENIX2 = 3, + + /// A FAT16 file system partition. + FAT16 = 4, + + /// An extended partition. + Extended = 5, + + Huge = 6, + + /// An IFS (Installable File System) partition. + IFS = 7, + + /// A FAT32 file system partition. + FAT32 = 11, + + FAT32XINT13 = 12, + XINT13 = 14, + XINT13Extended = 15, + + + /// A PREP (Power PC Reference Platform) partition. + Prep = 65, + + /// An LDM (Logical Disk Manager) partition. + LDF = 66, + + /// A UNIX partition. + UNIX = 99, + + /// An NTFT partition. + NTFT = 128, + + /// A valid NTFT partition. + ValidNTFT = 192, + } +} diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionAttributes.cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionAttributes.cs new file mode 100644 index 000000000..c3e72ab4e --- /dev/null +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionAttributes.cs @@ -0,0 +1,49 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + [Flags] + public enum PartitionAttributes : ulong + { + /// None. + None = 0, + + /// If this attribute is set, the partition is required by a Computer to function properly. + PlatformRequired = NativeMethods.PartitionAttributes.GPT_ATTRIBUTE_PLATFORM_REQUIRED, + + LegacyBIOSBootable = 0x0000000000000004, + + /// If this attribute is set, the partition is read-only. + ReadOnly = NativeMethods.PartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY, + + /// If this attribute is set, the partition is a shadow copy of another partition. + ShadowCopy = NativeMethods.PartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY, + + /// If this attribute is set, the partition is not detected by the Mount Manager. + Hidden = NativeMethods.PartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_HIDDEN, + + /// If this attribute is set, the partition does not receive a drive letter by default when the disk is moved to another Computer or when the disk is seen for the first time by a Computer. + NoDriveletter = NativeMethods.PartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER + } +} diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs new file mode 100644 index 000000000..8f58b2627 --- /dev/null +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs @@ -0,0 +1,40 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Represents the format of a partition. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + public enum PartitionStyle + { + /// Master boot record (MBR) format. This corresponds to standard AT-style MBR partitions. + Mbr = NativeMethods.PARTITION_STYLE.PARTITION_STYLE_MBR, + + /// GUID Partition Table (GPT) format. + Gpt = NativeMethods.PARTITION_STYLE.PARTITION_STYLE_GPT, + + /// Partition not formatted in either of the recognized formats; MBR or GPT. + Raw = NativeMethods.PARTITION_STYLE.PARTITION_STYLE_RAW + } +} diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs new file mode 100644 index 000000000..fa48df629 --- /dev/null +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs @@ -0,0 +1,229 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace Alphaleonis.Win32.Filesystem +{ + public enum PartitionType + { + /// PARTITION_ENTRY_UNUSED_GUID: There is no partition. + /// This value can be set for basic and dynamic disks. + /// + [Description("00000000-0000-0000-0000-000000000000")] + UnusedGuid, + + /// PARTITION_BASIC_DATA_GUID: The data partition type that is created and recognized by Windows. + /// + /// This value can be set only for basic disks, with one exception. + /// Only partitions of this type can be assigned drive letters, receive volume GUID paths, host mounted folders (also called volume mount points), and be enumerated by calls to FindFirstVolume and FindNextVolume. + /// + /// + [Description("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7")] + BasicDataGuid, + + /// PARTITION_LDM_DATA_GUID: The partition is an LDM data partition on a dynamic disk. + /// This value can be set only for dynamic disks. + /// + [Description("AF9B60A0-1431-4F62-BC68-3311714A69AD")] + LdmDataGuid, + + /// PARTITION_LDM_METADATA_GUID: The partition is a Logical Disk Manager (LDM) metadata partition on a dynamic disk. + /// This value can be set only for dynamic disks. + /// + [Description("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3")] + LdmMetaDataGuid, + + /// PARTITION_MSFT_RECOVERY_GUID: The partition is a Microsoft recovery partition. + /// This value can be set for basic and dynamic disks. + /// + [Description("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC")] + MsftRecoveryguid, + + /// PARTITION_MSFT_RESERVED_GUID: The partition is a Microsoft reserved partition. + /// This value can be set for basic and dynamic disks. + /// + [Description("E3C9E316-0B5C-4DB8-817D-F92DF00215AE")] + MsftReservedGuid, + + /// PARTITION_SYSTEM_GUID: The partition is an EFI system partition. + /// This value can be set for basic and dynamic disks. + /// + [Description("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")] + SystemGuid + } + + + ///// A wrapper class which represents the possible media types for DirectShow. Since a MediaType is a Guid, a simple enum couldn't be used. + //internal class PartitionTypeGuid : AbstractGuidEnum + //{ + // /// Creates a new PartitionTypeGuid instance, wrapping the given GUID. + // /// The GUID to wrap. + // public PartitionTypeGuid(Guid guid) : base(guid) + // { + // } + + + // public PartitionTypeGuid(PartitionType partitionType) : base(partitionType) + // { + // } + + + // protected override void FillTypeList(Dictionary typeList) + // { + // typeList.Add(NativeMethods.PartitionType.PARTITION_ENTRY_UNUSED_GUID, PartitionType.UnusedGuid); + + // typeList.Add(NativeMethods.PartitionType.PARTITION_BASIC_DATA_GUID, PartitionType.BasicDataGuid); + + // typeList.Add(NativeMethods.PartitionType.PARTITION_LDM_DATA_GUID, PartitionType.LdmDataGuid); + + // typeList.Add(NativeMethods.PartitionType.PARTITION_LDM_METADATA_GUID, PartitionType.LdmMetaDataGuid); + + // typeList.Add(NativeMethods.PartitionType.PARTITION_MSFT_RECOVERY_GUID, PartitionType.MsftRecoveryguid); + + // typeList.Add(NativeMethods.PartitionType.PARTITION_MSFT_RESERVED_GUID, PartitionType.MsftReservedGuid); + + // typeList.Add(NativeMethods.PartitionType.PARTITION_SYSTEM_GUID, PartitionType.SystemGuid); + // } + //} + + + ///// An abstract class to represent a set of GUIDs as an enum. + ///// An enum to use for the type to expose. + //internal abstract class AbstractGuidEnum + //{ + // /// The internal GUID. + // public Guid Guid { get; private set; } + + + // /// The enum type for this GUID. + // public T Type { get; private set; } + + + // /// Specifies whether the GUID is known as a specific type or not. + // public bool IsKnownType { get; private set; } + + + // /// List matching GUIDs with the enum types. + // private static Dictionary _typeList; + + + // /// Create a new GUID enum wrapping the given GUID. + // /// + // protected AbstractGuidEnum(Guid guid) + // { + // Guid = guid; + + // IsKnownType = IsGuidKnownType(guid); + + // if (IsKnownType) + // Type = GetType(guid); + // } + + + // /// Create a new GUID enum for the specified type. + // /// + // protected AbstractGuidEnum(T type) + // { + // Type = type; + // Guid = GetGuid(type); + // } + + + // /// Call to make sure the list of types is initialized. + // private void InitializeTypes() + // { + // if (null == _typeList) + // { + // _typeList = new Dictionary(); + + // FillTypeList(_typeList); + // } + // } + + + // public bool IsGuidKnownType(Guid guid) + // { + // InitializeTypes(); + + // return _typeList.ContainsKey(guid); + // } + + + // /// Returns the type for a given GUID. + // /// The GUID to get the type for. + // /// The type for the given GUID. + // public T GetType(Guid type) + // { + // InitializeTypes(); + + // if (!_typeList.ContainsKey(type)) + // throw new ArgumentException("No type is defined for the given GUID.", "type"); + + // return _typeList[type]; + // } + + + // /// Return the guid for a given type. + // /// The Type to get the Guid for. + // /// The Guid for the given type. + // /// Thrown when no Guid exists for the given type. + // private Guid GetGuid(T type) + // { + // InitializeTypes(); + + + // try + // { + // return _typeList.Keys.First(guid => _typeList[guid].Equals(type)); + // } + // catch (InvalidOperationException) + // { + // throw new InvalidCastException("No Guid exists for the given type."); + // } + // } + + + // public override bool Equals(object obj) + // { + // if (!(obj is AbstractGuidEnum)) + // return false; + + // AbstractGuidEnum guidObj = obj as AbstractGuidEnum; + + // return Guid.Equals(guidObj.Guid); + // } + + + // public override int GetHashCode() + // { + // unchecked + // { + // return Guid.GetHashCode(); + // } + // } + + + // /// Fill up the list which matches GUIDs to the desired enum types. + // /// + // protected abstract void FillTypeList(Dictionary typeList); + //} +} From 6541b4dce798b704c5a119c39130c8ca863f9264 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 23 Feb 2018 18:47:20 +0100 Subject: [PATCH 055/133] Fixed unit test utils. --- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 12 +- .../UnitTest Utility/InputPaths.cs | 14 +- .../UnitTest Utility/UnitTestConstants.cs | 250 +----------------- 3 files changed, 18 insertions(+), 258 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index acefcef5b..9bb59d46c 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -320,12 +320,11 @@ - - - + + @@ -335,12 +334,6 @@ - - - - - - @@ -349,6 +342,7 @@ + diff --git a/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs b/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs index 4fdddcd0e..1f650b3ba 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -35,6 +35,18 @@ public static partial class UnitTestConstants public static readonly string SysDrive = Environment.GetEnvironmentVariable("SystemDrive"); + public static readonly string MyStream = "ӍƔŞtrëƛɱ-" + GetRandomFileNameWithDiacriticCharacters(); + public static readonly string MyStream2 = "myStreamTWO-" + GetRandomFileNameWithDiacriticCharacters(); + public static readonly string[] AllStreams = { MyStream, MyStream2 }; + public static readonly string StreamStringContent = "(1) Computer: [" + LocalHost + "]" + "\tHello there, " + Environment.UserName; + 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) " + TextHelloWorld + " " + TextUnicode + }; + + public static readonly string[] InputPaths = { @".", diff --git a/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs b/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs index 431088d92..fe674181b 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs @@ -19,14 +19,7 @@ * THE SOFTWARE. */ -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.ComponentModel; -using System.Diagnostics; -using System.Globalization; -using System.Linq; -using System.Security.AccessControl; -using System.Text; namespace AlphaFS.UnitTest { @@ -42,9 +35,8 @@ public static partial class UnitTestConstants public const string EMspace = "\u3000"; #endif - public static readonly string LocalHost = Environment.MachineName; + /// The Computer name. public static readonly string TempFolder = Environment.GetEnvironmentVariable("Temp"); - public static readonly string SysDrive = Environment.GetEnvironmentVariable("SystemDrive"); public static readonly string SysRoot = Environment.GetEnvironmentVariable("SystemRoot"); public static readonly string SysRoot32 = System.IO.Path.Combine(SysRoot, "System32"); public static readonly string AppData = Environment.GetEnvironmentVariable("AppData"); @@ -56,245 +48,7 @@ public static partial class UnitTestConstants public const string TextHelloWorld = "Hëllõ Wørld!"; public const string TextGoodbyeWorld = "Góödbyé Wôrld!"; public const string TextUnicode = "ÛņïÇòdè; ǖŤƑ"; - - private static Stopwatch _stopWatcher; - - private static readonly string RandomName = GetRandomFileName(); - public static readonly string MyStream = "ӍƔŞtrëƛɱ-" + RandomName; - public static readonly string MyStream2 = "myStreamTWO-" + RandomName; - public static readonly string[] AllStreams = {MyStream, MyStream2}; - public static readonly string StreamStringContent = "(1) Computer: [" + LocalHost + "]" + "\tHello there, " + Environment.UserName; - public static readonly string[] StreamArrayContent = - { - "(1) The quick brown fox jumps over the lazy dog.", - "(2) Albert Einstein: \"Science is a wonderful thing if one does not have to earn one's living at it.\"", - "(3) " + TextHelloWorld + " " + TextUnicode - }; - - - #region InputPaths - - 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.GlobalRootPrefix + @"device\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\f", - SysDrive + @"\a\b\c\f.", - SysDrive + @"\a\b\c\f.t", - SysDrive + @"\a\b\c\f.tx", - SysDrive + @"\a\b\c\f.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\f", - Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.", - Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.t", - Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.tx", - Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + SysDrive + @"\a\b\c\f.txt", - - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\f", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fi", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fil", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.e", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ex", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ext", - - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\f", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fi", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fil", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.e", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ex", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ext" - }; - - #endregion // InputPaths - - #endregion // Fields - - #region Methods - - public static string StopWatcher(bool start = false) - { - if (_stopWatcher == null) - _stopWatcher = new Stopwatch(); - - if (start) - { - _stopWatcher.Restart(); - return null; - } - - _stopWatcher.Stop(); - var ms = _stopWatcher.ElapsedMilliseconds; - var elapsed = _stopWatcher.Elapsed; - - return String.Format(CultureInfo.InvariantCulture, "*Duration: [{0}] ms. ({1})", ms, elapsed); - } - - - public static string Reporter(bool onlyTime = false) - { - var lastError = new Win32Exception(); - - StopWatcher(); - - return onlyTime - ? String.Format(CultureInfo.InvariantCulture, "\t\t{0}", StopWatcher()) - : String.Format(CultureInfo.InvariantCulture, "\t{0} [{1}: {2}]", StopWatcher(), lastError.NativeErrorCode, lastError.Message); - } - - public static byte[] StringToByteArray(string str, params Encoding[] encoding) - { - var encode = encoding != null && encoding.Any() ? encoding[0] : new UTF8Encoding(true, true); - return encode.GetBytes(str); - } - - - 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); - } - - - public static void PrintUnitTestHeader(bool isNetwork) - { - Console.WriteLine("\n=== TEST {0} ===", isNetwork ? Network : Local); - } - - - public static string GetRandomFileName() - { - var randomFileName = System.IO.Path.GetRandomFileName(); - - switch (new Random().Next(0, 4)) - { - case 0: - break; - - case 1: - randomFileName = randomFileName.Replace("a", "ä"); - randomFileName = randomFileName.Replace("e", "ë"); - randomFileName = randomFileName.Replace("i", "ï"); - randomFileName = randomFileName.Replace("o", "ö"); - randomFileName = randomFileName.Replace("u", "ü"); - break; - - case 2: - randomFileName = randomFileName.Replace("a", "á"); - randomFileName = randomFileName.Replace("e", "é"); - randomFileName = randomFileName.Replace("i", "í"); - randomFileName = randomFileName.Replace("o", "ó"); - randomFileName = randomFileName.Replace("u", "ú"); - break; - - case 3: - randomFileName = randomFileName.Replace("a", "â"); - randomFileName = randomFileName.Replace("e", "ê"); - randomFileName = randomFileName.Replace("i", "î"); - randomFileName = randomFileName.Replace("o", "ô"); - randomFileName = randomFileName.Replace("u", "û"); - break; - } - - - return randomFileName; - } - - #endregion // Methods + #endregion // Fields } } From f86eb4a5d24ffb4e606db44a769e592308b2f32b Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 26 Feb 2018 23:40:56 +0100 Subject: [PATCH 056/133] -Added StoragePartitionInfo, work in progress; -Removed obsolete Directory.Copy argument; --- .../AlphaFS_Device.EnumerateDevices.cs | 21 +- .../AlphaFS_DeviceTest.cs | 9 - ...etStoragePartitionInfo_FromLogicalDrive.cs | 90 ++++ .../AlphaFS_DeviceTest.cs | 37 ++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 4 +- AlphaFS/AlphaFS.csproj | 16 +- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 77 ++- AlphaFS/Device/DeviceInfo.cs | 2 +- .../Device.GetPartitionInfo.cs | 109 ---- .../Device.GetPhysicalDriveInfo.cs | 2 +- .../Device.GetStorageAdapterInfo.cs | 2 +- .../Device.GetStoragePartitionInfo.cs | 171 +++---- AlphaFS/Device/StorageAdapterInfo.cs | 2 +- AlphaFS/Device/StorageDeviceInfo.cs | 2 +- ...nInfoGpt.cs => StorageGptPartitionInfo.cs} | 140 +++++- ...nInfoMbr.cs => StorageMbrPartitionInfo.cs} | 113 ++++- AlphaFS/Device/StoragePartitionInfo.cs | 249 +++++++--- AlphaFS/Device/Test.cs | 468 +++++++++--------- AlphaFS/Device/Test2.cs | 8 +- .../Directory Class/Directory.Copy.cs | 75 ++- .../Directory Class/Directory.Move.cs | 24 +- .../DirectoryInfo.CopyTo.cs | 2 +- .../NativeMethods.FileManagement.cs | 2 +- .../Native Other/DISK_DETECTION_INFO.cs | 51 ++ .../Native Other/DISK_EX_INT13_INFO.cs | 60 +++ .../Filesystem/Native Other/DISK_GEOMETRY.cs | 15 +- .../Native Other/DISK_GEOMETRY_EX.cs | 21 +- .../Native Other/DISK_INT13_INFO.cs | 64 +++ .../Native Other/DISK_PARTITION_INFO.cs | 56 +++ .../DRIVE_LAYOUT_INFORMATION_EX.cs | 4 +- .../Filesystem/Native Other/DiskInt13Union.cs | 47 ++ .../Filesystem/Native Other/IoControlCode.cs | 26 +- .../Native Other/STORAGE_MEDIA_TYPE.cs | 10 +- .../Structures, Enumerations/DetectionType.cs | 36 ++ .../DiskPartitionTypes.cs | 34 +- .../Structures, Enumerations/MoveOptions.cs | 6 +- .../PartitionAttributes.cs | 6 +- .../PartitionType..cs | 170 +------ .../StorageBusType.cs | 39 +- .../StorageMediaType.cs | 298 +++++++++++ .../SafeGlobalMemoryBufferHandle.cs | 7 +- .../SafeNativeMemoryBufferHandle.cs | 12 +- AlphaFS/Utils.cs | 20 + PowerShell/Enumerate-FileSystemEntryInfos.ps1 | 3 +- 44 files changed, 1664 insertions(+), 946 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs create mode 100644 AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs delete mode 100644 AlphaFS/Device/PhysicalDriveInfo/Device.GetPartitionInfo.cs rename AlphaFS/Device/{StoragePartitionInfoGpt.cs => StorageGptPartitionInfo.cs} (52%) rename AlphaFS/Device/{StoragePartitionInfoMbr.cs => StorageMbrPartitionInfo.cs} (58%) create mode 100644 AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs create mode 100644 AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs create mode 100644 AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs create mode 100644 AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs create mode 100644 AlphaFS/Filesystem/Native Other/DiskInt13Union.cs create mode 100644 AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs create mode 100644 AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs index d0dde0b84..3cbdfd028 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs @@ -21,7 +21,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Collections.Generic; using System.Linq; namespace AlphaFS.UnitTest @@ -43,7 +42,7 @@ public void AlphaFS_Device_EnumerateDevices_Local_Success() var host = UnitTestConstants.LocalHost; var classCount = 0; - foreach (var deviceClass in EnumMemberToList()) + foreach (var deviceClass in Alphaleonis.Utils.EnumToArray().OrderBy(memberName => memberName.ToString())) { Console.WriteLine(); Console.WriteLine("#{0:000}\tClass: [{1}]", ++classCount, deviceClass); @@ -57,23 +56,5 @@ public void AlphaFS_Device_EnumerateDevices_Local_Success() if (classCount == 0) Assert.Inconclusive("Nothing is enumerated, but it is expected."); } - - - private static IEnumerable EnumMemberToList() - { - 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().OrderBy(e => e.ToString()).ToList(); - var enumValList = new List(enumValArray.Count); - - enumValList.AddRange(enumValArray.Select(val => (T) Enum.Parse(enumType, val.ToString()))); - - return enumValList; - } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs index f9be2ca00..7c3e6dd41 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Filesystem; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -28,13 +27,5 @@ namespace AlphaFS.UnitTest [TestClass] public partial class AlphaFS_DeviceTest { - [TestMethod] - public void AlphaFS_Device_Test() - { - //var hw = new Hardware(); - - - IOCtl.Main(); - } } } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs new file mode 100644 index 000000000..c92486036 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs @@ -0,0 +1,90 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDriveInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrive_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + var gotDisk = false; + var driveCount = 0; + + + foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) + { + var storagePartitionInfo = Alphaleonis.Win32.Filesystem.Device.GetStoragePartitionInfo(drive.Name); + + Console.WriteLine(); + Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, drive.Name, storagePartitionInfo.ToString()); + + UnitTestConstants.Dump(storagePartitionInfo, -23); + + + Assert.IsNotNull(storagePartitionInfo); + + + if (null != storagePartitionInfo.GptPartitionInfo) + { + gotDisk = true; + + foreach (var partition in storagePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, -23, true); + } + + + if (null != storagePartitionInfo.MbrPartitionInfo) + { + gotDisk = true; + + foreach (var partition in storagePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, -23, true); + } + + + //if (drive.DriveType == System.IO.DriveType.Fixed) + //{ + // gotDisk = true; + // Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.Disk, storagePartitionInfo.DeviceType); + //} + + + //if (drive.DriveType == System.IO.DriveType.CDRom) + // Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.CDRom, storagePartitionInfo.DeviceType); + + + Console.WriteLine(); + } + + + Assert.IsTrue(gotDisk); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs new file mode 100644 index 000000000..64d15f315 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs @@ -0,0 +1,37 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace AlphaFS.UnitTest +{ + public partial class AlphaFS_PhysicalDriveInfoTest + { + [TestMethod] + public void Device_Test() + { + //var hw = new Hardware(); + + IOCtl.Main(); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 9bb59d46c..cd31c5e31 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -148,6 +148,7 @@ + @@ -157,8 +158,9 @@ + + - diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index fdac310b3..7e84f24d8 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -196,12 +196,10 @@ True - - - + + - @@ -223,6 +221,7 @@ + @@ -326,7 +325,13 @@ + + + + + + @@ -500,6 +505,7 @@ + @@ -704,7 +710,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index b9bdf6c87..8895b2a13 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -21,8 +21,6 @@ using System; using System.Runtime.InteropServices; -using System.Security; -using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem @@ -77,9 +75,8 @@ public static partial class Device for (int i = 0, itemOffset = 0; i < numberOfExtents - 1; i++, itemOffset = structSize * i) - { + diskExtent[i] = safeBuffer.PtrToStructure(itemOffset); - } return new NativeMethods.VOLUME_DISK_EXTENTS {Extents = diskExtent}; @@ -92,53 +89,53 @@ public static partial class Device } - [SecurityCritical] - internal static object GetDriveStuff(string logicalDrive) - { - using (var safeHandle = OpenPhysicalDrive(logicalDrive, FileSystemRights.Read | FileSystemRights.Write)) - { - // DRIVE_LAYOUT_INFORMATION_EX + //[SecurityCritical] + //internal static object GetDriveStuff(string logicalDrive) + //{ + // using (var safeHandle = OpenPhysicalDrive(logicalDrive, FileSystemRights.Read | FileSystemRights.Write)) + // { + // // DRIVE_LAYOUT_INFORMATION_EX - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, logicalDrive)) - { - if (null != safeBuffer) - { - var structure = safeBuffer.PtrToStructure(0); + // using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, logicalDrive)) + // { + // if (null != safeBuffer) + // { + // var structure = safeBuffer.PtrToStructure(0); - return structure; - } - } + // return structure; + // } + // } - return null; + // return null; - // DISK_GEOMETRY_EX + // // DISK_GEOMETRY_EX - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, logicalDrive)) - { - if (null != safeBuffer) - { - var structure = safeBuffer.PtrToStructure(0); + // using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, logicalDrive)) + // { + // if (null != safeBuffer) + // { + // var structure = safeBuffer.PtrToStructure(0); - //return structure; - } - } + // //return structure; + // } + // } - // PARTITION_INFORMATION_EX + // // PARTITION_INFORMATION_EX - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_PARTITION_INFO_EX, logicalDrive)) - { - if (null != safeBuffer) - { - var structure = safeBuffer.PtrToStructure(0); + // using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_PARTITION_INFO_EX, logicalDrive)) + // { + // if (null != safeBuffer) + // { + // var structure = safeBuffer.PtrToStructure(0); - //return structure; - } - } - } + // //return structure; + // } + // } + // } - return null; - } + // return null; + //} } } diff --git a/AlphaFS/Device/DeviceInfo.cs b/AlphaFS/Device/DeviceInfo.cs index d25731e0b..d3ff72b2b 100644 --- a/AlphaFS/Device/DeviceInfo.cs +++ b/AlphaFS/Device/DeviceInfo.cs @@ -25,7 +25,7 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides access to information of a device, on a local or remote host. + /// Provides access to information of a device. [Serializable] [SecurityCritical] public sealed class DeviceInfo diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPartitionInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPartitionInfo.cs deleted file mode 100644 index 7c8b4509d..000000000 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPartitionInfo.cs +++ /dev/null @@ -1,109 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 System.Security.AccessControl; -using Microsoft.Win32.SafeHandles; - -namespace Alphaleonis.Win32.Filesystem -{ - public static partial class Device - { - public static StorageAdapterInfo GetPartitionInfo(string devicePath) - { - return GetPartitionInfoCore(devicePath); - } - - - - - internal static StorageAdapterInfo GetPartitionInfoCore(string devicePath) - { - string logicalDrive; - - var pathToDevice = GetDevicePath(devicePath, out logicalDrive); - - if (Utils.IsNullOrWhiteSpace(pathToDevice)) - return null; - - - using (var safeHandle = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read)) - - return GetPartitionInfoNative(safeHandle, devicePath); - } - - - internal static StorageAdapterInfo GetPartitionInfoNative(SafeFileHandle safeHandle, string pathToDevice) - { - var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY - { - PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, - QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery - }; - - SafeFileHandle safeHandleRetry = null; - var isRetry = false; - - - StartGetData: - - // Get storage adapter info. - - using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, NativeMethods.DefaultFileBufferSize / 4)) - { - if (null == safeBuffer) - { - // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - - - var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); - - if (volDiskExtents.HasValue) - { - // Use the first disk extent. - - pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - - - safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); - - isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; - } - - - if (isRetry) - goto StartGetData; - - return null; - } - - - using (safeBuffer) - { - if (isRetry && !safeHandleRetry.IsClosed) - safeHandleRetry.Close(); - - return new StorageAdapterInfo(safeBuffer.PtrToStructure(0)); - } - } - } - } -} diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index 9923819ce..07b05e8ac 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -137,7 +137,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, stri if (isElevated) { - GetDriveStuff(@"\\.\C:"); + //GetDriveStuff(@"\\.\C:"); using (var safeHandle = OpenPhysicalDrive(devicePath, FileSystemRights.Read)) diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs index a5088ae95..09708f223 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs @@ -78,7 +78,7 @@ internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath) } - internal static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle safeHandle, string pathToDevice) + private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle safeHandle, string pathToDevice) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs index 569796325..a48dd2b5e 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs @@ -19,7 +19,9 @@ * THE SOFTWARE. */ +using System; using System.Globalization; +using System.Runtime.InteropServices; using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; @@ -28,15 +30,15 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Device { - public static StorageDeviceInfo GetStoragePartitionInfo(string devicePath) + public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) { - return GetStorageDeviceInfoCore(Security.ProcessContext.IsElevatedProcess, devicePath); + return GetStoragePartitionInfoCore(devicePath); } - - - internal static StorageDeviceInfo GetStoragePartitionInfoCore(bool isElevated, string devicePath) + + + internal static StoragePartitionInfo GetStoragePartitionInfoCore(string devicePath) { string logicalDrive; @@ -46,146 +48,111 @@ internal static StorageDeviceInfo GetStoragePartitionInfoCore(bool isElevated, s return null; - StorageDeviceInfo storageDeviceInfo = null; - - - StartGetData: - using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) - { - var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); - - if (null == safeBuffer) - { - // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - - - var volDiskExtents = GetVolumeDiskExtents(safeHandle); - - if (volDiskExtents.HasValue) - { - // Use the first disk extent. - pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - - goto StartGetData; - } - } - - else - using (safeBuffer) - storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure(0)); - } - - - if (null != storageDeviceInfo && isElevated) - { - using (var safeHandle = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read)) - - storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, pathToDevice, storageDeviceInfo); - } - - - return storageDeviceInfo; + return GetStoragePartitionInfoNative(safeHandle, devicePath); } - private static StorageDeviceInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandle, string pathToDevice, StorageDeviceInfo storageDeviceInfo) + private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandle, string pathForException) { - var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY - { - PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageDeviceProperty, - QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery - }; - - SafeFileHandle safeHandleRetry = null; - var isRetry = false; - - - StartGetData: - - // Get storage device info. - - using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, NativeMethods.DefaultFileBufferSize / 2)) - { - if (null == safeBuffer) + var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 + var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 + var partitionCount = 1; + + var bufferSize = driveStructureSize + partitionCount * partitionStructureSize; + + while (true) + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) { - // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var lastError = Marshal.GetLastWin32Error(); - var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); - if (volDiskExtents.HasValue) + if (success) { - // Use the first disk extent. + var drive = safeBuffer.PtrToStructure(0); - pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); + var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; - safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); + for (partitionCount = 0; partitionCount <= drive.PartitionCount - 1; partitionCount++) - isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; - } + partitions[partitionCount] = safeBuffer.PtrToStructure(driveStructureSize + partitionCount * partitionStructureSize); - if (isRetry) - goto StartGetData; + var disk = GetDiskGeometryExNative(safeHandle, pathForException); - return null; - } + return new StoragePartitionInfo(disk, drive, partitions); + } - var deviceDescriptor = safeBuffer.PtrToStructure(0); + //// Dynamic disk. + //if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_NOT_READY || + // // Request device number from a DeviceGuid.Image device. + // lastError == Win32Errors.ERROR_NOT_SUPPORTED) - storageDeviceInfo = new StorageDeviceInfo - { - DeviceType = storageDeviceInfo.DeviceType, + // return null; - DeviceNumber = storageDeviceInfo.DeviceNumber, - PartitionNumber = storageDeviceInfo.PartitionNumber, + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + } + } - BusType = (StorageBusType) deviceDescriptor.BusType, + /// Gets the disk geometry extended information + private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeHandle, string pathForException) + { + var bufferSize = 128; - CommandQueueing = deviceDescriptor.CommandQueueing, - - ProductId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductIdOffset).Trim(), + while (true) + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) + { + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); - ProductRevision = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductRevisionOffset).Trim(), + var lastError = Marshal.GetLastWin32Error(); - RemovableMedia = deviceDescriptor.RemovableMedia, - SerialNumber = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(), + if (success) + { + var typeOf = typeof(NativeMethods.DISK_GEOMETRY); + var sizeOf = Marshal.SizeOf(typeOf); - VendorId = safeBuffer.PtrToStringAnsi((int)deviceDescriptor.VendorIdOffset).Trim() - }; + var diskGeometryEx = new NativeMethods.DISK_GEOMETRY_EX + { + Geometry = safeBuffer.PtrToStructure(), + DiskSize = safeBuffer.ReadInt64(sizeOf) + }; - if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.ProductRevision) || storageDeviceInfo.ProductRevision.Length == 1) - storageDeviceInfo.ProductRevision = null; - if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.SerialNumber) || storageDeviceInfo.SerialNumber.Length == 1) - storageDeviceInfo.SerialNumber = null; - - if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.VendorId) || storageDeviceInfo.VendorId.Length == 1) - storageDeviceInfo.VendorId = null; - } + var offset = sizeOf + sizeof(long); // 32 + diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure(offset); - using (var safeBuffer = GetDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, pathToDevice)) - storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; + offset += (int) diskGeometryEx.PartitionInformation.SizeOfPartitionInfo; + + diskGeometryEx.DiskDetectionInfo = safeBuffer.PtrToStructure(offset); + return diskGeometryEx; + } + + + //// Dynamic disk. + //if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_NOT_READY || + // // Request device number from a DeviceGuid.Image device. + // lastError == Win32Errors.ERROR_NOT_SUPPORTED) - if (isRetry && !safeHandleRetry.IsClosed) - safeHandleRetry.Close(); + // return null; - return storageDeviceInfo; + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + } } } } diff --git a/AlphaFS/Device/StorageAdapterInfo.cs b/AlphaFS/Device/StorageAdapterInfo.cs index 8ff23d838..7d0335c88 100644 --- a/AlphaFS/Device/StorageAdapterInfo.cs +++ b/AlphaFS/Device/StorageAdapterInfo.cs @@ -26,7 +26,7 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides access to information of a device, on a local or remote host. + /// Provides access to adapter information of a storage device. [Serializable] [SecurityCritical] public sealed class StorageAdapterInfo diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs index d718812e9..b8863c4ed 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -26,7 +26,7 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides access to information of a device, on a local or remote host. + /// Provides access to information of a storage device. [Serializable] [SecurityCritical] public sealed class StorageDeviceInfo diff --git a/AlphaFS/Device/StoragePartitionInfoGpt.cs b/AlphaFS/Device/StorageGptPartitionInfo.cs similarity index 52% rename from AlphaFS/Device/StoragePartitionInfoGpt.cs rename to AlphaFS/Device/StorageGptPartitionInfo.cs index 530003ceb..ef730bc33 100644 --- a/AlphaFS/Device/StoragePartitionInfoGpt.cs +++ b/AlphaFS/Device/StorageGptPartitionInfo.cs @@ -20,55 +20,151 @@ */ using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Globalization; +using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { + /// Provides access to GPT partition information of a storage device. [Serializable] [SecurityCritical] - public sealed class StoragePartitionInfoGpt + public sealed class StorageGptPartitionInfo { + #region Private Fields + + private ulong _partitionLength; + private ulong _startingOffset; + private ulong _startingUsableOffset; + private static PartitionType[] _partitionTypes; + + #endregion // Private Fields + + #region Constructors - /// Initializes a StoragePartitionInfoGpt instance. - public StoragePartitionInfoGpt() + /// Initializes a StorageGptPartitionInfo instance. + public StorageGptPartitionInfo() { - } + if (null == _partitionTypes) + _partitionTypes = Utils.EnumToArray(); + PartitionNumber = -1; + } + - internal StoragePartitionInfoGpt(NativeMethods.PARTITION_INFORMATION_GPT gptPartition) : this() + internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partition) : this() { + _partitionLength = partition.PartitionLength; + + _startingOffset = partition.StartingOffset; + + PartitionNumber = (int) partition.PartitionNumber; + + RewritePartition = partition.RewritePartition; + + + + + + var gptPartition = partition.Gpt; + Attributes = (PartitionAttributes) gptPartition.Attributes; + - Id = gptPartition.PartitionId; - Description = gptPartition.Name; + Description = gptPartition.Name.Trim(); - Type = gptPartition.PartitionType; + PartitionId = gptPartition.PartitionId; + + + foreach (var guid in _partitionTypes) + if (gptPartition.PartitionType.Equals(new Guid(Utils.GetEnumDescription(guid)))) + { + PartitionType = guid; + break; + } } #endregion // Constructors #region Properties + /// The Extensible Firmware Interface (EFI) attributes of the partition. public PartitionAttributes Attributes { get; internal set; } - - /// The GUID of the partition. - public Guid Id { get; internal set; } - /// The description of the partition. public string Description { get; internal set; } - /// The GUID of the partition that identifies the partition type. - /// Each partition type that the EFI specification supports is identified by its own GUID, which is published by the developer of the partition. - /// - public Guid Type { get; internal set; } + /// The GUID of the partition. + public Guid PartitionId { get; internal set; } + + + /// The starting offset of the partition. + public long PartitionLength + { + get + { + unchecked + { + return (long) _partitionLength; + } + } + + internal set + { + unchecked + { + _partitionLength = (ulong) value; + } + } + } + + + /// The starting offset of the partition, formatted as a unit size. + public string PartitionLengthUnitSize + { + get { return Utils.UnitSizeToText(PartitionLength); } + } + + + /// The storage partition number, starting at 1. + public int PartitionNumber { get; internal set; } + + + /// The the partition type. Each partition type that the EFI specification supports is identified by its own GUID, which is published by the developer of the partition. + public PartitionType PartitionType { get; internal set; } + + + /// The rewritable status of the storage partition. + public bool RewritePartition { get; internal set; } + + + /// The starting offset of the partition. + public long StartingOffset + { + get + { + unchecked + { + return (long) _startingOffset; + } + } + + internal set + { + unchecked + { + _startingOffset = (ulong) value; + } + } + } #endregion // Properties @@ -91,13 +187,13 @@ public override bool Equals(object obj) if (null == obj || GetType() != obj.GetType()) return false; - var other = obj as StoragePartitionInfoGpt; + var other = obj as StorageGptPartitionInfo; return null != other && other.Attributes == Attributes && - other.Id == Id && + other.PartitionId == PartitionId && other.Description == Description && - other.Type == Type; + other.PartitionType == PartitionType; } @@ -107,7 +203,7 @@ public override int GetHashCode() { unchecked { - return Attributes.GetHashCode() + Id.GetHashCode() + Description.GetHashCode() + Type.GetHashCode(); + return Attributes.GetHashCode() + PartitionId.GetHashCode() + Description.GetHashCode() + PartitionType.GetHashCode(); } } @@ -116,7 +212,7 @@ public override int GetHashCode() /// A. /// B. /// The result of the operator. - public static bool operator ==(StoragePartitionInfoGpt left, StoragePartitionInfoGpt right) + public static bool operator ==(StorageGptPartitionInfo left, StorageGptPartitionInfo right) { return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); } @@ -126,7 +222,7 @@ public override int GetHashCode() /// A. /// B. /// The result of the operator. - public static bool operator !=(StoragePartitionInfoGpt left, StoragePartitionInfoGpt right) + public static bool operator !=(StorageGptPartitionInfo left, StorageGptPartitionInfo right) { return !(left == right); } diff --git a/AlphaFS/Device/StoragePartitionInfoMbr.cs b/AlphaFS/Device/StorageMbrPartitionInfo.cs similarity index 58% rename from AlphaFS/Device/StoragePartitionInfoMbr.cs rename to AlphaFS/Device/StorageMbrPartitionInfo.cs index d96aa62ed..803f6349d 100644 --- a/AlphaFS/Device/StoragePartitionInfoMbr.cs +++ b/AlphaFS/Device/StorageMbrPartitionInfo.cs @@ -25,27 +25,51 @@ namespace Alphaleonis.Win32.Filesystem { + /// Provides access to MBR partition information of a storage device. [Serializable] [SecurityCritical] - public sealed class StoragePartitionInfoMbr + public sealed class StorageMbrPartitionInfo { + #region Private Fields + + private ulong _partitionLength; + private ulong _startingOffset; + + #endregion // Private Fields + + #region Constructors - /// Initializes a StoragePartitionInfoMbr instance. - public StoragePartitionInfoMbr() + /// Initializes a StorageMbrPartitionInfo instance. + public StorageMbrPartitionInfo() { + HiddenSectors = -1; + + PartitionNumber = -1; } + - internal StoragePartitionInfoMbr(NativeMethods.PARTITION_INFORMATION_MBR gptPartition) : this() + internal StorageMbrPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partition) : this() { - BootIndicator = gptPartition.BootIndicator; + _partitionLength = partition.PartitionLength; + + _startingOffset = partition.StartingOffset; + + PartitionNumber = (int) partition.PartitionNumber; + + RewritePartition = partition.RewritePartition; + + + var mbrPartition = partition.Mbr; - HiddenSectors = (int) gptPartition.HiddenSectors; + BootIndicator = mbrPartition.BootIndicator; - RecognizedPartition = gptPartition.RecognizedPartition; + HiddenSectors = (int) mbrPartition.HiddenSectors; - Type = gptPartition.PartitionType; + RecognizedPartition = mbrPartition.RecognizedPartition; + + PartitionType = mbrPartition.PartitionType; } #endregion // Constructors @@ -61,12 +85,69 @@ internal StoragePartitionInfoMbr(NativeMethods.PARTITION_INFORMATION_MBR gptPart public int HiddenSectors { get; internal set; } + /// The starting offset of the partition. + public long PartitionLength + { + get + { + unchecked + { + return (long) _partitionLength; + } + } + + internal set + { + unchecked + { + _partitionLength = (ulong) value; + } + } + } + + + /// The starting offset of the partition, formatted as a unit size. + public string PartitionLengthUnitSize + { + get { return Utils.UnitSizeToText(PartitionLength); } + } + + + /// The storage partition number, starting at 1. + public int PartitionNumber { get; internal set; } + + + /// The type of the partition. + public DiskPartitionTypes PartitionType { get; internal set; } + + /// if the partition is of a recognized type. public bool RecognizedPartition { get; internal set; } - /// The type of the partition. - public DiskPartitionTypes Type { get; internal set; } + /// The rewritable status of the storage partition. + public bool RewritePartition { get; internal set; } + + + /// The starting offset of the partition. + public long StartingOffset + { + get + { + unchecked + { + return (long) _startingOffset; + } + } + + internal set + { + unchecked + { + _startingOffset = (ulong) value; + } + } + } #endregion // Properties @@ -77,7 +158,7 @@ internal StoragePartitionInfoMbr(NativeMethods.PARTITION_INFORMATION_MBR gptPart /// A string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "BootIndicator {0}, Type: {1}, RecognizedPartition: {2}", BootIndicator.ToString(), Type.ToString(), RecognizedPartition.ToString()).Trim(); + return string.Format(CultureInfo.CurrentCulture, "BootIndicator {0}, Type: {1}, RecognizedPartition: {2}", BootIndicator.ToString(), PartitionType.ToString(), RecognizedPartition.ToString()).Trim(); } @@ -89,13 +170,13 @@ public override bool Equals(object obj) if (null == obj || GetType() != obj.GetType()) return false; - var other = obj as StoragePartitionInfoMbr; + var other = obj as StorageMbrPartitionInfo; return null != other && other.BootIndicator == BootIndicator && other.HiddenSectors == HiddenSectors && other.RecognizedPartition == RecognizedPartition && - other.Type == Type; + other.PartitionType == PartitionType; } @@ -105,7 +186,7 @@ public override int GetHashCode() { unchecked { - return BootIndicator.GetHashCode() + HiddenSectors.GetHashCode() + RecognizedPartition.GetHashCode() + Type.GetHashCode(); + return BootIndicator.GetHashCode() + HiddenSectors.GetHashCode() + RecognizedPartition.GetHashCode() + PartitionType.GetHashCode(); } } @@ -114,7 +195,7 @@ public override int GetHashCode() /// A. /// B. /// The result of the operator. - public static bool operator ==(StoragePartitionInfoMbr left, StoragePartitionInfoMbr right) + public static bool operator ==(StorageMbrPartitionInfo left, StorageMbrPartitionInfo right) { return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); } @@ -124,7 +205,7 @@ public override int GetHashCode() /// A. /// B. /// The result of the operator. - public static bool operator !=(StoragePartitionInfoMbr left, StoragePartitionInfoMbr right) + public static bool operator !=(StorageMbrPartitionInfo left, StorageMbrPartitionInfo right) { return !(left == right); } diff --git a/AlphaFS/Device/StoragePartitionInfo.cs b/AlphaFS/Device/StoragePartitionInfo.cs index acf51d249..48d2ac377 100644 --- a/AlphaFS/Device/StoragePartitionInfo.cs +++ b/AlphaFS/Device/StoragePartitionInfo.cs @@ -20,15 +20,24 @@ */ using System; -using System.Globalization; +using System.Collections.ObjectModel; +using System.Net.Mime; using System.Security; namespace Alphaleonis.Win32.Filesystem { + /// Provides access to partition information of a storage device. [Serializable] [SecurityCritical] public sealed class StoragePartitionInfo { + #region Private Fields + + private ulong _gptStartingUsableOffset; + + #endregion // Private Fields + + #region Constructors /// Initializes a StoragePartitionInfo instance. @@ -36,132 +45,234 @@ public StoragePartitionInfo() { DeviceNumber = -1; - PartitionNumber = -1; + PartitionCount = -1; PartitionStyle = PartitionStyle.Raw; } - internal StoragePartitionInfo(NativeMethods.STORAGE_DEVICE_NUMBER device, NativeMethods.PARTITION_INFORMATION_EX partition) : this() + internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods.DRIVE_LAYOUT_INFORMATION_EX drive, NativeMethods.PARTITION_INFORMATION_EX[] partitions) : this() { - DeviceNumber = device.DeviceNumber; + MbrSignature = disk.PartitionInformation.MbrSignature; - PartitionNumber = (int) partition.PartitionNumber; - - PartitionStyle = (PartitionStyle) partition.PartitionStyle; + GptDiskId = disk.PartitionInformation.DiskId; + MediaType = (StorageMediaType) disk.Geometry.MediaType; - RewritePartition = partition.RewritePartition; + PartitionStyle = (PartitionStyle) disk.PartitionInformation.PartitionStyle; + + TotalSize = disk.DiskSize; + + + PartitionCount = (int) drive.PartitionCount; + + + switch (PartitionStyle) + { + case PartitionStyle.Gpt: + GptMaxPartitionCount = (int) drive.Gpt.MaxPartitionCount; + + _gptStartingUsableOffset = drive.Gpt.StartingUsableOffset; + + + GptPartitionInfo = new Collection(); + + for (var i = 0; i <= PartitionCount - 1; i++) + GptPartitionInfo.Add(new StorageGptPartitionInfo(partitions[i])); + + break; + - TotalSize = (long) partition.PartitionLength; + case PartitionStyle.Mbr: + for (var i = 0; i <= PartitionCount - 1; i++) + { + var partition = partitions[i]; - GptPartitionInfo = new StoragePartitionInfoGpt(partition.Gpt); + // MSDN: PartitionCount: On hard disks with the MBR layout, this value will always be a multiple of 4. + // Any partitions that are actually unused will have a partition type of PARTITION_ENTRY_UNUSED (0). - MbrPartitionInfo = new StoragePartitionInfoMbr(partition.Mbr); + if (partition.Mbr.PartitionType == DiskPartitionTypes.UnusedEntry) + continue; + + + if (null == MbrPartitionInfo) + MbrPartitionInfo = new Collection(); + + MbrPartitionInfo.Add(new StorageMbrPartitionInfo(partition)); + } + + + // Update to reflect the real number of used partition entries. + PartitionCount = MbrPartitionInfo.Count; + + break; + } } #endregion // Constructors #region Properties + + /// The GUID of the disk. + public Guid GptDiskId { get; internal set; } + /// The device number of the storage partition, starting at 0. public int DeviceNumber { get; internal set; } + /// The maximum number of partitions that can be defined in the usable block. + public int GptMaxPartitionCount { get; internal set; } + + /// Contains GUID partition table (GPT) partition information. - public StoragePartitionInfoGpt GptPartitionInfo { get; internal set; } + public Collection GptPartitionInfo { get; internal set; } + + + /// The starting byte offset of the first usable block. + public long GptStartingUsableOffset + { + get + { + unchecked + { + return (long) _gptStartingUsableOffset; + } + } + internal set + { + unchecked + { + _gptStartingUsableOffset = (ulong) value; + } + } + } - /// Contains partition information specific to master boot record (MBR) disks. - public StoragePartitionInfoMbr MbrPartitionInfo { get; internal set; } + ///// The size of the usable blocks on the disk, in bytes. + //public long GptUsableLength + //{ + // get + // { + // unchecked + // { + // return (long) _gptUsableLength; + // } + // } + + // internal set + // { + // unchecked + // { + // _gptUsableLength = (ulong) value; + // } + // } + //} - /// The storage partition number, starting at 1. - public int PartitionNumber { get; internal set; } + ///// (Only applicable to GPT partition) The size of the usable blocks on the disk in bytes, formatted as a unit size. + //public string GptUsableLengthUnitSize + //{ + // get { return Utils.UnitSizeToText(GptUsableLength); } + //} + + + /// Contains partition information specific to master boot record (MBR) disks. + public Collection MbrPartitionInfo { get; internal set; } + + + /// The MBR signature of the drive. + public long MbrSignature { get; internal set; } - /// The format of the partition. For a list of values, see . - public PartitionStyle PartitionStyle { get; internal set; } + /// The media type of the storage partition. + public StorageMediaType MediaType { get; internal set; } - /// The rewritable status of the storage partition. - public bool RewritePartition { get; internal set; } + + /// The number of partitions on the drive. + public int PartitionCount { get; internal set; } + + + /// The format of the partition. For a list of values, see . + public PartitionStyle PartitionStyle { get; internal set; } /// The total size of the storage partition. public long TotalSize { get; internal set; } - /// The total size of the physical drive, formatted as a unit size. + /// The total size of the storage partition, formatted as a unit size. public string TotalSizeUnitSize { get { return Utils.UnitSizeToText(TotalSize); } } + #endregion // Properties - #region Methods + //#region Methods - /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". - /// A string that represents this instance. - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "{0}:{1} {2} {3}", + ///// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". + ///// A string that represents this instance. + //public override string ToString() + //{ + // return string.Format(CultureInfo.CurrentCulture, "{0}:{1} {2} {3}", - DeviceNumber.ToString(), PartitionNumber.ToString(), PartitionStyle.ToString(), TotalSizeUnitSize).Trim(); - } + // DeviceNumber.ToString(CultureInfo.InvariantCulture), PartitionNumber.ToString(CultureInfo.InvariantCulture), PartitionStyle.ToString(), TotalSizeUnitSize).Trim(); + //} - /// Determines whether the specified Object is equal to the current Object. - /// Another object to compare to. - /// if the specified Object is equal to the current Object; otherwise, . - public override bool Equals(object obj) - { - if (null == obj || GetType() != obj.GetType()) - return false; + ///// Determines whether the specified Object is equal to the current Object. + ///// Another object to compare to. + ///// if the specified Object is equal to the current Object; otherwise, . + //public override bool Equals(object obj) + //{ + // if (null == obj || GetType() != obj.GetType()) + // return false; - var other = obj as StoragePartitionInfo; + // var other = obj as StoragePartitionInfo; - return null != other && - other.DeviceNumber == DeviceNumber && - other.PartitionNumber == PartitionNumber && - other.PartitionStyle == PartitionStyle && - other.TotalSize == TotalSize; - } + // return null != other && + // other.DeviceNumber == DeviceNumber && + // other.PartitionNumber == PartitionNumber && + // other.PartitionStyle == PartitionStyle && + // other.TotalSize == TotalSize; + //} - /// Serves as a hash function for a particular type. - /// A hash code for the current Object. - public override int GetHashCode() - { - unchecked - { - return DeviceNumber + PartitionNumber + PartitionStyle.GetHashCode() + TotalSize.GetHashCode(); - } - } + ///// Serves as a hash function for a particular type. + ///// A hash code for the current Object. + //public override int GetHashCode() + //{ + // unchecked + // { + // return PartitionCount + PartitionStyle.GetHashCode() + TotalSize.GetHashCode(); + // } + //} - /// Implements the operator == - /// A. - /// B. - /// The result of the operator. - public static bool operator ==(StoragePartitionInfo left, StoragePartitionInfo right) - { - return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); - } + ///// Implements the operator == + ///// A. + ///// B. + ///// The result of the operator. + //public static bool operator ==(StoragePartitionInfo left, StoragePartitionInfo right) + //{ + // return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); + //} - /// Implements the operator != - /// A. - /// B. - /// The result of the operator. - public static bool operator !=(StoragePartitionInfo left, StoragePartitionInfo right) - { - return !(left == right); - } + ///// Implements the operator != + ///// A. + ///// B. + ///// The result of the operator. + //public static bool operator !=(StoragePartitionInfo left, StoragePartitionInfo right) + //{ + // return !(left == right); + //} - #endregion // Methods + //#endregion // Methods } } diff --git a/AlphaFS/Device/Test.cs b/AlphaFS/Device/Test.cs index f775d39d5..dfcc97ab8 100644 --- a/AlphaFS/Device/Test.cs +++ b/AlphaFS/Device/Test.cs @@ -33,16 +33,16 @@ namespace Alphaleonis.Win32.Filesystem { #region Helper: Enum - public static class EnumHelper + internal static class EnumHelper { - public static bool HasFlag(this Enum flags, T value) where T : struct + internal static bool HasFlag(this Enum flags, T value) where T : struct { var iFlags = Convert.ToUInt64(flags); var iValue = Convert.ToUInt64(value); return ((iFlags & iValue) == iValue); } - public static T SetFlag(this Enum flags, T value, bool state = true) + internal static T SetFlag(this Enum flags, T value, bool state = true) { if (!Enum.IsDefined(typeof(T), value)) throw new ArgumentException("Enum value and flags types don't match."); if (state) return (T) Enum.ToObject(typeof(T), Convert.ToUInt64(flags) | Convert.ToUInt64(value)); @@ -54,9 +54,9 @@ public static T SetFlag(this Enum flags, T value, bool state = true) #region Helper: Byte[] - public static class ByteHelper + internal static class ByteHelper { - public static int IndexOf(this byte[] bytes, byte value, int startIndex = 0) + internal static int IndexOf(this byte[] bytes, byte value, int startIndex = 0) { while (startIndex < bytes.Length) if (bytes[startIndex++] == value) @@ -64,7 +64,7 @@ public static int IndexOf(this byte[] bytes, byte value, int startIndex = 0) return -1; } - public static string GetString(this byte[] bytes, int offset) + internal static string GetString(this byte[] bytes, int offset) { string result = null; var index = -1; @@ -73,7 +73,7 @@ public static string GetString(this byte[] bytes, int offset) return result; } - public static T ToStruct(this byte[] bytes, int start = 0) where T : struct + internal static T ToStruct(this byte[] bytes, int start = 0) where T : struct { var result = new T(); var size = Marshal.SizeOf(result); @@ -87,7 +87,7 @@ public static T ToStruct(this byte[] bytes, int start = 0) where T : struct #endregion - public class Hardware + internal class Hardware { #region [extern] WindowsAPI @@ -142,7 +142,7 @@ private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoCont private static extern int CloseHandle(int hObject); [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] - public static extern int EnumSystemFirmwareTables(BiosFirmwareTableProvider providerSignature, + internal static extern int EnumSystemFirmwareTables(BiosFirmwareTableProvider providerSignature, IntPtr firmwareTableBuffer, int bufferSize); [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] @@ -211,7 +211,7 @@ private static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref #region [enum] STORAGE_BUS_TYPE - public enum STORAGE_BUS_TYPE : byte + internal enum STORAGE_BUS_TYPE : byte { BusTypeUnknown = 0x00, BusTypeScsi = 0x01, @@ -238,12 +238,12 @@ public enum STORAGE_BUS_TYPE : byte #region [struct] VOLUMEDISKEXTENTS [StructLayout(LayoutKind.Explicit)] - public struct VOLUMEDISKEXTENTS + internal struct VOLUMEDISKEXTENTS { - [FieldOffset(0)] public uint numberOfDiskExtents; - [FieldOffset(8)] public uint diskNumber; - [FieldOffset(16)] public long startingOffset; - [FieldOffset(24)] public long extentLength; + [FieldOffset(0)] internal uint numberOfDiskExtents; + [FieldOffset(8)] internal uint diskNumber; + [FieldOffset(16)] internal long startingOffset; + [FieldOffset(24)] internal long extentLength; } #endregion @@ -253,11 +253,11 @@ public struct VOLUMEDISKEXTENTS [StructLayout(LayoutKind.Sequential)] private struct STORAGE_PROPERTY_QUERY { - public uint PropertyId; - public uint QueryType; + internal uint PropertyId; + internal uint QueryType; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] - public byte[] AdditionalParameters; + internal byte[] AdditionalParameters; } #endregion @@ -265,23 +265,23 @@ private struct STORAGE_PROPERTY_QUERY #region [struct] STORAGE_DEVICE_DESCRIPTOR [StructLayout(LayoutKind.Sequential)] - public struct STORAGE_DEVICE_DESCRIPTOR + internal struct STORAGE_DEVICE_DESCRIPTOR { - public int Version; - public int Size; - public byte DeviceType; - public byte DeviceTypeModifier; - public byte RemovableMedia; - public byte CommandQueueing; - public int VendorIdOffset; - public int ProductIdOffset; - public int ProductRevisionOffset; - public int SerialNumberOffset; - public STORAGE_BUS_TYPE BusType; - public int RawPropertiesLength; + internal int Version; + internal int Size; + internal byte DeviceType; + internal byte DeviceTypeModifier; + internal byte RemovableMedia; + internal byte CommandQueueing; + internal int VendorIdOffset; + internal int ProductIdOffset; + internal int ProductRevisionOffset; + internal int SerialNumberOffset; + internal STORAGE_BUS_TYPE BusType; + internal int RawPropertiesLength; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10240)] - public byte[] RawDeviceProperties; + internal byte[] RawDeviceProperties; } #endregion @@ -289,14 +289,14 @@ public struct STORAGE_DEVICE_DESCRIPTOR #region [struct] STORAGE_DEVICE_ID_DESCRIPTOR [StructLayout(LayoutKind.Sequential)] - public struct STORAGE_DEVICE_ID_DESCRIPTOR + internal struct STORAGE_DEVICE_ID_DESCRIPTOR { - public int Version; - public int Size; - public int NumberOfIdentifiers; + internal int Version; + internal int Size; + internal int NumberOfIdentifiers; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10240)] - public byte[] Identifiers; + internal byte[] Identifiers; } #endregion @@ -304,22 +304,22 @@ public struct STORAGE_DEVICE_ID_DESCRIPTOR #region [struct] STORAGE_ADAPTER_DESCRIPTOR [StructLayout(LayoutKind.Sequential)] - public struct STORAGE_ADAPTER_DESCRIPTOR + internal struct STORAGE_ADAPTER_DESCRIPTOR { - public uint Version; - public uint Size; - public uint MaximumTransferLength; - public uint MaximumPhysicalPages; - public uint AlignmentMask; - public byte AdapterUsesPio; - public byte AdapterScansDown; - public byte CommandQueueing; - public byte AcceleratedTransfer; - public STORAGE_BUS_TYPE BusType; - public ushort BusMajorVersion; - public ushort BusMinorVersion; - public byte SrbType; - public byte AddressType; + internal uint Version; + internal uint Size; + internal uint MaximumTransferLength; + internal uint MaximumPhysicalPages; + internal uint AlignmentMask; + internal byte AdapterUsesPio; + internal byte AdapterScansDown; + internal byte CommandQueueing; + internal byte AcceleratedTransfer; + internal STORAGE_BUS_TYPE BusType; + internal ushort BusMajorVersion; + internal ushort BusMinorVersion; + internal byte SrbType; + internal byte AddressType; } #endregion @@ -327,16 +327,16 @@ public struct STORAGE_ADAPTER_DESCRIPTOR #region [struct] GETVERSIONOUTPARAMS [StructLayout(LayoutKind.Sequential)] - public struct GETVERSIONOUTPARAMS + internal struct GETVERSIONOUTPARAMS { - public byte bVersion; - public byte bRevision; - public byte bReserved; - public byte bIDEDeviceMap; - public int fCapabilities; + internal byte bVersion; + internal byte bRevision; + internal byte bReserved; + internal byte bIDEDeviceMap; + internal int fCapabilities; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] - public int[] dwReserved; + internal int[] dwReserved; } #endregion @@ -344,16 +344,16 @@ public struct GETVERSIONOUTPARAMS #region [struct] IDEREGS [StructLayout(LayoutKind.Sequential, Size = 8)] - public struct IDEREGS + internal struct IDEREGS { - public byte Features; - public byte SectorCount; - public byte SectorNumber; - public byte CylinderLow; - public byte CylinderHigh; - public byte DriveHead; - public byte Command; - public byte Reserved; + internal byte Features; + internal byte SectorCount; + internal byte SectorNumber; + internal byte CylinderLow; + internal byte CylinderHigh; + internal byte DriveHead; + internal byte Command; + internal byte Reserved; } #endregion @@ -361,17 +361,17 @@ public struct IDEREGS #region [struct] SENDCMDINPARAMS [StructLayout(LayoutKind.Sequential, Size = 32)] - public struct SENDCMDINPARAMS + internal struct SENDCMDINPARAMS { - public int BufferSize; - public IDEREGS DriveRegs; - public byte DriveNumber; + internal int BufferSize; + internal IDEREGS DriveRegs; + internal byte DriveNumber; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] - public byte[] bReserved; + internal byte[] bReserved; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] - public int[] dwReserved; + internal int[] dwReserved; } #endregion @@ -379,16 +379,16 @@ public struct SENDCMDINPARAMS #region [struct] DRIVERSTATUS [StructLayout(LayoutKind.Sequential, Size = 12)] - public struct DRIVERSTATUS + internal struct DRIVERSTATUS { - public byte DriveError; - public byte IDEStatus; + internal byte DriveError; + internal byte IDEStatus; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] - public byte[] bReserved; + internal byte[] bReserved; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] - public int[] dwReserved; + internal int[] dwReserved; } #endregion @@ -396,51 +396,51 @@ public struct DRIVERSTATUS #region [struct] IDSECTOR [StructLayout(LayoutKind.Sequential)] - public struct IDSECTOR + internal struct IDSECTOR { - public short GenConfig; - public short NumberCylinders; - public short Reserved; - public short NumberHeads; - public short BytesPerTrack; - public short BytesPerSector; - public short SectorsPerTrack; + internal short GenConfig; + internal short NumberCylinders; + internal short Reserved; + internal short NumberHeads; + internal short BytesPerTrack; + internal short BytesPerSector; + internal short SectorsPerTrack; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] - public short[] VendorUnique; + internal short[] VendorUnique; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] - public byte[] SerialNumber; + internal byte[] SerialNumber; - public short BufferClass; - public short BufferSize; - public short ECCSize; + internal short BufferClass; + internal short BufferSize; + internal short ECCSize; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - public byte[] FirmwareRevision; + internal byte[] FirmwareRevision; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)] - public byte[] ModelNumber; - - public short MoreVendorUnique; - public short DoubleWordIO; - public short Capabilities; - public short Reserved1; - public short PIOTiming; - public short DMATiming; - public short BS; - public short NumberCurrentCyls; - public short NumberCurrentHeads; - public short NumberCurrentSectorsPerTrack; - public int CurrentSectorCapacity; - public short MultipleSectorCapacity; - public short MultipleSectorStuff; - public int TotalAddressableSectors; - public short SingleWordDMA; - public short MultiWordDMA; + internal byte[] ModelNumber; + + internal short MoreVendorUnique; + internal short DoubleWordIO; + internal short Capabilities; + internal short Reserved1; + internal short PIOTiming; + internal short DMATiming; + internal short BS; + internal short NumberCurrentCyls; + internal short NumberCurrentHeads; + internal short NumberCurrentSectorsPerTrack; + internal int CurrentSectorCapacity; + internal short MultipleSectorCapacity; + internal short MultipleSectorStuff; + internal int TotalAddressableSectors; + internal short SingleWordDMA; + internal short MultiWordDMA; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 382)] - public byte[] bReserved; + internal byte[] bReserved; } #endregion @@ -448,29 +448,29 @@ public struct IDSECTOR #region [struct] SENDCMDOUTPARAMS [StructLayout(LayoutKind.Sequential)] - public struct SENDCMDOUTPARAMS + internal struct SENDCMDOUTPARAMS { - public uint cBufferSize; - public DRIVERSTATUS Status; - public IDSECTOR IDS; + internal uint cBufferSize; + internal DRIVERSTATUS Status; + internal IDSECTOR IDS; } #endregion [StructLayout(LayoutKind.Sequential)] - public struct PhysicalDisk + internal struct PhysicalDisk { - public byte Number; - public string Model; - public string Firmware; - public string SerialNumber; - public bool RemovableMedia; - public VOLUMEDISKEXTENTS Extents; - public STORAGE_DEVICE_DESCRIPTOR Device; - public STORAGE_DEVICE_ID_DESCRIPTOR DeviceID; - public STORAGE_ADAPTER_DESCRIPTOR Adapter; - public GETVERSIONOUTPARAMS Version; - public SENDCMDOUTPARAMS Params; + internal byte Number; + internal string Model; + internal string Firmware; + internal string SerialNumber; + internal bool RemovableMedia; + internal VOLUMEDISKEXTENTS Extents; + internal STORAGE_DEVICE_DESCRIPTOR Device; + internal STORAGE_DEVICE_ID_DESCRIPTOR DeviceID; + internal STORAGE_ADAPTER_DESCRIPTOR Adapter; + internal GETVERSIONOUTPARAMS Version; + internal SENDCMDOUTPARAMS Params; } #region CTL_CODE @@ -546,7 +546,7 @@ private PhysicalDisk GetPhysicalDisk(string path) Result.Firmware = string.Empty; Result.Model = string.Empty; - var StoragePropertyQuery = new STORAGE_PROPERTY_QUERY(); + //var StoragePropertyQuery = new STORAGE_PROPERTY_QUERY(); Result.Extents = new VOLUMEDISKEXTENTS(); Result.Adapter = new STORAGE_ADAPTER_DESCRIPTOR(); @@ -665,7 +665,7 @@ private PhysicalDisk GetPhysicalDisk(string path) #region [enum] BiosFirmwareTableProvider - public enum BiosFirmwareTableProvider + internal enum BiosFirmwareTableProvider { ACPI = (byte) 'A' << 24 | (byte) 'C' << 16 | (byte) 'P' << 8 | (byte) 'I', FIRM = (byte) 'F' << 24 | (byte) 'I' << 16 | (byte) 'R' << 8 | (byte) 'M', @@ -676,7 +676,7 @@ public enum BiosFirmwareTableProvider #region [enum] SMBIOSTableType - public enum SMBIOSTableType : sbyte + internal enum SMBIOSTableType : sbyte { BIOSInformation = 0, SystemInformation = 1, @@ -707,18 +707,18 @@ public enum SMBIOSTableType : sbyte #region [enum] SMBIOSTableEntry [StructLayout(LayoutKind.Sequential)] - public struct SMBIOSTableHeader + internal struct SMBIOSTableHeader { - public SMBIOSTableType type; - public byte length; - public ushort Handle; + internal SMBIOSTableType type; + internal byte length; + internal ushort Handle; } [StructLayout(LayoutKind.Sequential)] - public struct SMBIOSTableEntry + internal struct SMBIOSTableEntry { - public SMBIOSTableHeader header; - public uint index; + internal SMBIOSTableHeader header; + internal uint index; } #endregion @@ -726,99 +726,99 @@ public struct SMBIOSTableEntry #region [enum] SMBIOSTableInfo [StructLayout(LayoutKind.Sequential)] - public struct SMBIOSTableBiosInfo + internal struct SMBIOSTableBiosInfo { - public SMBIOSTableHeader header; - public byte vendor; - public byte version; - public ushort startingSegment; - public byte releaseDate; - public byte biosRomSize; - public ulong characteristics; + internal SMBIOSTableHeader header; + internal byte vendor; + internal byte version; + internal ushort startingSegment; + internal byte releaseDate; + internal byte biosRomSize; + internal ulong characteristics; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] - public byte[] extensionBytes; + internal byte[] extensionBytes; } [StructLayout(LayoutKind.Sequential)] - public struct SMBIOSTableSystemInfo + internal struct SMBIOSTableSystemInfo { - public SMBIOSTableHeader header; - public byte manufacturer; - public byte productName; - public byte version; - public byte serialNumber; + internal SMBIOSTableHeader header; + internal byte manufacturer; + internal byte productName; + internal byte version; + internal byte serialNumber; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] UUID; + internal byte[] UUID; - public byte wakeUpType; + internal byte wakeUpType; } [StructLayout(LayoutKind.Sequential)] - public struct SMBIOSTableBaseBoardInfo + internal struct SMBIOSTableBaseBoardInfo { - public SMBIOSTableHeader header; - public byte manufacturer; - public byte productName; - public byte version; - public byte serialNumber; + internal SMBIOSTableHeader header; + internal byte manufacturer; + internal byte productName; + internal byte version; + internal byte serialNumber; } [StructLayout(LayoutKind.Sequential)] - public struct SMBIOSTableEnclosureInfo + internal struct SMBIOSTableEnclosureInfo { - public SMBIOSTableHeader header; - public byte manufacturer; - public byte type; - public byte version; - public byte serialNumber; - public byte assetTagNumber; - public byte bootUpState; - public byte powerSupplyState; - public byte thermalState; - public byte securityStatus; - public long OEM_Defined; + internal SMBIOSTableHeader header; + internal byte manufacturer; + internal byte type; + internal byte version; + internal byte serialNumber; + internal byte assetTagNumber; + internal byte bootUpState; + internal byte powerSupplyState; + internal byte thermalState; + internal byte securityStatus; + internal long OEM_Defined; } [StructLayout(LayoutKind.Sequential)] - public struct SMBIOSTableProcessorInfo + internal struct SMBIOSTableProcessorInfo { - public SMBIOSTableHeader header; - public byte socketDesignation; - public byte processorType; - public byte processorFamily; - public byte processorManufacturer; - public ulong processorID; - public byte processorVersion; - public byte processorVoltage; - public ushort externalClock; - public ushort maxSpeed; - public ushort currentSpeed; - public byte status; - public byte processorUpgrade; - public ushort L1CacheHandler; - public ushort L2CacheHandler; - public ushort L3CacheHandler; - public byte serialNumber; - public byte assetTag; - public byte partNumber; + internal SMBIOSTableHeader header; + internal byte socketDesignation; + internal byte processorType; + internal byte processorFamily; + internal byte processorManufacturer; + internal ulong processorID; + internal byte processorVersion; + internal byte processorVoltage; + internal ushort externalClock; + internal ushort maxSpeed; + internal ushort currentSpeed; + internal byte status; + internal byte processorUpgrade; + internal ushort L1CacheHandler; + internal ushort L2CacheHandler; + internal ushort L3CacheHandler; + internal byte serialNumber; + internal byte assetTag; + internal byte partNumber; } [StructLayout(LayoutKind.Sequential)] - public struct SMBIOSTableCacheInfo + internal struct SMBIOSTableCacheInfo { - public SMBIOSTableHeader header; - public byte socketDesignation; - public long cacheConfiguration; - public ushort maximumCacheSize; - public ushort installedSize; - public ushort supportedSRAMType; - public ushort currentSRAMType; - public byte cacheSpeed; - public byte errorCorrectionType; - public byte systemCacheType; - public byte associativity; + internal SMBIOSTableHeader header; + internal byte socketDesignation; + internal long cacheConfiguration; + internal ushort maximumCacheSize; + internal ushort installedSize; + internal ushort supportedSRAMType; + internal ushort currentSRAMType; + internal byte cacheSpeed; + internal byte errorCorrectionType; + internal byte systemCacheType; + internal byte associativity; } #endregion @@ -826,19 +826,19 @@ public struct SMBIOSTableCacheInfo #region [struct] RawSMBIOSData [StructLayout(LayoutKind.Sequential)] - public struct RawSMBIOSData + internal struct RawSMBIOSData { - public byte Used20CallingMethod; - public byte MajorVersion; - public byte MinorVersion; - public byte DmiRevision; - public uint Length; - public SMBIOSTableBiosInfo BiosInfo; - public SMBIOSTableSystemInfo SystemInfo; - public SMBIOSTableBaseBoardInfo BaseBoardInfo; - public SMBIOSTableEnclosureInfo EnclosureInfo; - public SMBIOSTableProcessorInfo ProcessorInfo; - public SMBIOSTableCacheInfo CacheInfo; + internal byte Used20CallingMethod; + internal byte MajorVersion; + internal byte MinorVersion; + internal byte DmiRevision; + internal uint Length; + internal SMBIOSTableBiosInfo BiosInfo; + internal SMBIOSTableSystemInfo SystemInfo; + internal SMBIOSTableBaseBoardInfo BaseBoardInfo; + internal SMBIOSTableEnclosureInfo EnclosureInfo; + internal SMBIOSTableProcessorInfo ProcessorInfo; + internal SMBIOSTableCacheInfo CacheInfo; } #endregion @@ -934,7 +934,7 @@ private static string[] GetRawStrings(byte[] bytes, SMBIOSTableEntry entry, ref #region [enum] DisplayDeviceStateFlags - public enum DisplayDeviceStateFlags + internal enum DisplayDeviceStateFlags { AttachedToDesktop = 0x0000001, MultiDriver = 0x0000002, @@ -952,28 +952,28 @@ public enum DisplayDeviceStateFlags #region [struct] DISPLAY_DEVICE [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - public struct DISPLAY_DEVICE + internal struct DISPLAY_DEVICE { - [MarshalAs(UnmanagedType.U4)] public int structSize; + [MarshalAs(UnmanagedType.U4)] internal int structSize; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] - public string DeviceName; + internal string DeviceName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - public string DeviceString; + internal string DeviceString; - [MarshalAs(UnmanagedType.U4)] public DisplayDeviceStateFlags StateFlags; + [MarshalAs(UnmanagedType.U4)] internal DisplayDeviceStateFlags StateFlags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - public string DeviceID; + internal string DeviceID; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - public string DeviceKey; + internal string DeviceKey; } #endregion - public Hardware() + internal Hardware() { using (var Binary = new BinaryWriter(new MemoryStream())) { @@ -1287,7 +1287,7 @@ public Hardware() Console.ResetColor(); } - public byte[] MD5 + internal byte[] MD5 { get { @@ -1296,7 +1296,7 @@ public byte[] MD5 } } - public byte[] SHA1 + internal byte[] SHA1 { get { @@ -1305,7 +1305,7 @@ public byte[] SHA1 } } - public byte[] SHA256 + internal byte[] SHA256 { get { @@ -1314,7 +1314,7 @@ public byte[] SHA256 } } - public byte[] SHA512 + internal byte[] SHA512 { get { @@ -1323,7 +1323,7 @@ public byte[] SHA512 } } - public string MD5String + internal string MD5String { get { @@ -1332,7 +1332,7 @@ public string MD5String } } - public string SHA1String + internal string SHA1String { get { @@ -1341,7 +1341,7 @@ public string SHA1String } } - public string SHA256String + internal string SHA256String { get { @@ -1350,7 +1350,7 @@ public string SHA256String } } - public string SHA512String + internal string SHA512String { get { diff --git a/AlphaFS/Device/Test2.cs b/AlphaFS/Device/Test2.cs index 306b7c121..8307969a9 100644 --- a/AlphaFS/Device/Test2.cs +++ b/AlphaFS/Device/Test2.cs @@ -8,7 +8,7 @@ namespace Alphaleonis.Win32.Filesystem { - public static class IOCtl + internal static class IOCtl { private const int GENERIC_READ = unchecked((int) 0x80000000); private const int FILE_SHARE_READ = 1; @@ -40,7 +40,7 @@ private class NativeMethods { [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] - public static extern SafeFileHandle CreateFile( + internal static extern SafeFileHandle CreateFile( string fileName, int desiredAccess, int shareMode, @@ -51,7 +51,7 @@ public static extern SafeFileHandle CreateFile( [DllImport("kernel32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool DeviceIoControl( + internal static extern bool DeviceIoControl( SafeFileHandle hVol, Filesystem.NativeMethods.IoControlCode controlCode, IntPtr inBuffer, @@ -70,7 +70,7 @@ public static extern bool DeviceIoControl( - public static void Main() + internal static void Main() { SendIoCtlDiskGetDriveLayoutEx(0); SendIoCtlDiskGetDriveLayoutEx(1); diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs index e200dea10..38dacd3f5 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs @@ -50,7 +50,7 @@ partial class Directory [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath) { - return CopyMoveCore(null, sourcePath, destinationPath, false, CopyOptions.FailIfExists, null, null, null, null, PathFormat.RelativePath); + return CopyMoveCore(null, sourcePath, destinationPath, false, CopyOptions.FailIfExists, null, null, null, PathFormat.RelativePath); } @@ -73,7 +73,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath) [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, PathFormat pathFormat) { - return CopyMoveCore(null, sourcePath, destinationPath, false, CopyOptions.FailIfExists, null, null, null, null, pathFormat); + return CopyMoveCore(null, sourcePath, destinationPath, false, CopyOptions.FailIfExists, null, null, null, pathFormat); } @@ -96,7 +96,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Pat [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite) { - return CopyMoveCore(null, sourcePath, destinationPath, false, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, null, null, null, PathFormat.RelativePath); + return CopyMoveCore(null, sourcePath, destinationPath, false, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, null, null, PathFormat.RelativePath); } @@ -120,7 +120,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, boo [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, bool overwrite, PathFormat pathFormat) { - return CopyMoveCore(null, sourcePath, destinationPath, false, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, null, null, null, pathFormat); + return CopyMoveCore(null, sourcePath, destinationPath, false, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, null, null, pathFormat); } @@ -143,7 +143,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, boo [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, CopyOptions.FailIfExists, null, null, null, null, PathFormat.RelativePath); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, CopyOptions.FailIfExists, null, null, null, PathFormat.RelativePath); } @@ -167,7 +167,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, PathFormat pathFormat) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, CopyOptions.FailIfExists, null, null, null, null, pathFormat); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, CopyOptions.FailIfExists, null, null, null, pathFormat); } @@ -191,7 +191,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, null, null, null, PathFormat.RelativePath); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, null, null, PathFormat.RelativePath); } @@ -216,7 +216,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, bool overwrite, PathFormat pathFormat) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, null, null, null, pathFormat); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, null, null, pathFormat); } @@ -242,7 +242,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions) { - return CopyMoveCore(null, sourcePath, destinationPath, false, copyOptions, null, null, null, null, PathFormat.RelativePath); + return CopyMoveCore(null, sourcePath, destinationPath, false, copyOptions, null, null, null, PathFormat.RelativePath); } @@ -267,7 +267,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, PathFormat pathFormat) { - return CopyMoveCore(null, sourcePath, destinationPath, false, copyOptions, null, null, null, null, pathFormat); + return CopyMoveCore(null, sourcePath, destinationPath, false, copyOptions, null, null, null, pathFormat); } @@ -292,7 +292,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates) { - return CopyMoveCore(null, sourcePath, destinationPath, preserveDates, copyOptions, null, null, null, null, PathFormat.RelativePath); + return CopyMoveCore(null, sourcePath, destinationPath, preserveDates, copyOptions, null, null, null, PathFormat.RelativePath); } @@ -318,7 +318,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) { - return CopyMoveCore(null, sourcePath, destinationPath, preserveDates, copyOptions, null, null, null, null, pathFormat); + return CopyMoveCore(null, sourcePath, destinationPath, preserveDates, copyOptions, null, null, null, pathFormat); } @@ -347,7 +347,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { - return CopyMoveCore(null, sourcePath, destinationPath, false, copyOptions, null, progressHandler, userProgressData, null, PathFormat.RelativePath); + return CopyMoveCore(null, sourcePath, destinationPath, false, copyOptions, null, progressHandler, userProgressData, PathFormat.RelativePath); } @@ -375,7 +375,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { - return CopyMoveCore(null, sourcePath, destinationPath, false, copyOptions, null, progressHandler, userProgressData, null, pathFormat); + return CopyMoveCore(null, sourcePath, destinationPath, false, copyOptions, null, progressHandler, userProgressData, pathFormat); } @@ -403,7 +403,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData) { - return CopyMoveCore(null, sourcePath, destinationPath, preserveDates, copyOptions, null, progressHandler, userProgressData, null, PathFormat.RelativePath); + return CopyMoveCore(null, sourcePath, destinationPath, preserveDates, copyOptions, null, progressHandler, userProgressData, PathFormat.RelativePath); } @@ -432,7 +432,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { - return CopyMoveCore(null, sourcePath, destinationPath, preserveDates, copyOptions, null, progressHandler, userProgressData, null, pathFormat); + return CopyMoveCore(null, sourcePath, destinationPath, preserveDates, copyOptions, null, progressHandler, userProgressData, pathFormat); } @@ -458,7 +458,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, copyOptions, null, null, null, null, PathFormat.RelativePath); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, copyOptions, null, null, null, PathFormat.RelativePath); } @@ -484,7 +484,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, PathFormat pathFormat) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, copyOptions, null, null, null, null, pathFormat); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, copyOptions, null, null, null, pathFormat); } @@ -510,7 +510,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates) { - return CopyMoveCore(transaction, sourcePath, destinationPath, preserveDates, copyOptions, null, null, null, null, PathFormat.RelativePath); + return CopyMoveCore(transaction, sourcePath, destinationPath, preserveDates, copyOptions, null, null, null, PathFormat.RelativePath); } @@ -537,7 +537,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) { - return CopyMoveCore(transaction, sourcePath, destinationPath, preserveDates, copyOptions, null, null, null, null, pathFormat); + return CopyMoveCore(transaction, sourcePath, destinationPath, preserveDates, copyOptions, null, null, null, pathFormat); } @@ -567,7 +567,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, copyOptions, null, progressHandler, userProgressData, null, PathFormat.RelativePath); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, copyOptions, null, progressHandler, userProgressData, PathFormat.RelativePath); } @@ -596,7 +596,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, copyOptions, null, progressHandler, userProgressData, null, pathFormat); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, copyOptions, null, progressHandler, userProgressData, pathFormat); } @@ -625,7 +625,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData) { - return CopyMoveCore(transaction, sourcePath, destinationPath, preserveDates, copyOptions, null, progressHandler, userProgressData, null, PathFormat.RelativePath); + return CopyMoveCore(transaction, sourcePath, destinationPath, preserveDates, copyOptions, null, progressHandler, userProgressData, PathFormat.RelativePath); } @@ -655,7 +655,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { - return CopyMoveCore(transaction, sourcePath, destinationPath, preserveDates, copyOptions, null, progressHandler, userProgressData, null, pathFormat); + return CopyMoveCore(transaction, sourcePath, destinationPath, preserveDates, copyOptions, null, progressHandler, userProgressData, pathFormat); } @@ -688,10 +688,9 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// that specify how the directory is to be moved. This parameter can be . /// A callback function that is called each time another portion of the file has been copied/moved. This parameter can be . /// The argument to be passed to the callback function. This parameter can be . - /// A instance containing Copy or Move action progress. /// Indicates the format of the path parameter(s). [SecurityCritical] - internal static CopyMoveResult CopyMoveCore(KernelTransaction transaction, string sourcePath, string destinationPath, bool preserveDates, CopyOptions? copyOptions, MoveOptions? moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, CopyMoveResult copyMoveResult, PathFormat pathFormat) + internal static CopyMoveResult CopyMoveCore(KernelTransaction transaction, string sourcePath, string destinationPath, bool preserveDates, CopyOptions? copyOptions, MoveOptions? moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { string sourcePathLp; string destinationPathLp; @@ -724,7 +723,7 @@ internal static CopyMoveResult CopyMoveCore(KernelTransaction transaction, strin pathFormat = PathFormat.LongFullPath; - var cmr = copyMoveResult ?? new CopyMoveResult(sourcePath, destinationPath, isCopy, true, preserveDates, emulateMove); + var cmr = new CopyMoveResult(sourcePath, destinationPath, isCopy, true, preserveDates, emulateMove); if (isCopy) @@ -745,7 +744,7 @@ internal static CopyMoveResult CopyMoveCore(KernelTransaction transaction, strin } else - cmr = CopyDeleteCore(transaction, sourcePathLp, destinationPathLp, preserveDates, emulateMove, copyOptions, progressHandler, userProgressData, cmr); + CopyDeleteCore(transaction, sourcePathLp, destinationPathLp, preserveDates, emulateMove, copyOptions, progressHandler, userProgressData, cmr); } // Move @@ -780,11 +779,8 @@ internal static CopyMoveResult CopyMoveCore(KernelTransaction transaction, strin } - private static CopyMoveResult CopyDeleteCore(KernelTransaction transaction, string sourcePathLp, string destinationPathLp, bool preserveDates, bool emulateMove, CopyOptions? copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, CopyMoveResult copyMoveResult) + private static void CopyDeleteCore(KernelTransaction transaction, string sourcePathLp, string destinationPathLp, bool preserveDates, bool emulateMove, CopyOptions? copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, CopyMoveResult copyMoveResult) { - var cmr = copyMoveResult ?? new CopyMoveResult(sourcePathLp, destinationPathLp, true, true, preserveDates, emulateMove); - - var dirs = new Queue(NativeMethods.DefaultFileBufferSize); dirs.Enqueue(sourcePathLp); @@ -810,7 +806,7 @@ private static CopyMoveResult CopyDeleteCore(KernelTransaction transaction, stri { CreateDirectoryCore(transaction, fseiDestinationPath, null, null, false, PathFormat.LongFullPath); - cmr.TotalFolders++; + copyMoveResult.TotalFolders++; dirs.Enqueue(fseiSourcePath); } @@ -821,9 +817,9 @@ private static CopyMoveResult CopyDeleteCore(KernelTransaction transaction, stri { // File count is done in File.CopyMoveCore method. - cmr = File.CopyMoveCore(transaction, true, false, fseiSourcePath, fseiDestinationPath, copyOptions, null, preserveDates, progressHandler, userProgressData, cmr, PathFormat.LongFullPath); + copyMoveResult = File.CopyMoveCore(transaction, true, false, fseiSourcePath, fseiDestinationPath, copyOptions, null, preserveDates, progressHandler, userProgressData, copyMoveResult, PathFormat.LongFullPath); - if (cmr.IsCanceled) + if (copyMoveResult.IsCanceled) { // Break while loop. dirs.Clear(); @@ -833,9 +829,9 @@ private static CopyMoveResult CopyDeleteCore(KernelTransaction transaction, stri } - if (cmr.ErrorCode == Win32Errors.ERROR_SUCCESS) + if (copyMoveResult.ErrorCode == Win32Errors.ERROR_SUCCESS) { - cmr.TotalBytes += fseiSource.FileSize; + copyMoveResult.TotalBytes += fseiSource.FileSize; if (emulateMove) File.DeleteFileCore(transaction, fseiSourcePath, true, PathFormat.LongFullPath); @@ -845,7 +841,7 @@ private static CopyMoveResult CopyDeleteCore(KernelTransaction transaction, stri } - if (cmr.ErrorCode == Win32Errors.ERROR_SUCCESS) + if (copyMoveResult.ErrorCode == Win32Errors.ERROR_SUCCESS) { if (preserveDates) { @@ -866,9 +862,6 @@ private static CopyMoveResult CopyDeleteCore(KernelTransaction transaction, stri if (emulateMove) DeleteDirectoryCore(transaction, null, sourcePathLp, true, true, true, PathFormat.LongFullPath); } - - - return cmr; } diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Move.cs b/AlphaFS/Filesystem/Directory Class/Directory.Move.cs index a1e8444f3..30f000dae 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Move.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Move.cs @@ -47,7 +47,7 @@ partial class Directory [SecurityCritical] public static void Move(string sourcePath, string destinationPath) { - CopyMoveCore(null, sourcePath, destinationPath, false, null, MoveOptions.None, null, null, null, PathFormat.RelativePath); + CopyMoveCore(null, sourcePath, destinationPath, false, null, MoveOptions.None, null, null, PathFormat.RelativePath); } #endregion // .NET @@ -73,7 +73,7 @@ public static void Move(string sourcePath, string destinationPath) [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, PathFormat pathFormat) { - return CopyMoveCore(null, sourcePath, destinationPath, false, null, MoveOptions.None, null, null, null, pathFormat); + return CopyMoveCore(null, sourcePath, destinationPath, false, null, MoveOptions.None, null, null, pathFormat); } @@ -97,7 +97,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Pat [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, MoveOptions.None, null, null, null, PathFormat.RelativePath); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, MoveOptions.None, null, null, PathFormat.RelativePath); } @@ -122,7 +122,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, PathFormat pathFormat) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, MoveOptions.None, null, null, null, pathFormat); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, MoveOptions.None, null, null, pathFormat); } @@ -148,7 +148,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions) { - return CopyMoveCore(null, sourcePath, destinationPath, false, null, moveOptions, null, null, null, PathFormat.RelativePath); + return CopyMoveCore(null, sourcePath, destinationPath, false, null, moveOptions, null, null, PathFormat.RelativePath); } @@ -173,7 +173,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { - return CopyMoveCore(null, sourcePath, destinationPath, false, null, moveOptions, null, null, null, pathFormat); + return CopyMoveCore(null, sourcePath, destinationPath, false, null, moveOptions, null, null, pathFormat); } @@ -200,7 +200,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { - return CopyMoveCore(null, sourcePath, destinationPath, false, null, moveOptions, progressHandler, userProgressData, null, PathFormat.RelativePath); + return CopyMoveCore(null, sourcePath, destinationPath, false, null, moveOptions, progressHandler, userProgressData, PathFormat.RelativePath); } @@ -228,7 +228,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov [SecurityCritical] public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { - return CopyMoveCore(null, sourcePath, destinationPath, false, null, moveOptions, progressHandler, userProgressData, null, pathFormat); + return CopyMoveCore(null, sourcePath, destinationPath, false, null, moveOptions, progressHandler, userProgressData, pathFormat); } @@ -255,7 +255,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, moveOptions, null, null, null, PathFormat.RelativePath); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, moveOptions, null, null, PathFormat.RelativePath); } /// [AlphaFS] Moves a file or a directory and its contents to a new location, can be specified. @@ -280,7 +280,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, moveOptions, null, null, null, pathFormat); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, moveOptions, null, null, pathFormat); } @@ -309,7 +309,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, moveOptions, progressHandler, userProgressData, null, PathFormat.RelativePath); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, moveOptions, progressHandler, userProgressData, PathFormat.RelativePath); } /// [AlphaFS] Moves a file or a directory and its contents to a new location, can be specified, @@ -338,7 +338,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin [SecurityCritical] public static CopyMoveResult MoveTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { - return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, moveOptions, progressHandler, userProgressData, null, pathFormat); + return CopyMoveCore(transaction, sourcePath, destinationPath, false, null, moveOptions, progressHandler, userProgressData, pathFormat); } } } diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs index 2d485f148..215758d90 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs @@ -413,7 +413,7 @@ private CopyMoveResult CopyToMoveToCore(string destinationPath, bool preserveDat { longFullPath = Path.GetExtendedLengthPathCore(Transaction, destinationPath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); - return Directory.CopyMoveCore(Transaction, LongFullName, longFullPath, preserveDates, copyOptions, moveOptions, progressHandler, userProgressData, null, PathFormat.LongFullPath); + return Directory.CopyMoveCore(Transaction, LongFullName, longFullPath, preserveDates, copyOptions, moveOptions, progressHandler, userProgressData, PathFormat.LongFullPath); } } } diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs index 36b23bfd7..04b44f5a1 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs @@ -655,7 +655,7 @@ internal static partial class NativeMethods /// An application-defined callback function used with the CopyFileEx, MoveFileTransacted, and MoveFileWithProgress functions. /// It is called when a portion of a copy or move operation is completed. /// The LPPROGRESS_ROUTINE type defines a pointer to this callback function. - /// NativeCopyMoveProgressRoutine (NativeCopyMoveProgressRoutine) is a placeholder for the application-defined function name. + /// NativeCopyMoveProgressRoutine is a placeholder for the application-defined function name. /// [SuppressUnmanagedCodeSecurity] internal delegate CopyMoveProgressResult NativeCopyMoveProgressRoutine([MarshalAs(UnmanagedType.I8)] long totalFileSize, [MarshalAs(UnmanagedType.I8)] long totalBytesTransferred, [MarshalAs(UnmanagedType.I8)] long streamSize, [MarshalAs(UnmanagedType.I8)] long streamBytesTransferred, [MarshalAs(UnmanagedType.U4)] uint dwStreamNumber, [MarshalAs(UnmanagedType.U4)] CopyMoveProgressCallbackReason dwCallbackReason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData); diff --git a/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs b/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs new file mode 100644 index 000000000..320768c2c --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs @@ -0,0 +1,51 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// Contains detected drive parameters. + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct DISK_DETECTION_INFO + { + /// The size of the structure, in bytes. + [MarshalAs(UnmanagedType.U4)] public readonly uint SizeOfDetectInfo; + + /// The detected partition type. This member can be one of the following values from the enumeration. + public readonly DetectionType DetectionType; + + /// + /// Union of and structs. + /// If DetectionType is DetectInt13, the union is a DISK_INT13_INFO structure. + /// If DetectionType is DetectExInt13, the union is a DISK_EX_INT13_INFO structure. + /// + public DiskInt13Union DiskInt13Union; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs b/AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs new file mode 100644 index 000000000..2bd45bad3 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs @@ -0,0 +1,60 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// Contains extended Int13 drive parameters. + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct DISK_EX_INT13_INFO + { + /// The size of the extended drive parameter buffer for this partition or disk. For valid values, see the BIOS documentation. + [MarshalAs(UnmanagedType.U2)] public readonly ushort ExBufferSize; + + /// The information flags for this partition or disk. For valid values, see the BIOS documentation. + [MarshalAs(UnmanagedType.U2)] public readonly ushort ExFlags; + + /// The number of cylinders per head. For valid values, see the BIOS documentation. + [MarshalAs(UnmanagedType.U4)] public readonly uint ExCylinders; + + /// The maximum number of heads for this hard disk. For valid values, see the BIOS documentation. + [MarshalAs(UnmanagedType.U4)] public readonly uint ExHeads; + + /// The number of sectors per track. For valid values, see the BIOS documentation. + [MarshalAs(UnmanagedType.U4)] public readonly uint ExSectorsPerTrack; + + /// The total number of sectors for this disk. For valid values, see the BIOS documentation. + [MarshalAs(UnmanagedType.U8)] public readonly ulong ExSectorsPerDrive; + + /// The sector size for this disk. For valid values, see the BIOS documentation. + [MarshalAs(UnmanagedType.U2)] public readonly ushort ExSectorSize; + + /// Reserved for future use. + [MarshalAs(UnmanagedType.U2)] public readonly ushort ExReserved; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs index b4195805b..90356052a 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs @@ -25,28 +25,27 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Describes the geometry of disk devices and media. - /// + /// Describes the geometry of disk devices and media. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct DISK_GEOMETRY { /// The number of cylinders. - [MarshalAs(UnmanagedType.U8)] public long Cylinders; + [MarshalAs(UnmanagedType.I8)] public readonly long Cylinders; /// The type of media. - [MarshalAs(UnmanagedType.U4)] public STORAGE_MEDIA_TYPE MediaType; + [MarshalAs(UnmanagedType.U4)] public readonly STORAGE_MEDIA_TYPE MediaType; /// The number of tracks per cylinder. - [MarshalAs(UnmanagedType.U4)] public uint TracksPerCylinder; + [MarshalAs(UnmanagedType.U4)] public readonly uint TracksPerCylinder; /// The number of sectors per track. - [MarshalAs(UnmanagedType.U4)] public uint SectorsPerTrack; + [MarshalAs(UnmanagedType.U4)] public readonly uint SectorsPerTrack; /// The number of bytes per sector. - [MarshalAs(UnmanagedType.U4)] public uint BytesPerSector; + [MarshalAs(UnmanagedType.U4)] public readonly uint BytesPerSector; } } } diff --git a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs index 69f436f46..e101ec026 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs @@ -25,22 +25,27 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Describes the extended geometry of disk devices and media. - /// + /// Describes the extended geometry of disk devices and media. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct DISK_GEOMETRY_EX + internal struct DISK_GEOMETRY_EX { - /// A structure. + /// Describes the geometry of disk devices and media. public DISK_GEOMETRY Geometry; /// The disk size, in bytes. - [MarshalAs(UnmanagedType.U8)] public readonly ulong DiskSize; + [MarshalAs(UnmanagedType.I8)] public long DiskSize; - /// Any additional data. - [MarshalAs(UnmanagedType.I1)] public readonly byte Data; + ///// Any additional data. + //[MarshalAs(UnmanagedType.I1)] public readonly byte Data; + + /// Contains the disk partition information. + public DISK_PARTITION_INFO PartitionInformation; + + /// Contains detected drive parameters. + public DISK_DETECTION_INFO DiskDetectionInfo; } } } diff --git a/AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs b/AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs new file mode 100644 index 000000000..cdeb37c30 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs @@ -0,0 +1,64 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// + /// The DISK_INT13_INFO structure is used by the BIOS to report disk detection data for a partition with an INT13 format. + /// + /// MSDN: http://msdn.microsoft.com/en-us/library/windows/hardware/ff552624(v=vs.85).aspx + [StructLayout(LayoutKind.Sequential)] + internal struct DISK_INT13_INFO + { + /// + /// Corresponds to the Device/Head register defined in the AT Attachment (ATA) specification. When zero, the fourth bit of this register + /// indicates that drive zero is selected. When 1, it indicates that drive one is selected. The values of bits 0, 1, 2, 3, and 6 depend + /// on the command in the command register. Bits 5 and 7 are no longer used. For more information about the values that the Device/Head + /// register can hold, see the ATA specification. + /// + public ushort DriveSelect; + + /// + /// Indicates the maximum number of cylinders on the disk. + /// + public ulong MaxCylinders; + + /// + /// Indicates the number of sectors per track. + /// + public ushort SectorsPerTrack; + + /// + /// Indicates the maximum number of disk heads. + /// + public ushort MaxHeads; + + /// + /// Indicates the number of drives. + /// + public ushort NumberDrives; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs b/AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs new file mode 100644 index 000000000..bdf4926ab --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs @@ -0,0 +1,56 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace Alphaleonis.Win32.Filesystem +{ + internal static partial class NativeMethods + { + /// Contains the disk partition information. + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] + internal struct DISK_PARTITION_INFO + { + /// The size of this structure, in bytes. + [FieldOffset(0)] [MarshalAs(UnmanagedType.U4)] + public readonly uint SizeOfPartitionInfo; + + /// The format of a partition. + [FieldOffset(4)] [MarshalAs(UnmanagedType.U4)] + public readonly PARTITION_STYLE PartitionStyle; + + /// Signature: MBR signature of the partition. + /// If PartitionStyle is PARTITION_STYLE_MBR (0), the union is a structure that contains information for an master boot record partition, which includes a disk signature and a checksum. + /// + [FieldOffset(8)] [MarshalAs(UnmanagedType.U4)] + public readonly uint MbrSignature; + + /// DiskId: GUID of the GPT partition. + /// If PartitionStyle is PARTITION_STYLE_GPT (1), the union is a structure that contains information for a GUID partition table partition, which includes a disk identifier (GUID). + /// + [FieldOffset(8)] public Guid DiskId; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs index 6160bc574..da3a391ab 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs @@ -33,7 +33,7 @@ internal static partial class NativeMethods [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] internal struct DRIVE_LAYOUT_INFORMATION_EX { - /// The style of the partitions on the drive enumerated by the enumeration. + /// The style of the partitions on the drive enumerated by the enumeration. [FieldOffset(0)] [MarshalAs(UnmanagedType.U4)] public readonly PartitionStyle PartitionStyle; @@ -41,8 +41,10 @@ internal struct DRIVE_LAYOUT_INFORMATION_EX [FieldOffset(4)] [MarshalAs(UnmanagedType.U4)] public readonly uint PartitionCount; + /// A structure containing information about the master boot record type partitioning on the drive. [FieldOffset(8)] public DRIVE_LAYOUT_INFORMATION_MBR Mbr; + /// A structure containing information about the GUID disk partition type partitioning on the drive. [FieldOffset(8)] public DRIVE_LAYOUT_INFORMATION_GPT Gpt; } } diff --git a/AlphaFS/Filesystem/Native Other/DiskInt13Union.cs b/AlphaFS/Filesystem/Native Other/DiskInt13Union.cs new file mode 100644 index 000000000..0a6b16ae9 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DiskInt13Union.cs @@ -0,0 +1,47 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Filesystem +{ + internal static partial class NativeMethods + { + /// + /// Un-named struct for structure + /// + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] + internal struct DiskInt13Union + { + /// + /// for member description + /// + [FieldOffset(0)] + public DISK_INT13_INFO Int13; + + /// + /// for member description + /// + [FieldOffset(0)] + public DISK_EX_INT13_INFO ExInt13; + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/IoControlCode.cs b/AlphaFS/Filesystem/Native Other/IoControlCode.cs index 72aeb3ba3..bae3b2aeb 100644 --- a/AlphaFS/Filesystem/Native Other/IoControlCode.cs +++ b/AlphaFS/Filesystem/Native Other/IoControlCode.cs @@ -139,37 +139,20 @@ internal enum IoControlCode : uint #region FILE_DEVICE_DISK - ///// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). - //[Obsolete("MSDN: IOCTL_DISK_GET_DRIVE_GEOMETRY has been superseded by IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, which retrieves additional information.")] - //IOCTL_DISK_GET_DRIVE_GEOMETRY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0000 << 2) | IoMethod.Buffered | (0 << 14), - - /// - /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). - /// The difference between IOCTL_DISK_GET_DRIVE_GEOMETRY_EX and the older IOCTL_DISK_GET_DRIVE_GEOMETRY request is that - /// IOCTL_DISK_GET_DRIVE_GEOMETRY_EX can retrieve information from both Master Boot Record (MBR) and GUID Partition Table (GPT)-type - /// partitioned media, whereas IOCTL_DISK_GET_DRIVE_GEOMETRY can only read MBR-style media. + /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). + /// IOCTL_DISK_GET_DRIVE_GEOMETRY_EX can retrieve information from both Master Boot Record (MBR) and GUID Partition Table (GPT)-type partitioned media. /// IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0028 << 2) | IoMethod.Buffered | (0 << 14), - ///// Returns information about the type, size, and nature of a disk partition. (Floppy drivers need not handle this request.) - //[Obsolete("IOCTL_DISK_GET_PARTITION_INFO is superseded by IOCTL_DISK_GET_PARTITION_INFO_EX, which retrieves partition information for AT and Extensible Firmware Interface (EFI) partitions.")] - //IOCTL_DISK_GET_PARTITION_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0001 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), - + ///////// Returns information about the type, size, and nature of a disk partition. (Floppy drivers need not handle this request.) + //IOCTL_DISK_GET_PARTITION_INFO_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0012 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), - /////// Returns information about the type, size, and nature of a disk partition. (Floppy drivers need not handle this request.) - IOCTL_DISK_GET_PARTITION_INFO_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0012 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), - ///// Changes the partition type of the specified disk partition. (Floppy drivers need not handle this request.) //IOCTL_DISK_SET_PARTITION_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0002 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), - ///// Returns information about the number of partitions, disk signature, and features of each partition on a disk. (Floppy drivers need not handle this request.) - //[Obsolete("IOCTL_DISK_GET_DRIVE_LAYOUT has been superseded by IOCTL_DISK_GET_DRIVE_LAYOUT_EX, which retrieves layout information for AT and EFI (Extensible Firmware Interface) partitions.")] - //IOCTL_DISK_GET_DRIVE_LAYOUT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0003 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), - - /// Contains extended information about a drive's partitions. IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0014 << 2) | IoMethod.Buffered | (0 << 14), @@ -578,7 +561,6 @@ internal enum IoControlCode : uint ///// Retrieves the set of update sequence number (USN) change journal records between two specified USN values. - ///// MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/aa364586(v=vs.85).aspx //FSCTL_READ_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (46 << 2) | IoMethod.Neither | (0 << 14), diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs index c362aeec5..dd785f75d 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs @@ -291,12 +291,14 @@ public enum STORAGE_MEDIA_TYPE /// STK 9940. STK_9940 = 92, - /// SAIT tape. - /// Windows Server 2003: This is not supported before Windows Server 2003 with SP1. + /// SAIT tape. + /// Windows Server 2003: This is not supported before Windows Server 2003 with SP1. + /// SAIT = 93, - /// Exabyte VXA tape. - /// Windows Server 2008: This is not supported before Windows Server 2008. + /// Exabyte VXA tape. + /// Windows Server 2008: This is not supported before Windows Server 2008. + /// VXATape = 94 } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs b/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs new file mode 100644 index 000000000..ea421c3a0 --- /dev/null +++ b/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs @@ -0,0 +1,36 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// The DETECTION_TYPE enumeration type is used in conjunction with the IOCTL_DISK_GET_DRIVE_GEOMETRY_EX request and the DISK_GEOMETRY_EX structure to determine the type of formatting used by the BIOS to record the disk geometry. + public enum DetectionType : uint + { + /// Indicates that the disk contains neither an INT 13h partition nor an extended INT 13h partition. + DetectNone = 0, + + /// Indicates that the disk has a standard INT 13h partition. + DetectInt13 = 1, + + /// Indicates that the disk contains an extended INT 13h partition. + DetectExInt13 = 2 + } +} diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionTypes.cs b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionTypes.cs index 98781175a..b1c474da3 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionTypes.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionTypes.cs @@ -32,43 +32,51 @@ public enum DiskPartitionTypes : byte UnusedEntry = 0, /// A FAT12 file system partition. - FAT12 = 1, + Fat12 = 1, - XENIX1 = 2, - XENIX2 = 3, + /// A XENIX1 partition. + Xenix1 = 2, + + /// A XENIX2 partition. + Xenix2 = 3, /// A FAT16 file system partition. - FAT16 = 4, + Fat16 = 4, /// An extended partition. Extended = 5, + /// A huge partition. Huge = 6, /// An IFS (Installable File System) partition. - IFS = 7, + Ifs = 7, /// A FAT32 file system partition. - FAT32 = 11, + Fat32 = 11, + + /// A FAT32 XINT13 partition. + Fat32XInt13 = 12, - FAT32XINT13 = 12, - XINT13 = 14, - XINT13Extended = 15, + /// An XINT13 partition. + XInt13 = 14, + /// An XINT13 Extended partition. + XInt13Extended = 15, /// A PREP (Power PC Reference Platform) partition. Prep = 65, /// An LDM (Logical Disk Manager) partition. - LDF = 66, + Ldf = 66, /// A UNIX partition. - UNIX = 99, + Unix = 99, /// An NTFT partition. - NTFT = 128, + Ntft = 128, /// A valid NTFT partition. - ValidNTFT = 192, + ValidNtft = 192, } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/MoveOptions.cs b/AlphaFS/Filesystem/Structures, Enumerations/MoveOptions.cs index ed7594309..92fea2731 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/MoveOptions.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/MoveOptions.cs @@ -42,7 +42,7 @@ public enum MoveOptions /// MOVE_FILE_COPY_ALLOWED /// If the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions. - /// This value cannot be used with . + /// This value cannot be used with . /// CopyAllowed = NativeMethods.MOVE_FILE_FLAGS.MOVE_FILE_COPY_ALLOWED, @@ -56,7 +56,7 @@ public enum MoveOptions /// 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. /// - /// This value cannot be used with . + /// This value cannot be used with . /// DelayUntilReboot = NativeMethods.MOVE_FILE_FLAGS.MOVE_FILE_DELAY_UNTIL_REBOOT, @@ -67,7 +67,7 @@ public enum MoveOptions /// 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. /// - /// This value has no effect if is set. + /// This value has no effect if is set. /// WriteThrough = NativeMethods.MOVE_FILE_FLAGS.MOVE_FILE_WRITE_THROUGH, diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionAttributes.cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionAttributes.cs index c3e72ab4e..14846976b 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionAttributes.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionAttributes.cs @@ -23,6 +23,7 @@ namespace Alphaleonis.Win32.Filesystem { + /// The different (GPT) partition attributes. [Flags] public enum PartitionAttributes : ulong { @@ -32,7 +33,10 @@ public enum PartitionAttributes : ulong /// If this attribute is set, the partition is required by a Computer to function properly. PlatformRequired = NativeMethods.PartitionAttributes.GPT_ATTRIBUTE_PLATFORM_REQUIRED, - LegacyBIOSBootable = 0x0000000000000004, + /// + /// + /// + LegacyBIOSBootable = 4, /// If this attribute is set, the partition is read-only. ReadOnly = NativeMethods.PartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY, diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs index fa48df629..065821f8b 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs @@ -29,7 +29,7 @@ public enum PartitionType /// This value can be set for basic and dynamic disks. /// [Description("00000000-0000-0000-0000-000000000000")] - UnusedGuid, + Unused, /// PARTITION_BASIC_DATA_GUID: The data partition type that is created and recognized by Windows. /// @@ -38,192 +38,36 @@ public enum PartitionType /// /// [Description("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7")] - BasicDataGuid, + BasicData, /// PARTITION_LDM_DATA_GUID: The partition is an LDM data partition on a dynamic disk. /// This value can be set only for dynamic disks. /// [Description("AF9B60A0-1431-4F62-BC68-3311714A69AD")] - LdmDataGuid, + LdmData, /// PARTITION_LDM_METADATA_GUID: The partition is a Logical Disk Manager (LDM) metadata partition on a dynamic disk. /// This value can be set only for dynamic disks. /// [Description("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3")] - LdmMetaDataGuid, + LdmMetaData, /// PARTITION_MSFT_RECOVERY_GUID: The partition is a Microsoft recovery partition. /// This value can be set for basic and dynamic disks. /// [Description("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC")] - MsftRecoveryguid, + MsftRecovery, /// PARTITION_MSFT_RESERVED_GUID: The partition is a Microsoft reserved partition. /// This value can be set for basic and dynamic disks. /// [Description("E3C9E316-0B5C-4DB8-817D-F92DF00215AE")] - MsftReservedGuid, + MsftReserved, /// PARTITION_SYSTEM_GUID: The partition is an EFI system partition. /// This value can be set for basic and dynamic disks. /// [Description("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")] - SystemGuid + System } - - - ///// A wrapper class which represents the possible media types for DirectShow. Since a MediaType is a Guid, a simple enum couldn't be used. - //internal class PartitionTypeGuid : AbstractGuidEnum - //{ - // /// Creates a new PartitionTypeGuid instance, wrapping the given GUID. - // /// The GUID to wrap. - // public PartitionTypeGuid(Guid guid) : base(guid) - // { - // } - - - // public PartitionTypeGuid(PartitionType partitionType) : base(partitionType) - // { - // } - - - // protected override void FillTypeList(Dictionary typeList) - // { - // typeList.Add(NativeMethods.PartitionType.PARTITION_ENTRY_UNUSED_GUID, PartitionType.UnusedGuid); - - // typeList.Add(NativeMethods.PartitionType.PARTITION_BASIC_DATA_GUID, PartitionType.BasicDataGuid); - - // typeList.Add(NativeMethods.PartitionType.PARTITION_LDM_DATA_GUID, PartitionType.LdmDataGuid); - - // typeList.Add(NativeMethods.PartitionType.PARTITION_LDM_METADATA_GUID, PartitionType.LdmMetaDataGuid); - - // typeList.Add(NativeMethods.PartitionType.PARTITION_MSFT_RECOVERY_GUID, PartitionType.MsftRecoveryguid); - - // typeList.Add(NativeMethods.PartitionType.PARTITION_MSFT_RESERVED_GUID, PartitionType.MsftReservedGuid); - - // typeList.Add(NativeMethods.PartitionType.PARTITION_SYSTEM_GUID, PartitionType.SystemGuid); - // } - //} - - - ///// An abstract class to represent a set of GUIDs as an enum. - ///// An enum to use for the type to expose. - //internal abstract class AbstractGuidEnum - //{ - // /// The internal GUID. - // public Guid Guid { get; private set; } - - - // /// The enum type for this GUID. - // public T Type { get; private set; } - - - // /// Specifies whether the GUID is known as a specific type or not. - // public bool IsKnownType { get; private set; } - - - // /// List matching GUIDs with the enum types. - // private static Dictionary _typeList; - - - // /// Create a new GUID enum wrapping the given GUID. - // /// - // protected AbstractGuidEnum(Guid guid) - // { - // Guid = guid; - - // IsKnownType = IsGuidKnownType(guid); - - // if (IsKnownType) - // Type = GetType(guid); - // } - - - // /// Create a new GUID enum for the specified type. - // /// - // protected AbstractGuidEnum(T type) - // { - // Type = type; - // Guid = GetGuid(type); - // } - - - // /// Call to make sure the list of types is initialized. - // private void InitializeTypes() - // { - // if (null == _typeList) - // { - // _typeList = new Dictionary(); - - // FillTypeList(_typeList); - // } - // } - - - // public bool IsGuidKnownType(Guid guid) - // { - // InitializeTypes(); - - // return _typeList.ContainsKey(guid); - // } - - - // /// Returns the type for a given GUID. - // /// The GUID to get the type for. - // /// The type for the given GUID. - // public T GetType(Guid type) - // { - // InitializeTypes(); - - // if (!_typeList.ContainsKey(type)) - // throw new ArgumentException("No type is defined for the given GUID.", "type"); - - // return _typeList[type]; - // } - - - // /// Return the guid for a given type. - // /// The Type to get the Guid for. - // /// The Guid for the given type. - // /// Thrown when no Guid exists for the given type. - // private Guid GetGuid(T type) - // { - // InitializeTypes(); - - - // try - // { - // return _typeList.Keys.First(guid => _typeList[guid].Equals(type)); - // } - // catch (InvalidOperationException) - // { - // throw new InvalidCastException("No Guid exists for the given type."); - // } - // } - - - // public override bool Equals(object obj) - // { - // if (!(obj is AbstractGuidEnum)) - // return false; - - // AbstractGuidEnum guidObj = obj as AbstractGuidEnum; - - // return Guid.Equals(guidObj.Guid); - // } - - - // public override int GetHashCode() - // { - // unchecked - // { - // return Guid.GetHashCode(); - // } - // } - - - // /// Fill up the list which matches GUIDs to the desired enum types. - // /// - // protected abstract void FillTypeList(Dictionary typeList); - //} } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs index b631ae9d9..fb769181d 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs @@ -19,8 +19,6 @@ * THE SOFTWARE. */ -using System.Diagnostics.CodeAnalysis; - namespace Alphaleonis.Win32.Filesystem { /// Provides a symbolic means of representing storage bus types. @@ -30,61 +28,48 @@ public enum StorageBusType Unknown = NativeMethods.STORAGE_BUS_TYPE.BusTypeUnknown, /// Indicates a SCSI bus type. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SCSI")] - SCSI = NativeMethods.STORAGE_BUS_TYPE.BusTypeScsi, + Scsi = NativeMethods.STORAGE_BUS_TYPE.BusTypeScsi, /// Indicates an ATAPI bus type. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ATAPI")] - ATAPI = NativeMethods.STORAGE_BUS_TYPE.BusTypeAtapi, + Atapi = NativeMethods.STORAGE_BUS_TYPE.BusTypeAtapi, /// Indicates an ATA bus type. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ATA")] - ATA = NativeMethods.STORAGE_BUS_TYPE.BusTypeAta, + Ata = NativeMethods.STORAGE_BUS_TYPE.BusTypeAta, /// Indicates an IEEE 1394 bus type. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "IEEE")] - IEEE1394 = NativeMethods.STORAGE_BUS_TYPE.BusType1394, + Ieee1394 = NativeMethods.STORAGE_BUS_TYPE.BusType1394, /// Indicates an SSA bus type. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSA")] - SSA = NativeMethods.STORAGE_BUS_TYPE.BusTypeSsa, + Ssa = NativeMethods.STORAGE_BUS_TYPE.BusTypeSsa, /// Indicates a fiber channel bus type. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fibre")] Fibre = NativeMethods.STORAGE_BUS_TYPE.BusTypeFibre, /// Indicates a USB bus type. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "USB")] - USB = NativeMethods.STORAGE_BUS_TYPE.BusTypeUsb, + Usb = NativeMethods.STORAGE_BUS_TYPE.BusTypeUsb, /// Indicates a RAID bus type. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "RAID")] - RAID = NativeMethods.STORAGE_BUS_TYPE.BusTypeRAID, + Raid = NativeMethods.STORAGE_BUS_TYPE.BusTypeRAID, /// Indicates an iSCSI bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SCSI")] - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "i")] - iSCSI = NativeMethods.STORAGE_BUS_TYPE.BusTypeiScsi, + iScsi = NativeMethods.STORAGE_BUS_TYPE.BusTypeiScsi, /// Indicates a serial-attached SCSI (SAS) bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SAS")] - SAS = NativeMethods.STORAGE_BUS_TYPE.BusTypeSas, + Sas = NativeMethods.STORAGE_BUS_TYPE.BusTypeSas, /// Indicates a SATA bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SATA")] - SATA = NativeMethods.STORAGE_BUS_TYPE.BusTypeSata, + Sata = NativeMethods.STORAGE_BUS_TYPE.BusTypeSata, /// Indicates a secure digital (SD) bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. - SD = NativeMethods.STORAGE_BUS_TYPE.BusTypeSd, + Sd = NativeMethods.STORAGE_BUS_TYPE.BusTypeSd, /// Indicates a multimedia card (MMC) bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "MMC")] - MMC = NativeMethods.STORAGE_BUS_TYPE.BusTypeMmc, + Mmc = NativeMethods.STORAGE_BUS_TYPE.BusTypeMmc, /// Indicates a virtual bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs new file mode 100644 index 000000000..839d6a90a --- /dev/null +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs @@ -0,0 +1,298 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// Specifies various types of storage media. + public enum StorageMediaType + { + /// Format is unknown. + Unknown = NativeMethods.STORAGE_MEDIA_TYPE.Unknown, + + /// A 5.25" floppy, with 1.2MB and 512 bytes/sector. + Floppy51Pt2512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_1Pt2_512, + + /// A 3.5" floppy, with 1.44MB and 512 bytes/sector. + Floppy31Pt44512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_1Pt44_512, + + /// A 3.5" floppy, with 2.88MB and 512 bytes/sector. + Floppy32Pt88512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_2Pt88_512, + + /// A 3.5" floppy, with 20.8MB and 512 bytes/sector. + Floppy320Pt8512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_20Pt8_512, + + /// A 3.5" floppy, with 720KB and 512 bytes/sector. + Floppy3720512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_720_512, + + /// A 5.25" floppy, with 360KB and 512 bytes/sector. + Floppy5360512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_360_512, + + /// A 5.25" floppy, with 320KB and 512 bytes/sector. + Floppy5320512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_320_512, + + /// A 5.25" floppy, with 320KB and 1024 bytes/sector. + Floppy53201024 = NativeMethods.STORAGE_MEDIA_TYPE.F5_320_1024, + + /// A 5.25" floppy, with 180KB and 512 bytes/sector. + Floppy5180512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_180_512, + + /// A 5.25" floppy, with 160KB and 512 bytes/sector. + Floppy5160512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_160_512, + + /// Removable media other than floppy. + RemovableMedia = NativeMethods.STORAGE_MEDIA_TYPE.RemovableMedia, + + /// Fixed hard disk media. + FixedMedia = NativeMethods.STORAGE_MEDIA_TYPE.FixedMedia, + + /// A 3.5" floppy, with 120MB and 512 bytes/sector. + Floppy3120M512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_120M_512, + + /// A 3.5" floppy, with 640KB and 512 bytes/sector. + Floppy3640512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_640_512, + + /// A 5.25" floppy, with 640KB and 512 bytes/sector. + Floppy5640512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_640_512, + + /// A 5.25" floppy, with 720KB and 512 bytes/sector. + Floppy5720512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_720_512, + + /// A 3.5" floppy, with 1.2MB and 512 bytes/sector. + Floppy31Pt2512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_1Pt2_512, + + /// A 3.5" floppy, with 1.23MB and 1024 bytes/sector. + Floppy31Pt231024 = NativeMethods.STORAGE_MEDIA_TYPE.F3_1Pt23_1024, + + /// A 5.25" floppy, with 1.23MB and 1024 bytes/sector. + Floppy51Pt231024 = NativeMethods.STORAGE_MEDIA_TYPE.F5_1Pt23_1024, + + /// A 3.5" floppy, with 128MB and 512 bytes/sector. + Floppy3128Mb512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_128Mb_512, + + /// A 3.5" floppy, with 230MB and 512 bytes/sector. + Floppy3230Mb512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_230Mb_512, + + /// An 8" floppy, with 256KB and 128 bytes/sector. + Floppy8256128 = NativeMethods.STORAGE_MEDIA_TYPE.F8_256_128, + + /// A 3.5" floppy, with 200MB and 512 bytes/sector. (HiFD). + Floppy3200Mb512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_200Mb_512, + + /// A 3.5" floppy, with 240MB and 512 bytes/sector. (HiFD). + Floppy3240M512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_240M_512, + + /// A 3.5" floppy, with 32MB and 512 bytes/sector. + Floppy332M512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_32M_512, + + /// One of the following tape types: DAT, DDS1, DDS2, and so on. + Dds4Mm = NativeMethods.STORAGE_MEDIA_TYPE.DDS_4mm, + + /// MiniQIC tape. + MiniQic = NativeMethods.STORAGE_MEDIA_TYPE.MiniQic, + + /// Travan tape (TR-1, TR-2, TR-3, and so on). + Travan = NativeMethods.STORAGE_MEDIA_TYPE.Travan, + + /// QIC tape. + Qic = NativeMethods.STORAGE_MEDIA_TYPE.QIC, + + /// An 8mm Exabyte metal particle tape. + Mp8Mm = NativeMethods.STORAGE_MEDIA_TYPE.MP_8mm, + + /// An 8mm Exabyte advanced metal evaporative tape. + Ame8Mm = NativeMethods.STORAGE_MEDIA_TYPE.AME_8mm, + + /// An 8mm Sony AIT1 tape. + Ait18Mm = NativeMethods.STORAGE_MEDIA_TYPE.AIT1_8mm, + + /// DLT compact tape (IIIxt or IV). + Dlt = NativeMethods.STORAGE_MEDIA_TYPE.DLT, + + /// Philips NCTP tape. + Nctp = NativeMethods.STORAGE_MEDIA_TYPE.NCTP, + + /// IBM 3480 tape. + Ibm3480 = NativeMethods.STORAGE_MEDIA_TYPE.IBM_3480, + + /// IBM 3490E tape. + Ibm3490E = NativeMethods.STORAGE_MEDIA_TYPE.IBM_3490E, + + /// IBM Magstar 3590 tape. + IbmMagstar3590 = NativeMethods.STORAGE_MEDIA_TYPE.IBM_Magstar_3590, + + /// IBM Magstar MP tape. + IbmMagstarMp = NativeMethods.STORAGE_MEDIA_TYPE.IBM_Magstar_MP, + + /// STK data D3 tape. + StkDataD3 = NativeMethods.STORAGE_MEDIA_TYPE.STK_DATA_D3, + + /// Sony DTF tape. + SonyDtf = NativeMethods.STORAGE_MEDIA_TYPE.SONY_DTF, + + /// A 6mm digital videotape. + Dv6Mm = NativeMethods.STORAGE_MEDIA_TYPE.DV_6mm, + + /// Exabyte DMI tape (or compatible). + Dmi = NativeMethods.STORAGE_MEDIA_TYPE.DMI, + + /// Sony D2S or D2L tape. + SonyD2 = NativeMethods.STORAGE_MEDIA_TYPE.SONY_D2, + + /// Cleaner (all drive types that support cleaners). + CleanerCartridge = NativeMethods.STORAGE_MEDIA_TYPE.CLEANER_CARTRIDGE, + + /// CD. + CDRom = NativeMethods.STORAGE_MEDIA_TYPE.CD_ROM, + + /// CD (write once). + CdR = NativeMethods.STORAGE_MEDIA_TYPE.CD_R, + + /// CD (rewriteable). + CdRw = NativeMethods.STORAGE_MEDIA_TYPE.CD_RW, + + /// DVD. + DvdRom = NativeMethods.STORAGE_MEDIA_TYPE.DVD_ROM, + + /// DVD (write once). + DvdR = NativeMethods.STORAGE_MEDIA_TYPE.DVD_R, + + /// DVD (rewriteable). + DvdRw = NativeMethods.STORAGE_MEDIA_TYPE.DVD_RW, + + /// Magneto-optical 3.5" (rewriteable). + Mo3Rw = NativeMethods.STORAGE_MEDIA_TYPE.MO_3_RW, + + /// Magneto-optical 5.25" (write once). + Mo5Wo = NativeMethods.STORAGE_MEDIA_TYPE.MO_5_WO, + + /// Magneto-optical 5.25" (rewriteable; not LIMDOW). + Mo5Rw = NativeMethods.STORAGE_MEDIA_TYPE.MO_5_RW, + + /// Magneto-optical 5.25" (rewriteable; LIMDOW). + Mo5Limdow = NativeMethods.STORAGE_MEDIA_TYPE.MO_5_LIMDOW, + + /// Phase change 5.25" (write once). + Pc5Wo = NativeMethods.STORAGE_MEDIA_TYPE.PC_5_WO, + + /// Phase change 5.25" (rewriteable). + Pc5Rw = NativeMethods.STORAGE_MEDIA_TYPE.PC_5_RW, + + /// Phase change dual (rewriteable). + Pd5Rw = NativeMethods.STORAGE_MEDIA_TYPE.PD_5_RW, + + /// Ablative 5.25" (write once). + Abl5Wo = NativeMethods.STORAGE_MEDIA_TYPE.ABL_5_WO, + + /// Pinnacle Apex 4.6GB (rewriteable) + PinnacleApex5Rw = NativeMethods.STORAGE_MEDIA_TYPE.PINNACLE_APEX_5_RW, + + /// Sony 12" (write once). + Sony12Wo = NativeMethods.STORAGE_MEDIA_TYPE.SONY_12_WO, + + /// Philips/LMS 12" (write once). + Philips12Wo = NativeMethods.STORAGE_MEDIA_TYPE.PHILIPS_12_WO, + + /// Hitachi 12" (write once). + Hitachi12Wo = NativeMethods.STORAGE_MEDIA_TYPE.HITACHI_12_WO, + + /// Cygnet/ATG 12" (write once). + Cygnet12Wo = NativeMethods.STORAGE_MEDIA_TYPE.CYGNET_12_WO, + + /// Kodak 14" (write once). + Kodak14Wo = NativeMethods.STORAGE_MEDIA_TYPE.KODAK_14_WO, + + /// MO near field recording (Terastor). + MoNfr525 = NativeMethods.STORAGE_MEDIA_TYPE.MO_NFR_525, + + /// Nikon 12" (rewriteable). + Nikon12Rw = NativeMethods.STORAGE_MEDIA_TYPE.NIKON_12_RW, + + /// Iomega Zip. + IomegaZip = NativeMethods.STORAGE_MEDIA_TYPE.IOMEGA_ZIP, + + /// Iomega Jaz. + IomegaJaz = NativeMethods.STORAGE_MEDIA_TYPE.IOMEGA_JAZ, + + /// Syquest EZ135. + SyquestEz135 = NativeMethods.STORAGE_MEDIA_TYPE.SYQUEST_EZ135, + + /// Syquest EzFlyer. + SyquestEzflyer = NativeMethods.STORAGE_MEDIA_TYPE.SYQUEST_EZFLYER, + + /// Syquest SyJet. + SyquestSyjet = NativeMethods.STORAGE_MEDIA_TYPE.SYQUEST_SYJET, + + /// Avatar 2.5" floppy. + AvatarF2 = NativeMethods.STORAGE_MEDIA_TYPE.AVATAR_F2, + + /// An 8mm Hitachi tape. + Mp28Mm = NativeMethods.STORAGE_MEDIA_TYPE.MP2_8mm, + + /// Ampex DST small tape. + DstS = NativeMethods.STORAGE_MEDIA_TYPE.DST_S, + + /// Ampex DST medium tape. + DstM = NativeMethods.STORAGE_MEDIA_TYPE.DST_M, + + /// Ampex DST large tape. + DstL = NativeMethods.STORAGE_MEDIA_TYPE.DST_L, + + /// Ecrix 8mm tape. + VxaTape1 = NativeMethods.STORAGE_MEDIA_TYPE.VXATape_1, + + /// Ecrix 8mm tape. + VxaTape2 = NativeMethods.STORAGE_MEDIA_TYPE.VXATape_2, + + /// STK 9840. + Stk9840 = NativeMethods.STORAGE_MEDIA_TYPE.STK_9840, + + /// LTO Ultrium (IBM, HP, Seagate). + LtoUltrium = NativeMethods.STORAGE_MEDIA_TYPE.LTO_Ultrium, + + /// LTO Accelis (IBM, HP, Seagate). + LtoAccelis = NativeMethods.STORAGE_MEDIA_TYPE.LTO_Accelis, + + /// DVD-RAM. + DvdRam = NativeMethods.STORAGE_MEDIA_TYPE.DVD_RAM, + + /// AIT tape (AIT2 or higher). + Ait8Mm = NativeMethods.STORAGE_MEDIA_TYPE.AIT_8mm, + + /// OnStream ADR1. + Adr1 = NativeMethods.STORAGE_MEDIA_TYPE.ADR_1, + + /// OnStream ADR2. + Adr2 = NativeMethods.STORAGE_MEDIA_TYPE.ADR_2, + + /// STK 9940. + Stk9940 = NativeMethods.STORAGE_MEDIA_TYPE.STK_9940, + + /// SAIT tape. + /// Windows Server 2003: This is not supported before Windows Server 2003 with SP1. + /// + Sait = NativeMethods.STORAGE_MEDIA_TYPE.SAIT, + + /// Exabyte VXA tape. + /// Windows Server 2008: This is not supported before Windows Server 2008. + /// + VxaTape = NativeMethods.STORAGE_MEDIA_TYPE.VXATape + } +} diff --git a/AlphaFS/Safe Handles/SafeGlobalMemoryBufferHandle.cs b/AlphaFS/Safe Handles/SafeGlobalMemoryBufferHandle.cs index 806c273c1..a92285571 100644 --- a/AlphaFS/Safe Handles/SafeGlobalMemoryBufferHandle.cs +++ b/AlphaFS/Safe Handles/SafeGlobalMemoryBufferHandle.cs @@ -80,7 +80,12 @@ public static SafeGlobalMemoryBufferHandle FromStringUni(string str) /// protected override bool ReleaseHandle() { - Marshal.FreeHGlobal(handle); + if (handle != IntPtr.Zero) + { + Marshal.FreeHGlobal(handle); + handle = IntPtr.Zero; + } + return true; } } diff --git a/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs b/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs index 40534810a..590f3d012 100644 --- a/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs +++ b/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs @@ -300,12 +300,20 @@ public void StructureToPtr(object structure, bool deleteOld) /// Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type. /// A managed object containing the data pointed to by the ptr parameter. - public T PtrToStructure(int offset) + public T PtrToStructure() { - return (T) Marshal.PtrToStructure(new IntPtr(handle.ToInt64() + offset), typeof (T)); + return PtrToStructure(0); } + /// Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type. + /// A managed object containing the data pointed to by the ptr parameter. + public T PtrToStructure(int offset) + { + return (T) Marshal.PtrToStructure(new IntPtr(handle.ToInt64() + offset), typeof(T)); + } + + /// Allocates a managed System.String and copies a specified number of characters from an unmanaged ANSI string into it. /// A managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null. public string PtrToStringAnsi(int offset) diff --git a/AlphaFS/Utils.cs b/AlphaFS/Utils.cs index 7678d09fd..6f273a6af 100644 --- a/AlphaFS/Utils.cs +++ b/AlphaFS/Utils.cs @@ -20,9 +20,11 @@ */ using System; +using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using System.Linq; namespace Alphaleonis { @@ -44,6 +46,24 @@ public static string GetEnumDescription(Enum enumValue) } + public static T[] EnumToArray() + { + 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().ToArray(); + var enumValList = new List(enumValArray.Length); + + enumValList.AddRange(enumValArray.Select(val => (T) Enum.Parse(enumType, val.ToString()))); + + return enumValList.ToArray(); + } + + /// Checks that the object is not null. public static bool IsNotNull(T obj) { diff --git a/PowerShell/Enumerate-FileSystemEntryInfos.ps1 b/PowerShell/Enumerate-FileSystemEntryInfos.ps1 index d0d26d97b..acaa18e59 100644 --- a/PowerShell/Enumerate-FileSystemEntryInfos.ps1 +++ b/PowerShell/Enumerate-FileSystemEntryInfos.ps1 @@ -232,8 +232,7 @@ Function Enumerate-FileSystemEntryInfos { .NOTES - Backup privileges are enables when run elevated. - This allows for browsing folders which are normally inaccessible. + Backup privileges are enabled when run elevated. This allows for browsing folders which are normally inaccessible. .OUTPUTS From 4579a55b2f22d8b2c8bb7a1b525676a907fde89c Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 27 Feb 2018 18:14:33 +0100 Subject: [PATCH 057/133] Work in progress. --- .../AlphaFS_DeviceTest.cs | 2 +- AlphaFS/AlphaFS.csproj | 9 +- AlphaFS/Device/Device.EnumerateDevices.cs | 2 +- AlphaFS/Device/Device.GetDeviceIoData.cs | 14 +- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 50 - AlphaFS/Device/Device.InvokeDeviceIoData.cs | 15 +- AlphaFS/Device/Device.OpenPhysicalDrive.cs | 20 +- .../Device.GetPhysicalDriveInfo.cs | 12 +- .../Device.GetStorageAdapterInfo.cs | 19 +- .../Device.GetStorageDeviceInfo.cs | 12 +- .../Device.GetStoragePartitionInfo.cs | 254 +- .../PhysicalDriveInfo/PhysicalDriveInfo.cs | 9 +- AlphaFS/Device/StorageDeviceInfo.cs | 4 +- AlphaFS/Device/StorageGptPartitionInfo.cs | 13 +- AlphaFS/Device/StorageMbrPartitionInfo.cs | 21 +- AlphaFS/Device/StoragePartitionInfo.cs | 10 +- AlphaFS/Device/Test.cs | 2562 ++++++++--------- AlphaFS/Device/Test2.cs | 442 +-- .../Native Methods/NativeMethods.Constants.cs | 4 + .../Native Other/COPY_FILE_FLAGS.cs | 35 +- .../Native Other/DISK_DETECTION_INFO.cs | 2 - .../Native Other/DiskPartitionType.cs | 60 + ...ttributes.cs => EfiPartitionAttributes.cs} | 3 +- .../Native Other/PARTITION_INFORMATION_GPT.cs | 2 +- .../Native Other/PARTITION_INFORMATION_MBR.cs | 4 +- .../Structures, Enumerations/DetectionType.cs | 2 +- .../Structures, Enumerations/DeviceGuid.cs | 2 + .../DirectoryEnumerationFilters.cs | 2 +- ...PartitionTypes.cs => DiskPartitionType.cs} | 31 +- ...ttributes.cs => EfiPartitionAttributes.cs} | 16 +- .../PartitionStyle.cs | 4 + .../PartitionType..cs | 47 +- .../StorageBusType.cs | 15 + .../StorageMediaType.cs | 125 + AlphaFS/GlobalSuppressions.cs | 2 + AlphaFS/Network/NetworkInfo.cs | 1 - .../NativeMethods.GetTokenInformation.cs | 4 +- .../NativeMethods.OpenProcessToken.cs | 4 +- AlphaFS/Utils.cs | 1 + 39 files changed, 2099 insertions(+), 1737 deletions(-) create mode 100644 AlphaFS/Filesystem/Native Other/DiskPartitionType.cs rename AlphaFS/Filesystem/Native Other/{PartitionAttributes.cs => EfiPartitionAttributes.cs} (94%) rename AlphaFS/Filesystem/Structures, Enumerations/{DiskPartitionTypes.cs => DiskPartitionType.cs} (67%) rename AlphaFS/Filesystem/Structures, Enumerations/{PartitionAttributes.cs => EfiPartitionAttributes.cs} (76%) diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs index 64d15f315..2eab23efe 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs @@ -31,7 +31,7 @@ public void Device_Test() { //var hw = new Hardware(); - IOCtl.Main(); + //IOCtl.Main(); } } } diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 7e84f24d8..176a6fab9 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -325,14 +325,15 @@ + - + - + @@ -341,7 +342,7 @@ - + @@ -710,7 +711,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Device.EnumerateDevices.cs index 483e132e8..d2d6c05e4 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -193,7 +193,7 @@ private static string GetDeviceBusReportedDeviceDescription(SafeHandle safeHandl var success = NativeMethods.SetupDiGetDeviceProperty(safeHandle, ref infoData, ref NativeMethods.DEVPROPKEYS.DeviceBusReportedDeviceDesc, ref propertyType, descriptionBuffer, descriptionBuffer.Length, ref requiredSize, 0); - var lastError = Marshal.GetLastWin32Error(); + Marshal.GetLastWin32Error(); if (success) { diff --git a/AlphaFS/Device/Device.GetDeviceIoData.cs b/AlphaFS/Device/Device.GetDeviceIoData.cs index f75be46c4..ec1c9cf75 100644 --- a/AlphaFS/Device/Device.GetDeviceIoData.cs +++ b/AlphaFS/Device/Device.GetDeviceIoData.cs @@ -51,14 +51,18 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa return safeBuffer; - // Dynamic disk. - if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_NOT_READY || + using (safeBuffer) + { + if (lastError == Win32Errors.ERROR_NOT_READY || - // Request device number from a DeviceGuid.Image device. - lastError == Win32Errors.ERROR_NOT_SUPPORTED) + // Dynamic disk. + lastError == Win32Errors.ERROR_INVALID_FUNCTION || - return null; + // Request device number from a DeviceGuid.Image device. + lastError == Win32Errors.ERROR_NOT_SUPPORTED) + return null; + } bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); } diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index 8895b2a13..5e93b4d81 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -87,55 +87,5 @@ public static partial class Device return structure; } - - - //[SecurityCritical] - //internal static object GetDriveStuff(string logicalDrive) - //{ - // using (var safeHandle = OpenPhysicalDrive(logicalDrive, FileSystemRights.Read | FileSystemRights.Write)) - // { - // // DRIVE_LAYOUT_INFORMATION_EX - - // using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, logicalDrive)) - // { - // if (null != safeBuffer) - // { - // var structure = safeBuffer.PtrToStructure(0); - - // return structure; - // } - // } - - // return null; - - - // // DISK_GEOMETRY_EX - - // using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, logicalDrive)) - // { - // if (null != safeBuffer) - // { - // var structure = safeBuffer.PtrToStructure(0); - - // //return structure; - // } - // } - - - // // PARTITION_INFORMATION_EX - - // using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_PARTITION_INFO_EX, logicalDrive)) - // { - // if (null != safeBuffer) - // { - // var structure = safeBuffer.PtrToStructure(0); - - // //return structure; - // } - // } - // } - - // return null; - //} } } diff --git a/AlphaFS/Device/Device.InvokeDeviceIoData.cs b/AlphaFS/Device/Device.InvokeDeviceIoData.cs index 99f5e8ac5..83f2c821b 100644 --- a/AlphaFS/Device/Device.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Device.InvokeDeviceIoData.cs @@ -46,15 +46,24 @@ private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle var success = NativeMethods.DeviceIoControlAnyObjectGetSet(safeHandle, controlCode, anyObject, (uint) bufferSize, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); - + if (success) return safeBuffer; - if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_NOT_READY || lastError == Win32Errors.ERROR_INVALID_PARAMETER) - return null; + using (safeBuffer) + { + if (lastError == Win32Errors.ERROR_NOT_READY || + + // Dynamic disk. + lastError == Win32Errors.ERROR_INVALID_FUNCTION || + + // Request device number from a DeviceGuid.Image device. + lastError == Win32Errors.ERROR_NOT_SUPPORTED) + return null; + } bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); } diff --git a/AlphaFS/Device/Device.OpenPhysicalDrive.cs b/AlphaFS/Device/Device.OpenPhysicalDrive.cs index d1bad5baf..786eaffaf 100644 --- a/AlphaFS/Device/Device.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/Device.OpenPhysicalDrive.cs @@ -29,23 +29,33 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// Opens a physical device, such as: "\\.\PhysicalDrive0" or "\\.\C:" for access. + /// Opens a physical disk, volume/logical drive for read access. /// A instance. /// /// /// /// - /// The path to the physical device, such as: "\\.\PhysicalDrive0". + /// + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// /// If no elevated access is needed to access the physical device, specify 0 for this parameter. [SecurityCritical] - public static SafeFileHandle OpenPhysicalDrive(string path, FileSystemRights fileSystemRights) + public static SafeFileHandle OpenPhysicalDrive(string devicePath, FileSystemRights fileSystemRights) { - // fileSystemRights: If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes + // fileSystemRights: If this parameter is 0 (FILE_ANY_ACCESS), the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + // + // + // When opening a volume or removable media drive (for example, a floppy disk drive or flash memory thumb drive), the lpFileName string should be the following form: "\\.\X:". + // Do not use a trailing backslash (\), which indicates the root directory of a drive. + // + // When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITE flag. - return File.CreateFileCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Open, fileSystemRights, FileShare.ReadWrite, false, false, PathFormat.LongFullPath); + return File.CreateFileCore(null, devicePath, ExtendedFileAttributes.Normal | ExtendedFileAttributes.NoBuffering, null, FileMode.Open, fileSystemRights, FileShare.ReadWrite, false, false, PathFormat.LongFullPath); } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index 07b05e8ac..d3da090fb 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -39,9 +39,9 @@ public static partial class Device /// /// /// - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string (when is set to ). + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string such as: "\\?\pcistor#disk&...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// [SecurityCritical] public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) @@ -97,9 +97,9 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// /// indicates the current process is in an elevated state, allowing to retrieve more data. /// - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string (when is set to ). + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string such as: "\\?\pcistor#disk&...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// /// A instance. /// A instance. diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs index 09708f223..e71ceeb25 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs @@ -20,6 +20,7 @@ */ using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; @@ -37,9 +38,9 @@ public static partial class Device /// /// /// - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string (when is set to ). + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string such as: "\\?\pcistor#disk&...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) { @@ -78,6 +79,7 @@ internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath) } + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle safeHandle, string pathToDevice) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY @@ -94,7 +96,7 @@ private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle saf // Get storage adapter info. - using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, NativeMethods.DefaultFileBufferSize / 4)) + using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, NativeMethods.DefaultFileBufferSize / 8)) { if (null == safeBuffer) { @@ -123,13 +125,10 @@ private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle saf } - using (safeBuffer) - { - if (isRetry && !safeHandleRetry.IsClosed) - safeHandleRetry.Close(); + if (isRetry && !safeHandleRetry.IsClosed) + safeHandleRetry.Close(); - return new StorageAdapterInfo(safeBuffer.PtrToStructure(0)); - } + return new StorageAdapterInfo(safeBuffer.PtrToStructure(0)); } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs index 4401f8a6f..83521bec3 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs @@ -20,6 +20,7 @@ */ using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; @@ -37,9 +38,9 @@ public static partial class Device /// /// /// - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string (when is set to ). + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string such as: "\\?\pcistor#disk&...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { @@ -78,7 +79,9 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri StartGetData: - using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) + // Get storage device info. + + using (var safeHandle = OpenPhysicalDrive(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) { var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); @@ -118,6 +121,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri /// Sets the physical drive properties such as FriendlyName, device size and serial number. + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeHandle, string pathToDevice, StorageDeviceInfo storageDeviceInfo) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs index a48dd2b5e..ce5f45973 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs @@ -19,7 +19,7 @@ * THE SOFTWARE. */ -using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security.AccessControl; @@ -48,111 +48,245 @@ internal static StoragePartitionInfo GetStoragePartitionInfoCore(string devicePa return null; - using (var safeHandle = OpenPhysicalDrive(pathToDevice, 0)) + using (var safeHandle = OpenPhysicalDrive(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) return GetStoragePartitionInfoNative(safeHandle, devicePath); } + - - private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandle, string pathForException) + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] + private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandle, string pathToDevice) { - var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 - var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 - var partitionCount = 1; - - var bufferSize = driveStructureSize + partitionCount * partitionStructureSize; - - while (true) - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) + SafeFileHandle safeHandleRetry = null; + var isRetry = false; + + + StartGetData: + + // Get storage partition info. + + using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, pathToDevice, NativeMethods.DefaultFileBufferSize / 8)) + { + if (null == safeBuffer) { - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - var lastError = Marshal.GetLastWin32Error(); + var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); - if (success) + if (volDiskExtents.HasValue) { - var drive = safeBuffer.PtrToStructure(0); + // Use the first disk extent. - var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; + pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - for (partitionCount = 0; partitionCount <= drive.PartitionCount - 1; partitionCount++) + safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); - partitions[partitionCount] = safeBuffer.PtrToStructure(driveStructureSize + partitionCount * partitionStructureSize); + isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; + } - var disk = GetDiskGeometryExNative(safeHandle, pathForException); + if (isRetry) + goto StartGetData; - return new StoragePartitionInfo(disk, drive, partitions); - } + return null; + } - //// Dynamic disk. - //if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_NOT_READY || + if (isRetry && !safeHandleRetry.IsClosed) + safeHandleRetry.Close(); - // // Request device number from a DeviceGuid.Image device. - // lastError == Win32Errors.ERROR_NOT_SUPPORTED) - // return null; + var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 + var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 + var drive = safeBuffer.PtrToStructure(0); - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); - } - } + var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; - /// Gets the disk geometry extended information - private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeHandle, string pathForException) + for (var partitionCount = 0; partitionCount <= drive.PartitionCount - 1; partitionCount++) + + partitions[partitionCount] = safeBuffer.PtrToStructure(driveStructureSize + partitionCount * partitionStructureSize); + + + var disk = GetDiskGeometryExNative(safeHandle, pathToDevice); + + return new StoragePartitionInfo(disk, drive, partitions); + } + } + + + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] + private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeHandle, string pathToDevice) { - var bufferSize = 128; + SafeFileHandle safeHandleRetry = null; + var isRetry = false; + - while (true) - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) + StartGetData: + + using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, 0, pathToDevice, NativeMethods.DefaultFileBufferSize / 8)) + { + if (null == safeBuffer) { - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - var lastError = Marshal.GetLastWin32Error(); + var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); - if (success) + if (volDiskExtents.HasValue) { - var typeOf = typeof(NativeMethods.DISK_GEOMETRY); - var sizeOf = Marshal.SizeOf(typeOf); + // Use the first disk extent. - var diskGeometryEx = new NativeMethods.DISK_GEOMETRY_EX - { - Geometry = safeBuffer.PtrToStructure(), + pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - DiskSize = safeBuffer.ReadInt64(sizeOf) - }; + safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); - var offset = sizeOf + sizeof(long); // 32 + isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; + } - diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure(offset); + if (isRetry) + goto StartGetData; - offset += (int) diskGeometryEx.PartitionInformation.SizeOfPartitionInfo; - - diskGeometryEx.DiskDetectionInfo = safeBuffer.PtrToStructure(offset); + //return null; + return new NativeMethods.DISK_GEOMETRY_EX(); + } - return diskGeometryEx; - } + var typeOf = typeof(NativeMethods.DISK_GEOMETRY); + var sizeOf = Marshal.SizeOf(typeOf); - - //// Dynamic disk. - //if (lastError == Win32Errors.ERROR_INVALID_FUNCTION || lastError == Win32Errors.ERROR_NOT_READY || + var diskGeometryEx = new NativeMethods.DISK_GEOMETRY_EX + { + Geometry = safeBuffer.PtrToStructure(), - // // Request device number from a DeviceGuid.Image device. - // lastError == Win32Errors.ERROR_NOT_SUPPORTED) + DiskSize = safeBuffer.ReadInt64(sizeOf) + }; - // return null; + var offset = sizeOf + sizeof(long); // 32 - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); - } + diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure(offset); + + + offset += (int)diskGeometryEx.PartitionInformation.SizeOfPartitionInfo; + + diskGeometryEx.DiskDetectionInfo = safeBuffer.PtrToStructure(offset); + + + return diskGeometryEx; + } } + + + + //private static StoragePartitionInfo GetStoragePartitionInfoNative0(SafeFileHandle safeHandle, string pathForException) + //{ + // var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 + // var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 + // var partitionCount = 1; + + // var bufferSize = driveStructureSize + partitionCount * partitionStructureSize; + + // while (true) + // using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) + // { + // var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + + // var lastError = Marshal.GetLastWin32Error(); + + + // if (success) + // { + // var drive = safeBuffer.PtrToStructure(0); + + // var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; + + + // for (partitionCount = 0; partitionCount <= drive.PartitionCount - 1; partitionCount++) + + // partitions[partitionCount] = safeBuffer.PtrToStructure(driveStructureSize + partitionCount * partitionStructureSize); + + + // var disk = GetDiskGeometryExNative(safeHandle, pathForException); + + // return new StoragePartitionInfo(disk, drive, partitions); + // } + + + // if (lastError == Win32Errors.ERROR_NOT_READY || + + // // Dynamic disk. + // lastError == Win32Errors.ERROR_INVALID_FUNCTION || + + // // Request device number from a DeviceGuid.Image device. + // lastError == Win32Errors.ERROR_NOT_SUPPORTED) + + // return null; + + + // bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + // } + //} + + + ///// Gets the disk geometry extended information + //private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative0(SafeFileHandle safeHandle, string pathForException) + //{ + // var bufferSize = 128; + + // while (true) + // using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) + // { + // var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + + // var lastError = Marshal.GetLastWin32Error(); + + + // if (success) + // { + // var typeOf = typeof(NativeMethods.DISK_GEOMETRY); + // var sizeOf = Marshal.SizeOf(typeOf); + + // var diskGeometryEx = new NativeMethods.DISK_GEOMETRY_EX + // { + // Geometry = safeBuffer.PtrToStructure(), + + // DiskSize = safeBuffer.ReadInt64(sizeOf) + // }; + + + // var offset = sizeOf + sizeof(long); // 32 + + // diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure(offset); + + + // offset += (int) diskGeometryEx.PartitionInformation.SizeOfPartitionInfo; + + // diskGeometryEx.DiskDetectionInfo = safeBuffer.PtrToStructure(offset); + + + // return diskGeometryEx; + // } + + + // if (lastError == Win32Errors.ERROR_NOT_READY || + + // // Dynamic disk. + // lastError == Win32Errors.ERROR_INVALID_FUNCTION || + + // // Request device number from a DeviceGuid.Image device. + // lastError == Win32Errors.ERROR_NOT_SUPPORTED) + + // return new NativeMethods.DISK_GEOMETRY_EX(); + + + // bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + // } + //} } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs index 2108a3c28..ea97177e3 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs @@ -103,11 +103,10 @@ public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) #region Methods - /// Checks if the logical drive or volume is located on the physical drive. - /// - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// + /// Checks if the logical drive or volume is located on the physical drive. + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// public bool ContainsVolume(string devicePath) { bool isDrive; diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs index b8863c4ed..10dae1dbd 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -118,9 +118,7 @@ public string TotalSizeUnitSize /// A string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "{0} {1}:{2} {3}", - - DeviceType.ToString(), DeviceNumber.ToString(), PartitionNumber.ToString(), (VendorId + " " + ProductId + " " + ProductRevision).Trim()).Trim(); + return string.Format(CultureInfo.CurrentCulture, "{0} {1}:{2} {3}", DeviceType.ToString(), DeviceNumber.ToString(CultureInfo.InvariantCulture), PartitionNumber.ToString(CultureInfo.InvariantCulture), (VendorId + " " + ProductId + " " + ProductRevision).Trim()).Trim(); } diff --git a/AlphaFS/Device/StorageGptPartitionInfo.cs b/AlphaFS/Device/StorageGptPartitionInfo.cs index ef730bc33..1ddccca8e 100644 --- a/AlphaFS/Device/StorageGptPartitionInfo.cs +++ b/AlphaFS/Device/StorageGptPartitionInfo.cs @@ -20,16 +20,14 @@ */ using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { /// Provides access to GPT partition information of a storage device. - [Serializable] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt"), Serializable] [SecurityCritical] public sealed class StorageGptPartitionInfo { @@ -37,7 +35,6 @@ public sealed class StorageGptPartitionInfo private ulong _partitionLength; private ulong _startingOffset; - private ulong _startingUsableOffset; private static PartitionType[] _partitionTypes; #endregion // Private Fields @@ -71,7 +68,7 @@ internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio var gptPartition = partition.Gpt; - Attributes = (PartitionAttributes) gptPartition.Attributes; + Attributes = (EfiPartitionAttributes) gptPartition.Attributes; @@ -92,10 +89,10 @@ internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio #region Properties - + /// The Extensible Firmware Interface (EFI) attributes of the partition. - public PartitionAttributes Attributes { get; internal set; } + public EfiPartitionAttributes Attributes { get; internal set; } /// The description of the partition. diff --git a/AlphaFS/Device/StorageMbrPartitionInfo.cs b/AlphaFS/Device/StorageMbrPartitionInfo.cs index 803f6349d..a891d5194 100644 --- a/AlphaFS/Device/StorageMbrPartitionInfo.cs +++ b/AlphaFS/Device/StorageMbrPartitionInfo.cs @@ -20,13 +20,14 @@ */ using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; namespace Alphaleonis.Win32.Filesystem { /// Provides access to MBR partition information of a storage device. - [Serializable] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr"), Serializable] [SecurityCritical] public sealed class StorageMbrPartitionInfo { @@ -69,7 +70,7 @@ internal StorageMbrPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio RecognizedPartition = mbrPartition.RecognizedPartition; - PartitionType = mbrPartition.PartitionType; + DiskPartitionType = (DiskPartitionType) mbrPartition.PartitionType; } #endregion // Constructors @@ -81,6 +82,10 @@ internal StorageMbrPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio public bool BootIndicator { get; internal set; } + /// The type of the partition. + public DiskPartitionType DiskPartitionType { get; internal set; } + + /// The number of hidden sectors to be allocated when the partition table is created. public int HiddenSectors { get; internal set; } @@ -115,11 +120,7 @@ public string PartitionLengthUnitSize /// The storage partition number, starting at 1. public int PartitionNumber { get; internal set; } - - - /// The type of the partition. - public DiskPartitionTypes PartitionType { get; internal set; } - + /// if the partition is of a recognized type. public bool RecognizedPartition { get; internal set; } @@ -158,7 +159,7 @@ internal set /// A string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "BootIndicator {0}, Type: {1}, RecognizedPartition: {2}", BootIndicator.ToString(), PartitionType.ToString(), RecognizedPartition.ToString()).Trim(); + return string.Format(CultureInfo.CurrentCulture, "BootIndicator {0}, Type: {1}, RecognizedPartition: {2}", BootIndicator.ToString(), DiskPartitionType.ToString(), RecognizedPartition.ToString()).Trim(); } @@ -176,7 +177,7 @@ public override bool Equals(object obj) other.BootIndicator == BootIndicator && other.HiddenSectors == HiddenSectors && other.RecognizedPartition == RecognizedPartition && - other.PartitionType == PartitionType; + other.DiskPartitionType == DiskPartitionType; } @@ -186,7 +187,7 @@ public override int GetHashCode() { unchecked { - return BootIndicator.GetHashCode() + HiddenSectors.GetHashCode() + RecognizedPartition.GetHashCode() + PartitionType.GetHashCode(); + return BootIndicator.GetHashCode() + HiddenSectors.GetHashCode() + RecognizedPartition.GetHashCode() + DiskPartitionType.GetHashCode(); } } diff --git a/AlphaFS/Device/StoragePartitionInfo.cs b/AlphaFS/Device/StoragePartitionInfo.cs index 48d2ac377..ee30ed024 100644 --- a/AlphaFS/Device/StoragePartitionInfo.cs +++ b/AlphaFS/Device/StoragePartitionInfo.cs @@ -21,7 +21,7 @@ using System; using System.Collections.ObjectModel; -using System.Net.Mime; +using System.Diagnostics.CodeAnalysis; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -91,7 +91,7 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods // MSDN: PartitionCount: On hard disks with the MBR layout, this value will always be a multiple of 4. // Any partitions that are actually unused will have a partition type of PARTITION_ENTRY_UNUSED (0). - if (partition.Mbr.PartitionType == DiskPartitionTypes.UnusedEntry) + if (partition.Mbr.PartitionType == (NativeMethods.DiskPartitionType) DiskPartitionType.EntryUnused) continue; @@ -115,6 +115,7 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods #region Properties /// The GUID of the disk. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] public Guid GptDiskId { get; internal set; } @@ -123,14 +124,17 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods /// The maximum number of partitions that can be defined in the usable block. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] public int GptMaxPartitionCount { get; internal set; } /// Contains GUID partition table (GPT) partition information. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] public Collection GptPartitionInfo { get; internal set; } /// The starting byte offset of the first usable block. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] public long GptStartingUsableOffset { get @@ -180,10 +184,12 @@ internal set /// Contains partition information specific to master boot record (MBR) disks. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr")] public Collection MbrPartitionInfo { get; internal set; } /// The MBR signature of the drive. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr")] public long MbrSignature { get; internal set; } diff --git a/AlphaFS/Device/Test.cs b/AlphaFS/Device/Test.cs index dfcc97ab8..0d008c4da 100644 --- a/AlphaFS/Device/Test.cs +++ b/AlphaFS/Device/Test.cs @@ -1,1362 +1,1362 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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.IO; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Text; -using Microsoft.Win32; -using Microsoft.Win32.SafeHandles; - -namespace Alphaleonis.Win32.Filesystem -{ - #region Helper: Enum - - internal static class EnumHelper - { - internal static bool HasFlag(this Enum flags, T value) where T : struct - { - var iFlags = Convert.ToUInt64(flags); - var iValue = Convert.ToUInt64(value); - return ((iFlags & iValue) == iValue); - } - - internal static T SetFlag(this Enum flags, T value, bool state = true) - { - if (!Enum.IsDefined(typeof(T), value)) throw new ArgumentException("Enum value and flags types don't match."); - if (state) return (T) Enum.ToObject(typeof(T), Convert.ToUInt64(flags) | Convert.ToUInt64(value)); - return (T) Enum.ToObject(typeof(T), Convert.ToUInt64(flags) & ~Convert.ToUInt64(value)); - } - } - - #endregion - - #region Helper: Byte[] - - internal static class ByteHelper - { - internal static int IndexOf(this byte[] bytes, byte value, int startIndex = 0) - { - while (startIndex < bytes.Length) - if (bytes[startIndex++] == value) - return startIndex - 1; - return -1; - } - - internal static string GetString(this byte[] bytes, int offset) - { - string result = null; - var index = -1; - index = bytes.IndexOf(0, offset); - if (index >= 0) result = Encoding.ASCII.GetString(bytes, offset, index - offset); - return result; - } - - internal static T ToStruct(this byte[] bytes, int start = 0) where T : struct - { - var result = new T(); - var size = Marshal.SizeOf(result); - var ptr = Marshal.AllocHGlobal(size); - Marshal.Copy(bytes, start, ptr, size); - result = (T) Marshal.PtrToStructure(ptr, result.GetType()); - Marshal.FreeHGlobal(ptr); - return result; - } - } - - #endregion - - internal class Hardware - { - #region [extern] WindowsAPI - - [DllImport("USER32.DLL", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] - private static extern IntPtr CallWindowProcW([In] byte[] bytes, IntPtr hWnd, int msg, [In, Out] byte[] wParam, - IntPtr lParam); - - [DllImport("KERNEL32.DLL", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern bool VirtualProtect([In] byte[] bytes, IntPtr size, int newProtect, out int oldProtect); - - [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] - private static extern SafeFileHandle CreateFileW([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, - uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, - uint dwFlagsAndAttributes, IntPtr hTemplateFile); - - [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, - SetLastError = true)] - private static extern bool GetVolumeNameForVolumeMountPoint(string mountPoint, StringBuilder name, - uint bufferLength); - - [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] - private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, - STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_DEVICE_ID_DESCRIPTOR lpOutBuffer, - int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); - - [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] - private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, - STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_ADAPTER_DESCRIPTOR lpOutBuffer, - int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); - - [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] - private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, - STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_DEVICE_DESCRIPTOR lpOutBuffer, - int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); - - [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] - private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, - SENDCMDINPARAMS lpInBuffer, int lpInBufferSize, ref SENDCMDOUTPARAMS lpOutBuffer, int lpOutBufferSize, - ref uint lpBytesReturned, int lpOverlapped); - - [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] - private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, IntPtr lpInBuffer, - int lpInBufferSize, ref GETVERSIONOUTPARAMS lpOutBuffer, int lpOutBufferSize, ref uint lpBytesReturned, - int lpOverlapped); - - [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] - private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, IntPtr lpInBuffer, - int lpInBufferSize, ref VOLUMEDISKEXTENTS lpOutBuffer, int lpOutBufferSize, ref uint lpBytesReturned, - int lpOverlapped); - - [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall)] - private static extern int CloseHandle(int hObject); - - [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern int EnumSystemFirmwareTables(BiosFirmwareTableProvider providerSignature, - IntPtr firmwareTableBuffer, int bufferSize); - - [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] - private static extern int GetSystemFirmwareTable(BiosFirmwareTableProvider providerSignature, - int dwFirmwareTableID, IntPtr lpTableBuffer, int dwBufferSize); - - [DllImport("USER32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] - private static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, - uint dwFlags); - - #endregion - - private static byte[] _MD5; - private static byte[] _SHA1; - private static byte[] _SHA256; - private static byte[] _SHA512; - - private static string GenerateDate = DateTime.Now.ToString("yyyyMMddHH"); - - // HDD // - - #region [constants] HDD - - private const int VER_PLATFORM_WIN32_NT = 2; - private const int IDENTIFY_BUFFER_SIZE = 512; - private const int CREATE_NEW = 0x1; - private const int OPEN_EXISTING = 0x3; - private const uint GENERIC_READ = 0x80000000; - private const uint GENERIC_WRITE = 0x40000000; - private const int FILE_SHARE_READ = 0x00000001; - private const int FILE_SHARE_WRITE = 0x00000002; - private const uint IDE_ATAPI_IDENTIFY = 0xA1; - private const uint IDE_ATA_IDENTIFY = 0xEC; - private const uint CAP_SMART_CMD = 0x04; - private const uint METHOD_BUFFERED = 0; - private const uint FILE_ANY_ACCESS = 0; - private const uint FILE_ATTRIBUTE_NORMAL = 0x00000080; - private const uint FILE_DEVICE_CONTROLLER = 0x00000004; - private const uint IOCTL_SCSI_BASE = FILE_DEVICE_CONTROLLER; - private const uint FILE_DEVICE_MASS_STORAGE = 0x0000002d; - private const uint IOCTL_STORAGE_BASE = FILE_DEVICE_MASS_STORAGE; - private const uint IOCTL_VOLUME_BASE = 0x00000056; - private const uint IOCTL_SCSI_PASS_THROUGH = 0x0004d004; - private const uint IOCTL_DISK_GET_DRIVE_GEOMETRY = 0x00070000; - private const uint IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = 0x000700a0; - private const uint DFP_GET_VERSION = 0x00074080; - private const uint DFP_SEND_DRIVE_COMMAND = 0x0007c084; - private const uint DFP_RECEIVE_DRIVE_DATA = 0x0007c088; - private const uint IOCTL_STORAGE_GET_DEVICE_NUMBER = 0x002d1080; - private const uint IOCTL_STORAGE_QUERY_PROPERTY = 0x002d1400; - - private const uint IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = 0x00560000; - - // PropertyId For DeviceIoControl // - private const uint StorageDeviceProperty = 0; - private const uint StorageAdapterProperty = 1; - private const uint StorageDeviceIdProperty = 2; - - private const uint StorageDeviceSeekPenaltyProperty = 7; - - // Query Type For DeviceIoControl // - private const uint PropertyStandardQuery = 0; - private const uint PropertyExistsQuery = 1; - - #endregion - - #region [enum] STORAGE_BUS_TYPE - - internal enum STORAGE_BUS_TYPE : byte - { - BusTypeUnknown = 0x00, - BusTypeScsi = 0x01, - BusTypeAtapi = 0x02, - BusTypeAta = 0x03, - BusType1394 = 0x04, - BusTypeSsa = 0x05, - BusTypeFibre = 0x06, - BusTypeUsb = 0x07, - BusTypeRAID = 0x08, - BusTypeiScsi = 0x09, - BusTypeSas = 0x0A, - BusTypeSata = 0x0B, - BusTypeSd = 0x0C, - BusTypeMmc = 0x0D, - BusTypeVirtual = 0x0E, - BusTypeFileBackedVirtual = 0x0F, - BusTypeMax = 0x10, - BusTypeMaxReserved = 0x7F - } - - #endregion - - #region [struct] VOLUMEDISKEXTENTS - - [StructLayout(LayoutKind.Explicit)] - internal struct VOLUMEDISKEXTENTS - { - [FieldOffset(0)] internal uint numberOfDiskExtents; - [FieldOffset(8)] internal uint diskNumber; - [FieldOffset(16)] internal long startingOffset; - [FieldOffset(24)] internal long extentLength; - } - - #endregion - - #region [struct] STORAGE_PROPERTY_QUERY - - [StructLayout(LayoutKind.Sequential)] - private struct STORAGE_PROPERTY_QUERY - { - internal uint PropertyId; - internal uint QueryType; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] - internal byte[] AdditionalParameters; - } - - #endregion - - #region [struct] STORAGE_DEVICE_DESCRIPTOR - - [StructLayout(LayoutKind.Sequential)] - internal struct STORAGE_DEVICE_DESCRIPTOR - { - internal int Version; - internal int Size; - internal byte DeviceType; - internal byte DeviceTypeModifier; - internal byte RemovableMedia; - internal byte CommandQueueing; - internal int VendorIdOffset; - internal int ProductIdOffset; - internal int ProductRevisionOffset; - internal int SerialNumberOffset; - internal STORAGE_BUS_TYPE BusType; - internal int RawPropertiesLength; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10240)] - internal byte[] RawDeviceProperties; - } - - #endregion - - #region [struct] STORAGE_DEVICE_ID_DESCRIPTOR - - [StructLayout(LayoutKind.Sequential)] - internal struct STORAGE_DEVICE_ID_DESCRIPTOR - { - internal int Version; - internal int Size; - internal int NumberOfIdentifiers; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10240)] - internal byte[] Identifiers; - } - - #endregion - - #region [struct] STORAGE_ADAPTER_DESCRIPTOR - - [StructLayout(LayoutKind.Sequential)] - internal struct STORAGE_ADAPTER_DESCRIPTOR - { - internal uint Version; - internal uint Size; - internal uint MaximumTransferLength; - internal uint MaximumPhysicalPages; - internal uint AlignmentMask; - internal byte AdapterUsesPio; - internal byte AdapterScansDown; - internal byte CommandQueueing; - internal byte AcceleratedTransfer; - internal STORAGE_BUS_TYPE BusType; - internal ushort BusMajorVersion; - internal ushort BusMinorVersion; - internal byte SrbType; - internal byte AddressType; - } - - #endregion - - #region [struct] GETVERSIONOUTPARAMS - - [StructLayout(LayoutKind.Sequential)] - internal struct GETVERSIONOUTPARAMS - { - internal byte bVersion; - internal byte bRevision; - internal byte bReserved; - internal byte bIDEDeviceMap; - internal int fCapabilities; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] - internal int[] dwReserved; - } - - #endregion - - #region [struct] IDEREGS - - [StructLayout(LayoutKind.Sequential, Size = 8)] - internal struct IDEREGS - { - internal byte Features; - internal byte SectorCount; - internal byte SectorNumber; - internal byte CylinderLow; - internal byte CylinderHigh; - internal byte DriveHead; - internal byte Command; - internal byte Reserved; - } - - #endregion - - #region [struct] SENDCMDINPARAMS - - [StructLayout(LayoutKind.Sequential, Size = 32)] - internal struct SENDCMDINPARAMS - { - internal int BufferSize; - internal IDEREGS DriveRegs; - internal byte DriveNumber; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] - internal byte[] bReserved; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] - internal int[] dwReserved; - } - - #endregion - - #region [struct] DRIVERSTATUS - - [StructLayout(LayoutKind.Sequential, Size = 12)] - internal struct DRIVERSTATUS - { - internal byte DriveError; - internal byte IDEStatus; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] - internal byte[] bReserved; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] - internal int[] dwReserved; - } - - #endregion - - #region [struct] IDSECTOR - - [StructLayout(LayoutKind.Sequential)] - internal struct IDSECTOR - { - internal short GenConfig; - internal short NumberCylinders; - internal short Reserved; - internal short NumberHeads; - internal short BytesPerTrack; - internal short BytesPerSector; - internal short SectorsPerTrack; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] - internal short[] VendorUnique; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] - internal byte[] SerialNumber; - - internal short BufferClass; - internal short BufferSize; - internal short ECCSize; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - internal byte[] FirmwareRevision; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)] - internal byte[] ModelNumber; - - internal short MoreVendorUnique; - internal short DoubleWordIO; - internal short Capabilities; - internal short Reserved1; - internal short PIOTiming; - internal short DMATiming; - internal short BS; - internal short NumberCurrentCyls; - internal short NumberCurrentHeads; - internal short NumberCurrentSectorsPerTrack; - internal int CurrentSectorCapacity; - internal short MultipleSectorCapacity; - internal short MultipleSectorStuff; - internal int TotalAddressableSectors; - internal short SingleWordDMA; - internal short MultiWordDMA; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 382)] - internal byte[] bReserved; - } - - #endregion - - #region [struct] SENDCMDOUTPARAMS - - [StructLayout(LayoutKind.Sequential)] - internal struct SENDCMDOUTPARAMS - { - internal uint cBufferSize; - internal DRIVERSTATUS Status; - internal IDSECTOR IDS; - } - - #endregion - - [StructLayout(LayoutKind.Sequential)] - internal struct PhysicalDisk - { - internal byte Number; - internal string Model; - internal string Firmware; - internal string SerialNumber; - internal bool RemovableMedia; - internal VOLUMEDISKEXTENTS Extents; - internal STORAGE_DEVICE_DESCRIPTOR Device; - internal STORAGE_DEVICE_ID_DESCRIPTOR DeviceID; - internal STORAGE_ADAPTER_DESCRIPTOR Adapter; - internal GETVERSIONOUTPARAMS Version; - internal SENDCMDOUTPARAMS Params; - } - - #region CTL_CODE - - private uint CTL_CODE(uint DeviceType, uint Function, uint Method, uint Access) - { - return ((DeviceType << 16) | (Access << 14) | (Function << 2) | Method); - } - - #endregion - - #region [private] SwapChars - - private string SwapChars(char[] chars) - { - for (var i = 0; i <= chars.Length - 2; i += 2) - { - char T; - T = chars[i]; - chars[i] = chars[i + 1]; - chars[i + 1] = T; - } - - return new string(chars); - } - - #endregion - - #region [private] SwapBytes - - private string SwapBytes(byte[] bytes) - { - for (var i = 0; i <= bytes.Length - 2; i += 2) - { - byte T; - T = bytes[i]; - bytes[i] = bytes[i + 1]; - bytes[i + 1] = T; - } - - return Encoding.ASCII.GetString(bytes); - } - - #endregion - - #region [private] SwapRawString - - private string SwapRawString(string hexString) - { - var Result = new StringBuilder(); - for (var i = 0; i < hexString.Length; i += 4) - { - Result.Append(Convert.ToChar(Convert.ToByte(hexString.Substring(i + 2, 2), 16))); - Result.Append(Convert.ToChar(Convert.ToByte(hexString.Substring(i + 0, 2), 16))); - } - - return Result.ToString().Trim('\0', ' '); - } - - #endregion - - #region [private] GetPhysicalDisk - - private PhysicalDisk GetPhysicalDisk(string path) - { - var drive = System.IO.Path.GetPathRoot(path).TrimEnd('\\'); +///* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +// * +// * Permission is hereby granted, free of charge, to any person obtaining a copy +// * of this software and associated documentation files (the "Software"), to deal +// * in the Software without restriction, including without limitation the rights +// * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// * copies of the Software, and to permit persons to whom the Software is +// * furnished to do so, subject to the following conditions: +// * +// * The above copyright notice and this permission notice shall be included in +// * all copies or substantial portions of the Software. +// * +// * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// * LIABILITY, WHETHER IN AN ACTION 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.IO; +//using System.Runtime.InteropServices; +//using System.Security.Cryptography; +//using System.Text; +//using Microsoft.Win32; +//using Microsoft.Win32.SafeHandles; + +//namespace Alphaleonis.Win32.Filesystem +//{ +// #region Helper: Enum + +// internal static class EnumHelper +// { +// internal static bool HasFlag(this Enum flags, T value) where T : struct +// { +// var iFlags = Convert.ToUInt64(flags); +// var iValue = Convert.ToUInt64(value); +// return ((iFlags & iValue) == iValue); +// } + +// internal static T SetFlag(this Enum flags, T value, bool state = true) +// { +// if (!Enum.IsDefined(typeof(T), value)) throw new ArgumentException("Enum value and flags types don't match."); +// if (state) return (T) Enum.ToObject(typeof(T), Convert.ToUInt64(flags) | Convert.ToUInt64(value)); +// return (T) Enum.ToObject(typeof(T), Convert.ToUInt64(flags) & ~Convert.ToUInt64(value)); +// } +// } + +// #endregion + +// #region Helper: Byte[] + +// internal static class ByteHelper +// { +// internal static int IndexOf(this byte[] bytes, byte value, int startIndex = 0) +// { +// while (startIndex < bytes.Length) +// if (bytes[startIndex++] == value) +// return startIndex - 1; +// return -1; +// } + +// internal static string GetString(this byte[] bytes, int offset) +// { +// string result = null; +// var index = -1; +// index = bytes.IndexOf(0, offset); +// if (index >= 0) result = Encoding.ASCII.GetString(bytes, offset, index - offset); +// return result; +// } + +// internal static T ToStruct(this byte[] bytes, int start = 0) where T : struct +// { +// var result = new T(); +// var size = Marshal.SizeOf(result); +// var ptr = Marshal.AllocHGlobal(size); +// Marshal.Copy(bytes, start, ptr, size); +// result = (T) Marshal.PtrToStructure(ptr, result.GetType()); +// Marshal.FreeHGlobal(ptr); +// return result; +// } +// } + +// #endregion + +// internal class Hardware +// { +// #region [extern] WindowsAPI + +// [DllImport("USER32.DLL", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] +// private static extern IntPtr CallWindowProcW([In] byte[] bytes, IntPtr hWnd, int msg, [In, Out] byte[] wParam, +// IntPtr lParam); + +// [DllImport("KERNEL32.DLL", CharSet = CharSet.Unicode, SetLastError = true)] +// private static extern bool VirtualProtect([In] byte[] bytes, IntPtr size, int newProtect, out int oldProtect); + +// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] +// private static extern SafeFileHandle CreateFileW([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, +// uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, +// uint dwFlagsAndAttributes, IntPtr hTemplateFile); + +// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, +// SetLastError = true)] +// private static extern bool GetVolumeNameForVolumeMountPoint(string mountPoint, StringBuilder name, +// uint bufferLength); + +// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] +// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, +// STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_DEVICE_ID_DESCRIPTOR lpOutBuffer, +// int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); + +// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] +// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, +// STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_ADAPTER_DESCRIPTOR lpOutBuffer, +// int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); + +// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] +// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, +// STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_DEVICE_DESCRIPTOR lpOutBuffer, +// int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); + +// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] +// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, +// SENDCMDINPARAMS lpInBuffer, int lpInBufferSize, ref SENDCMDOUTPARAMS lpOutBuffer, int lpOutBufferSize, +// ref uint lpBytesReturned, int lpOverlapped); + +// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] +// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, IntPtr lpInBuffer, +// int lpInBufferSize, ref GETVERSIONOUTPARAMS lpOutBuffer, int lpOutBufferSize, ref uint lpBytesReturned, +// int lpOverlapped); + +// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] +// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, IntPtr lpInBuffer, +// int lpInBufferSize, ref VOLUMEDISKEXTENTS lpOutBuffer, int lpOutBufferSize, ref uint lpBytesReturned, +// int lpOverlapped); + +// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall)] +// private static extern int CloseHandle(int hObject); + +// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] +// internal static extern int EnumSystemFirmwareTables(BiosFirmwareTableProvider providerSignature, +// IntPtr firmwareTableBuffer, int bufferSize); + +// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] +// private static extern int GetSystemFirmwareTable(BiosFirmwareTableProvider providerSignature, +// int dwFirmwareTableID, IntPtr lpTableBuffer, int dwBufferSize); + +// [DllImport("USER32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] +// private static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, +// uint dwFlags); + +// #endregion + +// private static byte[] _MD5; +// private static byte[] _SHA1; +// private static byte[] _SHA256; +// private static byte[] _SHA512; + +// private static string GenerateDate = DateTime.Now.ToString("yyyyMMddHH"); + +// // HDD // + +// #region [constants] HDD + +// private const int VER_PLATFORM_WIN32_NT = 2; +// private const int IDENTIFY_BUFFER_SIZE = 512; +// private const int CREATE_NEW = 0x1; +// private const int OPEN_EXISTING = 0x3; +// private const uint GENERIC_READ = 0x80000000; +// private const uint GENERIC_WRITE = 0x40000000; +// private const int FILE_SHARE_READ = 0x00000001; +// private const int FILE_SHARE_WRITE = 0x00000002; +// private const uint IDE_ATAPI_IDENTIFY = 0xA1; +// private const uint IDE_ATA_IDENTIFY = 0xEC; +// private const uint CAP_SMART_CMD = 0x04; +// private const uint METHOD_BUFFERED = 0; +// private const uint FILE_ANY_ACCESS = 0; +// private const uint FILE_ATTRIBUTE_NORMAL = 0x00000080; +// private const uint FILE_DEVICE_CONTROLLER = 0x00000004; +// private const uint IOCTL_SCSI_BASE = FILE_DEVICE_CONTROLLER; +// private const uint FILE_DEVICE_MASS_STORAGE = 0x0000002d; +// private const uint IOCTL_STORAGE_BASE = FILE_DEVICE_MASS_STORAGE; +// private const uint IOCTL_VOLUME_BASE = 0x00000056; +// private const uint IOCTL_SCSI_PASS_THROUGH = 0x0004d004; +// private const uint IOCTL_DISK_GET_DRIVE_GEOMETRY = 0x00070000; +// private const uint IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = 0x000700a0; +// private const uint DFP_GET_VERSION = 0x00074080; +// private const uint DFP_SEND_DRIVE_COMMAND = 0x0007c084; +// private const uint DFP_RECEIVE_DRIVE_DATA = 0x0007c088; +// private const uint IOCTL_STORAGE_GET_DEVICE_NUMBER = 0x002d1080; +// private const uint IOCTL_STORAGE_QUERY_PROPERTY = 0x002d1400; + +// private const uint IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = 0x00560000; + +// // PropertyId For DeviceIoControl // +// private const uint StorageDeviceProperty = 0; +// private const uint StorageAdapterProperty = 1; +// private const uint StorageDeviceIdProperty = 2; + +// private const uint StorageDeviceSeekPenaltyProperty = 7; + +// // Query Type For DeviceIoControl // +// private const uint PropertyStandardQuery = 0; +// private const uint PropertyExistsQuery = 1; + +// #endregion + +// #region [enum] STORAGE_BUS_TYPE + +// internal enum STORAGE_BUS_TYPE : byte +// { +// BusTypeUnknown = 0x00, +// BusTypeScsi = 0x01, +// BusTypeAtapi = 0x02, +// BusTypeAta = 0x03, +// BusType1394 = 0x04, +// BusTypeSsa = 0x05, +// BusTypeFibre = 0x06, +// BusTypeUsb = 0x07, +// BusTypeRAID = 0x08, +// BusTypeiScsi = 0x09, +// BusTypeSas = 0x0A, +// BusTypeSata = 0x0B, +// BusTypeSd = 0x0C, +// BusTypeMmc = 0x0D, +// BusTypeVirtual = 0x0E, +// BusTypeFileBackedVirtual = 0x0F, +// BusTypeMax = 0x10, +// BusTypeMaxReserved = 0x7F +// } + +// #endregion + +// #region [struct] VOLUMEDISKEXTENTS + +// [StructLayout(LayoutKind.Explicit)] +// internal struct VOLUMEDISKEXTENTS +// { +// [FieldOffset(0)] internal uint numberOfDiskExtents; +// [FieldOffset(8)] internal uint diskNumber; +// [FieldOffset(16)] internal long startingOffset; +// [FieldOffset(24)] internal long extentLength; +// } + +// #endregion + +// #region [struct] STORAGE_PROPERTY_QUERY + +// [StructLayout(LayoutKind.Sequential)] +// private struct STORAGE_PROPERTY_QUERY +// { +// internal uint PropertyId; +// internal uint QueryType; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] +// internal byte[] AdditionalParameters; +// } + +// #endregion + +// #region [struct] STORAGE_DEVICE_DESCRIPTOR + +// [StructLayout(LayoutKind.Sequential)] +// internal struct STORAGE_DEVICE_DESCRIPTOR +// { +// internal int Version; +// internal int Size; +// internal byte DeviceType; +// internal byte DeviceTypeModifier; +// internal byte RemovableMedia; +// internal byte CommandQueueing; +// internal int VendorIdOffset; +// internal int ProductIdOffset; +// internal int ProductRevisionOffset; +// internal int SerialNumberOffset; +// internal STORAGE_BUS_TYPE BusType; +// internal int RawPropertiesLength; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10240)] +// internal byte[] RawDeviceProperties; +// } + +// #endregion + +// #region [struct] STORAGE_DEVICE_ID_DESCRIPTOR + +// [StructLayout(LayoutKind.Sequential)] +// internal struct STORAGE_DEVICE_ID_DESCRIPTOR +// { +// internal int Version; +// internal int Size; +// internal int NumberOfIdentifiers; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10240)] +// internal byte[] Identifiers; +// } + +// #endregion + +// #region [struct] STORAGE_ADAPTER_DESCRIPTOR + +// [StructLayout(LayoutKind.Sequential)] +// internal struct STORAGE_ADAPTER_DESCRIPTOR +// { +// internal uint Version; +// internal uint Size; +// internal uint MaximumTransferLength; +// internal uint MaximumPhysicalPages; +// internal uint AlignmentMask; +// internal byte AdapterUsesPio; +// internal byte AdapterScansDown; +// internal byte CommandQueueing; +// internal byte AcceleratedTransfer; +// internal STORAGE_BUS_TYPE BusType; +// internal ushort BusMajorVersion; +// internal ushort BusMinorVersion; +// internal byte SrbType; +// internal byte AddressType; +// } + +// #endregion + +// #region [struct] GETVERSIONOUTPARAMS + +// [StructLayout(LayoutKind.Sequential)] +// internal struct GETVERSIONOUTPARAMS +// { +// internal byte bVersion; +// internal byte bRevision; +// internal byte bReserved; +// internal byte bIDEDeviceMap; +// internal int fCapabilities; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] +// internal int[] dwReserved; +// } + +// #endregion + +// #region [struct] IDEREGS + +// [StructLayout(LayoutKind.Sequential, Size = 8)] +// internal struct IDEREGS +// { +// internal byte Features; +// internal byte SectorCount; +// internal byte SectorNumber; +// internal byte CylinderLow; +// internal byte CylinderHigh; +// internal byte DriveHead; +// internal byte Command; +// internal byte Reserved; +// } + +// #endregion + +// #region [struct] SENDCMDINPARAMS + +// [StructLayout(LayoutKind.Sequential, Size = 32)] +// internal struct SENDCMDINPARAMS +// { +// internal int BufferSize; +// internal IDEREGS DriveRegs; +// internal byte DriveNumber; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] +// internal byte[] bReserved; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] +// internal int[] dwReserved; +// } + +// #endregion + +// #region [struct] DRIVERSTATUS + +// [StructLayout(LayoutKind.Sequential, Size = 12)] +// internal struct DRIVERSTATUS +// { +// internal byte DriveError; +// internal byte IDEStatus; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] +// internal byte[] bReserved; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] +// internal int[] dwReserved; +// } + +// #endregion + +// #region [struct] IDSECTOR + +// [StructLayout(LayoutKind.Sequential)] +// internal struct IDSECTOR +// { +// internal short GenConfig; +// internal short NumberCylinders; +// internal short Reserved; +// internal short NumberHeads; +// internal short BytesPerTrack; +// internal short BytesPerSector; +// internal short SectorsPerTrack; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] +// internal short[] VendorUnique; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] +// internal byte[] SerialNumber; + +// internal short BufferClass; +// internal short BufferSize; +// internal short ECCSize; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] +// internal byte[] FirmwareRevision; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)] +// internal byte[] ModelNumber; + +// internal short MoreVendorUnique; +// internal short DoubleWordIO; +// internal short Capabilities; +// internal short Reserved1; +// internal short PIOTiming; +// internal short DMATiming; +// internal short BS; +// internal short NumberCurrentCyls; +// internal short NumberCurrentHeads; +// internal short NumberCurrentSectorsPerTrack; +// internal int CurrentSectorCapacity; +// internal short MultipleSectorCapacity; +// internal short MultipleSectorStuff; +// internal int TotalAddressableSectors; +// internal short SingleWordDMA; +// internal short MultiWordDMA; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 382)] +// internal byte[] bReserved; +// } + +// #endregion + +// #region [struct] SENDCMDOUTPARAMS + +// [StructLayout(LayoutKind.Sequential)] +// internal struct SENDCMDOUTPARAMS +// { +// internal uint cBufferSize; +// internal DRIVERSTATUS Status; +// internal IDSECTOR IDS; +// } + +// #endregion + +// [StructLayout(LayoutKind.Sequential)] +// internal struct PhysicalDisk +// { +// internal byte Number; +// internal string Model; +// internal string Firmware; +// internal string SerialNumber; +// internal bool RemovableMedia; +// internal VOLUMEDISKEXTENTS Extents; +// internal STORAGE_DEVICE_DESCRIPTOR Device; +// internal STORAGE_DEVICE_ID_DESCRIPTOR DeviceID; +// internal STORAGE_ADAPTER_DESCRIPTOR Adapter; +// internal GETVERSIONOUTPARAMS Version; +// internal SENDCMDOUTPARAMS Params; +// } + +// #region CTL_CODE + +// private uint CTL_CODE(uint DeviceType, uint Function, uint Method, uint Access) +// { +// return ((DeviceType << 16) | (Access << 14) | (Function << 2) | Method); +// } + +// #endregion + +// #region [private] SwapChars + +// private string SwapChars(char[] chars) +// { +// for (var i = 0; i <= chars.Length - 2; i += 2) +// { +// char T; +// T = chars[i]; +// chars[i] = chars[i + 1]; +// chars[i + 1] = T; +// } + +// return new string(chars); +// } + +// #endregion + +// #region [private] SwapBytes + +// private string SwapBytes(byte[] bytes) +// { +// for (var i = 0; i <= bytes.Length - 2; i += 2) +// { +// byte T; +// T = bytes[i]; +// bytes[i] = bytes[i + 1]; +// bytes[i + 1] = T; +// } + +// return Encoding.ASCII.GetString(bytes); +// } + +// #endregion + +// #region [private] SwapRawString + +// private string SwapRawString(string hexString) +// { +// var Result = new StringBuilder(); +// for (var i = 0; i < hexString.Length; i += 4) +// { +// Result.Append(Convert.ToChar(Convert.ToByte(hexString.Substring(i + 2, 2), 16))); +// Result.Append(Convert.ToChar(Convert.ToByte(hexString.Substring(i + 0, 2), 16))); +// } + +// return Result.ToString().Trim('\0', ' '); +// } + +// #endregion + +// #region [private] GetPhysicalDisk + +// private PhysicalDisk GetPhysicalDisk(string path) +// { +// var drive = System.IO.Path.GetPathRoot(path).TrimEnd('\\'); - using (var hDisk = CreateFileW(@"\\.\" + drive, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero)) - { - var Result = new PhysicalDisk(); - uint iBytesReturned = 0; - Result.SerialNumber = string.Empty; - Result.Firmware = string.Empty; - Result.Model = string.Empty; - - //var StoragePropertyQuery = new STORAGE_PROPERTY_QUERY(); - - Result.Extents = new VOLUMEDISKEXTENTS(); - Result.Adapter = new STORAGE_ADAPTER_DESCRIPTOR(); - Result.Device = new STORAGE_DEVICE_DESCRIPTOR(); - Result.DeviceID = new STORAGE_DEVICE_ID_DESCRIPTOR(); - Result.Version = new GETVERSIONOUTPARAMS(); - Result.Params = new SENDCMDOUTPARAMS(); - - var IOCMD = CTL_CODE(IOCTL_VOLUME_BASE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS); - if (DeviceIoControl(hDisk, IOCMD, IntPtr.Zero, 0, ref Result.Extents, Marshal.SizeOf(Result.Extents), ref iBytesReturned, 0)) - { - Console.ForegroundColor = ConsoleColor.DarkGray; - Console.WriteLine("Received: IOCTL_VOLUME_BASE"); - Result.Number = Convert.ToByte(Result.Extents.diskNumber); - } - - - - //StoragePropertyQuery.PropertyId = StorageAdapterProperty; - //StoragePropertyQuery.QueryType = PropertyStandardQuery; - - //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.Adapter, Marshal.SizeOf(Result.Adapter), ref iBytesReturned, 0)) - //{ - // Console.ForegroundColor = ConsoleColor.DarkGray; - // Console.WriteLine("Received: STORAGE_ADAPTER_DESCRIPTOR"); - // Console.WriteLine("> Version: "+Result.Adapter.Version+", Size: "+Result.Adapter.Size); - // Console.WriteLine("> MaximumPhysicalPages: "+Result.Adapter.MaximumPhysicalPages); - // Console.WriteLine("> MaximumTransferLength: "+Result.Adapter.MaximumTransferLength); - // Console.WriteLine("> CommandQueueing: "+Result.Adapter.CommandQueueing); - // Console.WriteLine("> BusMajorVersion: "+Result.Adapter.BusMajorVersion); - // Console.WriteLine("> BusMinorVersion: "+Result.Adapter.BusMinorVersion); - // Console.WriteLine("> BusType: "+Result.Adapter.BusType); - //} +// using (var hDisk = CreateFileW(@"\\.\" + drive, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero)) +// { +// var Result = new PhysicalDisk(); +// uint iBytesReturned = 0; +// Result.SerialNumber = string.Empty; +// Result.Firmware = string.Empty; +// Result.Model = string.Empty; + +// //var StoragePropertyQuery = new STORAGE_PROPERTY_QUERY(); + +// Result.Extents = new VOLUMEDISKEXTENTS(); +// Result.Adapter = new STORAGE_ADAPTER_DESCRIPTOR(); +// Result.Device = new STORAGE_DEVICE_DESCRIPTOR(); +// Result.DeviceID = new STORAGE_DEVICE_ID_DESCRIPTOR(); +// Result.Version = new GETVERSIONOUTPARAMS(); +// Result.Params = new SENDCMDOUTPARAMS(); + +// var IOCMD = CTL_CODE(IOCTL_VOLUME_BASE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS); +// if (DeviceIoControl(hDisk, IOCMD, IntPtr.Zero, 0, ref Result.Extents, Marshal.SizeOf(Result.Extents), ref iBytesReturned, 0)) +// { +// Console.ForegroundColor = ConsoleColor.DarkGray; +// Console.WriteLine("Received: IOCTL_VOLUME_BASE"); +// Result.Number = Convert.ToByte(Result.Extents.diskNumber); +// } + + + +// //StoragePropertyQuery.PropertyId = StorageAdapterProperty; +// //StoragePropertyQuery.QueryType = PropertyStandardQuery; + +// //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.Adapter, Marshal.SizeOf(Result.Adapter), ref iBytesReturned, 0)) +// //{ +// // Console.ForegroundColor = ConsoleColor.DarkGray; +// // Console.WriteLine("Received: STORAGE_ADAPTER_DESCRIPTOR"); +// // Console.WriteLine("> Version: "+Result.Adapter.Version+", Size: "+Result.Adapter.Size); +// // Console.WriteLine("> MaximumPhysicalPages: "+Result.Adapter.MaximumPhysicalPages); +// // Console.WriteLine("> MaximumTransferLength: "+Result.Adapter.MaximumTransferLength); +// // Console.WriteLine("> CommandQueueing: "+Result.Adapter.CommandQueueing); +// // Console.WriteLine("> BusMajorVersion: "+Result.Adapter.BusMajorVersion); +// // Console.WriteLine("> BusMinorVersion: "+Result.Adapter.BusMinorVersion); +// // Console.WriteLine("> BusType: "+Result.Adapter.BusType); +// //} - //StoragePropertyQuery.PropertyId = StorageDeviceIdProperty; - //StoragePropertyQuery.QueryType = PropertyStandardQuery; - //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.DeviceID, Marshal.SizeOf(Result.DeviceID), ref iBytesReturned, 0)) - //{ - // /File.WriteAllBytes("Hardware."+GenerateDate+".RAID-"+drive[0]+".bin", Result.DeviceID.Identifiers); - // Console.ForegroundColor = ConsoleColor.DarkGray; - // Console.WriteLine("Received: STORAGE_DEVICE_ID_DESCRIPTOR"); - // Console.WriteLine("> Version: "+Result.DeviceID.Version+", Size: "+Result.DeviceID.Size); - // Console.WriteLine("> NumberOfIdentifiers: "+Result.DeviceID.NumberOfIdentifiers); - //} +// //StoragePropertyQuery.PropertyId = StorageDeviceIdProperty; +// //StoragePropertyQuery.QueryType = PropertyStandardQuery; +// //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.DeviceID, Marshal.SizeOf(Result.DeviceID), ref iBytesReturned, 0)) +// //{ +// // /File.WriteAllBytes("Hardware."+GenerateDate+".RAID-"+drive[0]+".bin", Result.DeviceID.Identifiers); +// // Console.ForegroundColor = ConsoleColor.DarkGray; +// // Console.WriteLine("Received: STORAGE_DEVICE_ID_DESCRIPTOR"); +// // Console.WriteLine("> Version: "+Result.DeviceID.Version+", Size: "+Result.DeviceID.Size); +// // Console.WriteLine("> NumberOfIdentifiers: "+Result.DeviceID.NumberOfIdentifiers); +// //} - //StoragePropertyQuery.PropertyId = StorageDeviceProperty; - //StoragePropertyQuery.QueryType = PropertyStandardQuery; - //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.Device, Marshal.SizeOf(Result.Device), ref iBytesReturned, 0)) - //{ - // /File.WriteAllBytes("Hardware."+GenerateDate+".HDD-"+drive[0]+".bin", Result.Device.RawDeviceProperties); - // Console.ForegroundColor = ConsoleColor.DarkGray; - // Console.WriteLine("Received: STORAGE_DEVICE_DESCRIPTOR"); - // Console.WriteLine("> RemovableMedia: "+Convert.ToBoolean(Result.Device.RemovableMedia)); - // Console.WriteLine("> DeviceType: "+Result.Device.DeviceType); - // Console.WriteLine("> BusType: "+Result.Device.BusType); - - // var buffer = Encoding.ASCII.GetString(Result.Device.RawDeviceProperties); - // var basepos = Marshal.SizeOf(Result.Device) - Result.Device.RawDeviceProperties.Length; - - // if (Result.Device.ProductIdOffset > 0) - // Result.Model = buffer.Substring(Result.Device.ProductIdOffset - basepos, 20).Trim('\0', ' '); - // if (Result.Device.ProductRevisionOffset > 0) - // Result.Firmware = buffer.Substring(Result.Device.ProductRevisionOffset - basepos, 8).Trim('\0', ' '); - // if (Result.Device.SerialNumberOffset > 0) - // Result.SerialNumber = - // buffer.Substring(Result.Device.SerialNumberOffset - basepos, 40).Trim('\0', ' '); - // if (Result.SerialNumber != null && Result.SerialNumber.Length == 40) - // Result.SerialNumber = SwapRawString(Result.SerialNumber); - - // Result.RemovableMedia = Convert.ToBoolean(Result.Device.RemovableMedia); - //} - - DeviceIoControl(hDisk, DFP_GET_VERSION, IntPtr.Zero, 0, ref Result.Version, Marshal.SizeOf(Result.Version), ref iBytesReturned, 0); +// //StoragePropertyQuery.PropertyId = StorageDeviceProperty; +// //StoragePropertyQuery.QueryType = PropertyStandardQuery; +// //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.Device, Marshal.SizeOf(Result.Device), ref iBytesReturned, 0)) +// //{ +// // /File.WriteAllBytes("Hardware."+GenerateDate+".HDD-"+drive[0]+".bin", Result.Device.RawDeviceProperties); +// // Console.ForegroundColor = ConsoleColor.DarkGray; +// // Console.WriteLine("Received: STORAGE_DEVICE_DESCRIPTOR"); +// // Console.WriteLine("> RemovableMedia: "+Convert.ToBoolean(Result.Device.RemovableMedia)); +// // Console.WriteLine("> DeviceType: "+Result.Device.DeviceType); +// // Console.WriteLine("> BusType: "+Result.Device.BusType); + +// // var buffer = Encoding.ASCII.GetString(Result.Device.RawDeviceProperties); +// // var basepos = Marshal.SizeOf(Result.Device) - Result.Device.RawDeviceProperties.Length; + +// // if (Result.Device.ProductIdOffset > 0) +// // Result.Model = buffer.Substring(Result.Device.ProductIdOffset - basepos, 20).Trim('\0', ' '); +// // if (Result.Device.ProductRevisionOffset > 0) +// // Result.Firmware = buffer.Substring(Result.Device.ProductRevisionOffset - basepos, 8).Trim('\0', ' '); +// // if (Result.Device.SerialNumberOffset > 0) +// // Result.SerialNumber = +// // buffer.Substring(Result.Device.SerialNumberOffset - basepos, 40).Trim('\0', ' '); +// // if (Result.SerialNumber != null && Result.SerialNumber.Length == 40) +// // Result.SerialNumber = SwapRawString(Result.SerialNumber); + +// // Result.RemovableMedia = Convert.ToBoolean(Result.Device.RemovableMedia); +// //} + +// DeviceIoControl(hDisk, DFP_GET_VERSION, IntPtr.Zero, 0, ref Result.Version, Marshal.SizeOf(Result.Version), ref iBytesReturned, 0); - if ((Result.Version.fCapabilities & CAP_SMART_CMD) > 0) - { - Console.ForegroundColor = ConsoleColor.DarkGray; - Console.WriteLine("Received: GETVERSIONOUTPARAMS"); - Console.WriteLine("> Version: "+Result.Version.bVersion+"."+Result.Version.bRevision); - var SCI = new SENDCMDINPARAMS - { - DriveRegs = {Command = (int) IDE_ATA_IDENTIFY}, - DriveNumber = Result.Number, - BufferSize = IDENTIFY_BUFFER_SIZE - }; +// if ((Result.Version.fCapabilities & CAP_SMART_CMD) > 0) +// { +// Console.ForegroundColor = ConsoleColor.DarkGray; +// Console.WriteLine("Received: GETVERSIONOUTPARAMS"); +// Console.WriteLine("> Version: "+Result.Version.bVersion+"."+Result.Version.bRevision); +// var SCI = new SENDCMDINPARAMS +// { +// DriveRegs = {Command = (int) IDE_ATA_IDENTIFY}, +// DriveNumber = Result.Number, +// BufferSize = IDENTIFY_BUFFER_SIZE +// }; - if (DeviceIoControl(hDisk, DFP_RECEIVE_DRIVE_DATA, SCI, Marshal.SizeOf(SCI), ref Result.Params, Marshal.SizeOf(Result.Params), ref iBytesReturned, 0)) - { - Console.WriteLine("Received: SENDCMDOUTPARAMS"); - Console.WriteLine("> IDS.Capabilities: "+Result.Params.IDS.Capabilities); - Console.WriteLine("> IDS.BufferSize: "+Result.Params.IDS.BufferSize); - Console.WriteLine("> IDS.SectorsPerTrack: "+Result.Params.IDS.SectorsPerTrack); - Console.WriteLine("> IDS.NumberCylinders: "+Result.Params.IDS.NumberCylinders); - Console.WriteLine("> IDS.NumberHeads: "+Result.Params.IDS.NumberHeads); - - Result.Model = SwapBytes(Result.Params.IDS.ModelNumber).Trim(); - Result.Firmware = SwapBytes(Result.Params.IDS.FirmwareRevision).Trim(); - Result.SerialNumber = SwapBytes(Result.Params.IDS.SerialNumber).Trim(); - } - - } - - return Result; - } - - throw new Win32Exception(); - } - - #endregion - - // CPU // - - #region [enum] BiosFirmwareTableProvider - - internal enum BiosFirmwareTableProvider - { - ACPI = (byte) 'A' << 24 | (byte) 'C' << 16 | (byte) 'P' << 8 | (byte) 'I', - FIRM = (byte) 'F' << 24 | (byte) 'I' << 16 | (byte) 'R' << 8 | (byte) 'M', - RSMB = (byte) 'R' << 24 | (byte) 'S' << 16 | (byte) 'M' << 8 | (byte) 'B' - } - - #endregion - - #region [enum] SMBIOSTableType - - internal enum SMBIOSTableType : sbyte - { - BIOSInformation = 0, - SystemInformation = 1, - BaseBoardInformation = 2, - EnclosureInformation = 3, - ProcessorInformation = 4, - MemoryControllerInformation = 5, - MemoryModuleInformation = 6, - CacheInformation = 7, - PortConnectorInformation = 8, - SystemSlotsInformation = 9, - OnBoardDevicesInformation = 10, - OEMStrings = 11, - SystemConfigurationOptions = 12, - BIOSLanguageInformation = 13, - GroupAssociations = 14, - SystemEventLog = 15, - PhysicalMemoryArray = 16, - MemoryDevice = 17, - MemoryErrorInformation = 18, - MemoryArrayMappedAddress = 19, - MemoryDeviceMappedAddress = 20, - EndofTable = 127 - } - - #endregion - - #region [enum] SMBIOSTableEntry - - [StructLayout(LayoutKind.Sequential)] - internal struct SMBIOSTableHeader - { - internal SMBIOSTableType type; - internal byte length; - internal ushort Handle; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SMBIOSTableEntry - { - internal SMBIOSTableHeader header; - internal uint index; - } - - #endregion - - #region [enum] SMBIOSTableInfo - - [StructLayout(LayoutKind.Sequential)] - internal struct SMBIOSTableBiosInfo - { - internal SMBIOSTableHeader header; - internal byte vendor; - internal byte version; - internal ushort startingSegment; - internal byte releaseDate; - internal byte biosRomSize; - internal ulong characteristics; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] - internal byte[] extensionBytes; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SMBIOSTableSystemInfo - { - internal SMBIOSTableHeader header; - internal byte manufacturer; - internal byte productName; - internal byte version; - internal byte serialNumber; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - internal byte[] UUID; - - internal byte wakeUpType; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SMBIOSTableBaseBoardInfo - { - internal SMBIOSTableHeader header; - internal byte manufacturer; - internal byte productName; - internal byte version; - internal byte serialNumber; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SMBIOSTableEnclosureInfo - { - internal SMBIOSTableHeader header; - internal byte manufacturer; - internal byte type; - internal byte version; - internal byte serialNumber; - internal byte assetTagNumber; - internal byte bootUpState; - internal byte powerSupplyState; - internal byte thermalState; - internal byte securityStatus; - internal long OEM_Defined; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SMBIOSTableProcessorInfo - { - internal SMBIOSTableHeader header; - internal byte socketDesignation; - internal byte processorType; - internal byte processorFamily; - internal byte processorManufacturer; - internal ulong processorID; - internal byte processorVersion; - internal byte processorVoltage; - internal ushort externalClock; - internal ushort maxSpeed; - internal ushort currentSpeed; - internal byte status; - internal byte processorUpgrade; - internal ushort L1CacheHandler; - internal ushort L2CacheHandler; - internal ushort L3CacheHandler; - internal byte serialNumber; - internal byte assetTag; - internal byte partNumber; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SMBIOSTableCacheInfo - { - internal SMBIOSTableHeader header; - internal byte socketDesignation; - internal long cacheConfiguration; - internal ushort maximumCacheSize; - internal ushort installedSize; - internal ushort supportedSRAMType; - internal ushort currentSRAMType; - internal byte cacheSpeed; - internal byte errorCorrectionType; - internal byte systemCacheType; - internal byte associativity; - } - - #endregion - - #region [struct] RawSMBIOSData - - [StructLayout(LayoutKind.Sequential)] - internal struct RawSMBIOSData - { - internal byte Used20CallingMethod; - internal byte MajorVersion; - internal byte MinorVersion; - internal byte DmiRevision; - internal uint Length; - internal SMBIOSTableBiosInfo BiosInfo; - internal SMBIOSTableSystemInfo SystemInfo; - internal SMBIOSTableBaseBoardInfo BaseBoardInfo; - internal SMBIOSTableEnclosureInfo EnclosureInfo; - internal SMBIOSTableProcessorInfo ProcessorInfo; - internal SMBIOSTableCacheInfo CacheInfo; - } - - #endregion - - #region [private] GetTable - - private static byte[] GetTable(BiosFirmwareTableProvider provider, string table) - { - var id = table[3] << 24 | table[2] << 16 | table[1] << 8 | table[0]; - return GetTable(provider, id); - } - - private static byte[] GetTable(BiosFirmwareTableProvider provider, int table) - { - var Result = new byte[0]; - try - { - var sizeNeeded = GetSystemFirmwareTable(provider, table, IntPtr.Zero, 0); - if (sizeNeeded > 0) - { - var bufferPtr = Marshal.AllocHGlobal(sizeNeeded); - GetSystemFirmwareTable(provider, table, bufferPtr, sizeNeeded); - if (Marshal.GetLastWin32Error() == 0) - { - Result = new byte[sizeNeeded]; - Marshal.Copy(bufferPtr, Result, 0, sizeNeeded); - } - - Marshal.FreeHGlobal(bufferPtr); - } - } - catch - { - } - - return Result; - } - - #endregion - - #region [private] EnumerateTables - - private static string[] EnumerateTables(BiosFirmwareTableProvider provider) - { - var Result = new string[0]; - try - { - var sizeNeeded = EnumSystemFirmwareTables(provider, IntPtr.Zero, 0); - if (sizeNeeded > 0) - { - var buffer = new byte[sizeNeeded]; - var bufferPtr = Marshal.AllocHGlobal(sizeNeeded); - EnumSystemFirmwareTables(provider, bufferPtr, sizeNeeded); - if (Marshal.GetLastWin32Error() == 0) - { - Result = new string[sizeNeeded / 4]; - Marshal.Copy(bufferPtr, buffer, 0, sizeNeeded); - for (var i = 0; i < Result.Length; i++) Result[i] = Encoding.ASCII.GetString(buffer, 4 * i, 4); - } - - Marshal.FreeHGlobal(bufferPtr); - } - } - catch - { - } - - return Result; - } - - #endregion - - #region [private] GetRawStrings - - private static string[] GetRawStrings(byte[] bytes, SMBIOSTableEntry entry, ref int pos) - { - var result = new List(); - pos += entry.header.length; - do - { - string s = bytes.GetString(pos); - result.Add(s); - pos += s.Length; - } while (bytes[++pos] != 0); - - pos++; - return result.ToArray(); - } - - #endregion - - // VIDEO // - - #region [enum] DisplayDeviceStateFlags - - internal enum DisplayDeviceStateFlags - { - AttachedToDesktop = 0x0000001, - MultiDriver = 0x0000002, - PrimaryDevice = 0x0000004, - MirroringDriver = 0x0000008, - VGACompatible = 0x0000010, - Removable = 0x0000020, - ModesPruned = 0x8000000, - Remote = 0x4000000, - Disconnect = 0x2000000 - } - - #endregion - - #region [struct] DISPLAY_DEVICE - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - internal struct DISPLAY_DEVICE - { - [MarshalAs(UnmanagedType.U4)] internal int structSize; - - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] - internal string DeviceName; - - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - internal string DeviceString; - - [MarshalAs(UnmanagedType.U4)] internal DisplayDeviceStateFlags StateFlags; - - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - internal string DeviceID; - - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - internal string DeviceKey; - } - - #endregion - - internal Hardware() - { - using (var Binary = new BinaryWriter(new MemoryStream())) - { +// if (DeviceIoControl(hDisk, DFP_RECEIVE_DRIVE_DATA, SCI, Marshal.SizeOf(SCI), ref Result.Params, Marshal.SizeOf(Result.Params), ref iBytesReturned, 0)) +// { +// Console.WriteLine("Received: SENDCMDOUTPARAMS"); +// Console.WriteLine("> IDS.Capabilities: "+Result.Params.IDS.Capabilities); +// Console.WriteLine("> IDS.BufferSize: "+Result.Params.IDS.BufferSize); +// Console.WriteLine("> IDS.SectorsPerTrack: "+Result.Params.IDS.SectorsPerTrack); +// Console.WriteLine("> IDS.NumberCylinders: "+Result.Params.IDS.NumberCylinders); +// Console.WriteLine("> IDS.NumberHeads: "+Result.Params.IDS.NumberHeads); + +// Result.Model = SwapBytes(Result.Params.IDS.ModelNumber).Trim(); +// Result.Firmware = SwapBytes(Result.Params.IDS.FirmwareRevision).Trim(); +// Result.SerialNumber = SwapBytes(Result.Params.IDS.SerialNumber).Trim(); +// } + +// } + +// return Result; +// } + +// throw new Win32Exception(); +// } + +// #endregion + +// // CPU // + +// #region [enum] BiosFirmwareTableProvider + +// internal enum BiosFirmwareTableProvider +// { +// ACPI = (byte) 'A' << 24 | (byte) 'C' << 16 | (byte) 'P' << 8 | (byte) 'I', +// FIRM = (byte) 'F' << 24 | (byte) 'I' << 16 | (byte) 'R' << 8 | (byte) 'M', +// RSMB = (byte) 'R' << 24 | (byte) 'S' << 16 | (byte) 'M' << 8 | (byte) 'B' +// } + +// #endregion + +// #region [enum] SMBIOSTableType + +// internal enum SMBIOSTableType : sbyte +// { +// BIOSInformation = 0, +// SystemInformation = 1, +// BaseBoardInformation = 2, +// EnclosureInformation = 3, +// ProcessorInformation = 4, +// MemoryControllerInformation = 5, +// MemoryModuleInformation = 6, +// CacheInformation = 7, +// PortConnectorInformation = 8, +// SystemSlotsInformation = 9, +// OnBoardDevicesInformation = 10, +// OEMStrings = 11, +// SystemConfigurationOptions = 12, +// BIOSLanguageInformation = 13, +// GroupAssociations = 14, +// SystemEventLog = 15, +// PhysicalMemoryArray = 16, +// MemoryDevice = 17, +// MemoryErrorInformation = 18, +// MemoryArrayMappedAddress = 19, +// MemoryDeviceMappedAddress = 20, +// EndofTable = 127 +// } + +// #endregion + +// #region [enum] SMBIOSTableEntry + +// [StructLayout(LayoutKind.Sequential)] +// internal struct SMBIOSTableHeader +// { +// internal SMBIOSTableType type; +// internal byte length; +// internal ushort Handle; +// } + +// [StructLayout(LayoutKind.Sequential)] +// internal struct SMBIOSTableEntry +// { +// internal SMBIOSTableHeader header; +// internal uint index; +// } + +// #endregion + +// #region [enum] SMBIOSTableInfo + +// [StructLayout(LayoutKind.Sequential)] +// internal struct SMBIOSTableBiosInfo +// { +// internal SMBIOSTableHeader header; +// internal byte vendor; +// internal byte version; +// internal ushort startingSegment; +// internal byte releaseDate; +// internal byte biosRomSize; +// internal ulong characteristics; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] +// internal byte[] extensionBytes; +// } + +// [StructLayout(LayoutKind.Sequential)] +// internal struct SMBIOSTableSystemInfo +// { +// internal SMBIOSTableHeader header; +// internal byte manufacturer; +// internal byte productName; +// internal byte version; +// internal byte serialNumber; + +// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] +// internal byte[] UUID; + +// internal byte wakeUpType; +// } + +// [StructLayout(LayoutKind.Sequential)] +// internal struct SMBIOSTableBaseBoardInfo +// { +// internal SMBIOSTableHeader header; +// internal byte manufacturer; +// internal byte productName; +// internal byte version; +// internal byte serialNumber; +// } + +// [StructLayout(LayoutKind.Sequential)] +// internal struct SMBIOSTableEnclosureInfo +// { +// internal SMBIOSTableHeader header; +// internal byte manufacturer; +// internal byte type; +// internal byte version; +// internal byte serialNumber; +// internal byte assetTagNumber; +// internal byte bootUpState; +// internal byte powerSupplyState; +// internal byte thermalState; +// internal byte securityStatus; +// internal long OEM_Defined; +// } + +// [StructLayout(LayoutKind.Sequential)] +// internal struct SMBIOSTableProcessorInfo +// { +// internal SMBIOSTableHeader header; +// internal byte socketDesignation; +// internal byte processorType; +// internal byte processorFamily; +// internal byte processorManufacturer; +// internal ulong processorID; +// internal byte processorVersion; +// internal byte processorVoltage; +// internal ushort externalClock; +// internal ushort maxSpeed; +// internal ushort currentSpeed; +// internal byte status; +// internal byte processorUpgrade; +// internal ushort L1CacheHandler; +// internal ushort L2CacheHandler; +// internal ushort L3CacheHandler; +// internal byte serialNumber; +// internal byte assetTag; +// internal byte partNumber; +// } + +// [StructLayout(LayoutKind.Sequential)] +// internal struct SMBIOSTableCacheInfo +// { +// internal SMBIOSTableHeader header; +// internal byte socketDesignation; +// internal long cacheConfiguration; +// internal ushort maximumCacheSize; +// internal ushort installedSize; +// internal ushort supportedSRAMType; +// internal ushort currentSRAMType; +// internal byte cacheSpeed; +// internal byte errorCorrectionType; +// internal byte systemCacheType; +// internal byte associativity; +// } + +// #endregion + +// #region [struct] RawSMBIOSData + +// [StructLayout(LayoutKind.Sequential)] +// internal struct RawSMBIOSData +// { +// internal byte Used20CallingMethod; +// internal byte MajorVersion; +// internal byte MinorVersion; +// internal byte DmiRevision; +// internal uint Length; +// internal SMBIOSTableBiosInfo BiosInfo; +// internal SMBIOSTableSystemInfo SystemInfo; +// internal SMBIOSTableBaseBoardInfo BaseBoardInfo; +// internal SMBIOSTableEnclosureInfo EnclosureInfo; +// internal SMBIOSTableProcessorInfo ProcessorInfo; +// internal SMBIOSTableCacheInfo CacheInfo; +// } + +// #endregion + +// #region [private] GetTable + +// private static byte[] GetTable(BiosFirmwareTableProvider provider, string table) +// { +// var id = table[3] << 24 | table[2] << 16 | table[1] << 8 | table[0]; +// return GetTable(provider, id); +// } + +// private static byte[] GetTable(BiosFirmwareTableProvider provider, int table) +// { +// var Result = new byte[0]; +// try +// { +// var sizeNeeded = GetSystemFirmwareTable(provider, table, IntPtr.Zero, 0); +// if (sizeNeeded > 0) +// { +// var bufferPtr = Marshal.AllocHGlobal(sizeNeeded); +// GetSystemFirmwareTable(provider, table, bufferPtr, sizeNeeded); +// if (Marshal.GetLastWin32Error() == 0) +// { +// Result = new byte[sizeNeeded]; +// Marshal.Copy(bufferPtr, Result, 0, sizeNeeded); +// } + +// Marshal.FreeHGlobal(bufferPtr); +// } +// } +// catch +// { +// } + +// return Result; +// } + +// #endregion + +// #region [private] EnumerateTables + +// private static string[] EnumerateTables(BiosFirmwareTableProvider provider) +// { +// var Result = new string[0]; +// try +// { +// var sizeNeeded = EnumSystemFirmwareTables(provider, IntPtr.Zero, 0); +// if (sizeNeeded > 0) +// { +// var buffer = new byte[sizeNeeded]; +// var bufferPtr = Marshal.AllocHGlobal(sizeNeeded); +// EnumSystemFirmwareTables(provider, bufferPtr, sizeNeeded); +// if (Marshal.GetLastWin32Error() == 0) +// { +// Result = new string[sizeNeeded / 4]; +// Marshal.Copy(bufferPtr, buffer, 0, sizeNeeded); +// for (var i = 0; i < Result.Length; i++) Result[i] = Encoding.ASCII.GetString(buffer, 4 * i, 4); +// } + +// Marshal.FreeHGlobal(bufferPtr); +// } +// } +// catch +// { +// } + +// return Result; +// } + +// #endregion + +// #region [private] GetRawStrings + +// private static string[] GetRawStrings(byte[] bytes, SMBIOSTableEntry entry, ref int pos) +// { +// var result = new List(); +// pos += entry.header.length; +// do +// { +// string s = bytes.GetString(pos); +// result.Add(s); +// pos += s.Length; +// } while (bytes[++pos] != 0); + +// pos++; +// return result.ToArray(); +// } + +// #endregion + +// // VIDEO // + +// #region [enum] DisplayDeviceStateFlags + +// internal enum DisplayDeviceStateFlags +// { +// AttachedToDesktop = 0x0000001, +// MultiDriver = 0x0000002, +// PrimaryDevice = 0x0000004, +// MirroringDriver = 0x0000008, +// VGACompatible = 0x0000010, +// Removable = 0x0000020, +// ModesPruned = 0x8000000, +// Remote = 0x4000000, +// Disconnect = 0x2000000 +// } + +// #endregion + +// #region [struct] DISPLAY_DEVICE + +// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] +// internal struct DISPLAY_DEVICE +// { +// [MarshalAs(UnmanagedType.U4)] internal int structSize; + +// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] +// internal string DeviceName; + +// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] +// internal string DeviceString; + +// [MarshalAs(UnmanagedType.U4)] internal DisplayDeviceStateFlags StateFlags; + +// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] +// internal string DeviceID; + +// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] +// internal string DeviceKey; +// } + +// #endregion + +// internal Hardware() +// { +// using (var Binary = new BinaryWriter(new MemoryStream())) +// { - Console.WriteLine(); +// Console.WriteLine(); - Console.ForegroundColor = ConsoleColor.White; +// Console.ForegroundColor = ConsoleColor.White; - Console.WriteLine("[SMBIOS]"); - - // Get BIOS Information // - var RSMB_Tables = EnumerateTables(BiosFirmwareTableProvider.RSMB); - if (RSMB_Tables.Length > 0) - { - var RSMB = GetTable(BiosFirmwareTableProvider.RSMB, RSMB_Tables[0]); - if (RSMB.Length > 0) - { +// Console.WriteLine("[SMBIOS]"); + +// // Get BIOS Information // +// var RSMB_Tables = EnumerateTables(BiosFirmwareTableProvider.RSMB); +// if (RSMB_Tables.Length > 0) +// { +// var RSMB = GetTable(BiosFirmwareTableProvider.RSMB, RSMB_Tables[0]); +// if (RSMB.Length > 0) +// { - File.WriteAllBytes("BIOS." + BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(RSMB), 0).Replace("-", "") + ".RSMB.bin", RSMB); +// File.WriteAllBytes("BIOS." + BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(RSMB), 0).Replace("-", "") + ".RSMB.bin", RSMB); - Binary.Write(RSMB); +// Binary.Write(RSMB); - var RawStrings = new string[0]; - RawSMBIOSData SMBIOS = RSMB.ToStruct(); +// var RawStrings = new string[0]; +// RawSMBIOSData SMBIOS = RSMB.ToStruct(); - if (SMBIOS.Length > 8) - { - var pos = 0x08; - while (pos < SMBIOS.Length) - { +// if (SMBIOS.Length > 8) +// { +// var pos = 0x08; +// while (pos < SMBIOS.Length) +// { - Console.ForegroundColor = ConsoleColor.Green; - SMBIOSTableEntry tableEntry = RSMB.ToStruct(pos); - switch (tableEntry.header.type) - { - case SMBIOSTableType.BIOSInformation: - SMBIOS.BiosInfo = RSMB.ToStruct(pos); - RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); +// Console.ForegroundColor = ConsoleColor.Green; +// SMBIOSTableEntry tableEntry = RSMB.ToStruct(pos); +// switch (tableEntry.header.type) +// { +// case SMBIOSTableType.BIOSInformation: +// SMBIOS.BiosInfo = RSMB.ToStruct(pos); +// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - Console.WriteLine("BIOSInformation"); +// Console.WriteLine("BIOSInformation"); - Console.ForegroundColor = ConsoleColor.Yellow; +// Console.ForegroundColor = ConsoleColor.Yellow; - if (SMBIOS.BiosInfo.vendor > 0 && SMBIOS.BiosInfo.vendor <= RawStrings.Length) - Console.WriteLine("Vendor: " + RawStrings[SMBIOS.BiosInfo.vendor - 1]); +// if (SMBIOS.BiosInfo.vendor > 0 && SMBIOS.BiosInfo.vendor <= RawStrings.Length) +// Console.WriteLine("Vendor: " + RawStrings[SMBIOS.BiosInfo.vendor - 1]); - if (SMBIOS.BiosInfo.version > 0 && SMBIOS.BiosInfo.version <= RawStrings.Length) - Console.WriteLine("Version: " + RawStrings[SMBIOS.BiosInfo.version - 1]); - break; - case SMBIOSTableType.SystemInformation: - SMBIOS.SystemInfo = RSMB.ToStruct(pos); - RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); +// if (SMBIOS.BiosInfo.version > 0 && SMBIOS.BiosInfo.version <= RawStrings.Length) +// Console.WriteLine("Version: " + RawStrings[SMBIOS.BiosInfo.version - 1]); +// break; +// case SMBIOSTableType.SystemInformation: +// SMBIOS.SystemInfo = RSMB.ToStruct(pos); +// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - Console.WriteLine("SystemInformation"); +// Console.WriteLine("SystemInformation"); - Console.ForegroundColor = ConsoleColor.Yellow; +// Console.ForegroundColor = ConsoleColor.Yellow; - if (SMBIOS.SystemInfo.manufacturer > 0 && - SMBIOS.SystemInfo.manufacturer <= RawStrings.Length) - Console.WriteLine("Manufacturer: " + RawStrings[SMBIOS.SystemInfo.manufacturer - 1]); +// if (SMBIOS.SystemInfo.manufacturer > 0 && +// SMBIOS.SystemInfo.manufacturer <= RawStrings.Length) +// Console.WriteLine("Manufacturer: " + RawStrings[SMBIOS.SystemInfo.manufacturer - 1]); - if (SMBIOS.SystemInfo.productName > 0 && - SMBIOS.SystemInfo.productName <= RawStrings.Length) - Console.WriteLine("Product name: " + RawStrings[SMBIOS.SystemInfo.productName - 1]); +// if (SMBIOS.SystemInfo.productName > 0 && +// SMBIOS.SystemInfo.productName <= RawStrings.Length) +// Console.WriteLine("Product name: " + RawStrings[SMBIOS.SystemInfo.productName - 1]); - if (SMBIOS.SystemInfo.version > 0 && SMBIOS.SystemInfo.version <= RawStrings.Length) - Console.WriteLine("Version: " + RawStrings[SMBIOS.SystemInfo.version - 1]); +// if (SMBIOS.SystemInfo.version > 0 && SMBIOS.SystemInfo.version <= RawStrings.Length) +// Console.WriteLine("Version: " + RawStrings[SMBIOS.SystemInfo.version - 1]); - if (SMBIOS.SystemInfo.serialNumber > 0 && - SMBIOS.SystemInfo.serialNumber <= RawStrings.Length) - Console.WriteLine("Serial Number: " + RawStrings[SMBIOS.SystemInfo.serialNumber - 1]); - break; - case SMBIOSTableType.BaseBoardInformation: - SMBIOS.BaseBoardInfo = RSMB.ToStruct(pos); - RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); +// if (SMBIOS.SystemInfo.serialNumber > 0 && +// SMBIOS.SystemInfo.serialNumber <= RawStrings.Length) +// Console.WriteLine("Serial Number: " + RawStrings[SMBIOS.SystemInfo.serialNumber - 1]); +// break; +// case SMBIOSTableType.BaseBoardInformation: +// SMBIOS.BaseBoardInfo = RSMB.ToStruct(pos); +// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - Console.WriteLine("BaseBoardInformation"); +// Console.WriteLine("BaseBoardInformation"); - Console.ForegroundColor = ConsoleColor.Yellow; +// Console.ForegroundColor = ConsoleColor.Yellow; - if (SMBIOS.BaseBoardInfo.manufacturer > 0 && - SMBIOS.BaseBoardInfo.manufacturer <= RawStrings.Length) - Console.WriteLine("Manufacturer: " + - RawStrings[SMBIOS.BaseBoardInfo.manufacturer - 1]); +// if (SMBIOS.BaseBoardInfo.manufacturer > 0 && +// SMBIOS.BaseBoardInfo.manufacturer <= RawStrings.Length) +// Console.WriteLine("Manufacturer: " + +// RawStrings[SMBIOS.BaseBoardInfo.manufacturer - 1]); - if (SMBIOS.BaseBoardInfo.productName > 0 && - SMBIOS.BaseBoardInfo.productName <= RawStrings.Length) - Console.WriteLine("Product name: " + RawStrings[SMBIOS.BaseBoardInfo.productName - 1]); +// if (SMBIOS.BaseBoardInfo.productName > 0 && +// SMBIOS.BaseBoardInfo.productName <= RawStrings.Length) +// Console.WriteLine("Product name: " + RawStrings[SMBIOS.BaseBoardInfo.productName - 1]); - if (SMBIOS.BaseBoardInfo.version > 0 && SMBIOS.BaseBoardInfo.version <= RawStrings.Length) - Console.WriteLine("Version: " + RawStrings[SMBIOS.BaseBoardInfo.version - 1]); +// if (SMBIOS.BaseBoardInfo.version > 0 && SMBIOS.BaseBoardInfo.version <= RawStrings.Length) +// Console.WriteLine("Version: " + RawStrings[SMBIOS.BaseBoardInfo.version - 1]); - if (SMBIOS.BaseBoardInfo.serialNumber > 0 && - SMBIOS.BaseBoardInfo.serialNumber <= RawStrings.Length) - Console.WriteLine( - "Serial Number: " + RawStrings[SMBIOS.BaseBoardInfo.serialNumber - 1]); - break; - case SMBIOSTableType.EnclosureInformation: - SMBIOS.EnclosureInfo = RSMB.ToStruct(pos); - RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); +// if (SMBIOS.BaseBoardInfo.serialNumber > 0 && +// SMBIOS.BaseBoardInfo.serialNumber <= RawStrings.Length) +// Console.WriteLine( +// "Serial Number: " + RawStrings[SMBIOS.BaseBoardInfo.serialNumber - 1]); +// break; +// case SMBIOSTableType.EnclosureInformation: +// SMBIOS.EnclosureInfo = RSMB.ToStruct(pos); +// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - Console.WriteLine("EnclosureInformation"); +// Console.WriteLine("EnclosureInformation"); - Console.ForegroundColor = ConsoleColor.Yellow; +// Console.ForegroundColor = ConsoleColor.Yellow; - if (SMBIOS.EnclosureInfo.manufacturer > 0 && - SMBIOS.EnclosureInfo.manufacturer <= RawStrings.Length) - Console.WriteLine("Manufacturer: " + - RawStrings[SMBIOS.EnclosureInfo.manufacturer - 1]); +// if (SMBIOS.EnclosureInfo.manufacturer > 0 && +// SMBIOS.EnclosureInfo.manufacturer <= RawStrings.Length) +// Console.WriteLine("Manufacturer: " + +// RawStrings[SMBIOS.EnclosureInfo.manufacturer - 1]); - if (SMBIOS.EnclosureInfo.version > 0 && SMBIOS.EnclosureInfo.version <= RawStrings.Length) - Console.WriteLine("Version: " + RawStrings[SMBIOS.EnclosureInfo.version - 1]); +// if (SMBIOS.EnclosureInfo.version > 0 && SMBIOS.EnclosureInfo.version <= RawStrings.Length) +// Console.WriteLine("Version: " + RawStrings[SMBIOS.EnclosureInfo.version - 1]); - if (SMBIOS.EnclosureInfo.serialNumber > 0 && - SMBIOS.EnclosureInfo.serialNumber <= RawStrings.Length) - Console.WriteLine( - "Serial Number: " + RawStrings[SMBIOS.EnclosureInfo.serialNumber - 1]); +// if (SMBIOS.EnclosureInfo.serialNumber > 0 && +// SMBIOS.EnclosureInfo.serialNumber <= RawStrings.Length) +// Console.WriteLine( +// "Serial Number: " + RawStrings[SMBIOS.EnclosureInfo.serialNumber - 1]); - if (SMBIOS.EnclosureInfo.assetTagNumber > 0 && - SMBIOS.EnclosureInfo.assetTagNumber <= RawStrings.Length) - Console.WriteLine("Asset Tag Number: " + - RawStrings[SMBIOS.EnclosureInfo.assetTagNumber - 1]); - break; - case SMBIOSTableType.ProcessorInformation: - SMBIOS.ProcessorInfo = RSMB.ToStruct(pos); - RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); +// if (SMBIOS.EnclosureInfo.assetTagNumber > 0 && +// SMBIOS.EnclosureInfo.assetTagNumber <= RawStrings.Length) +// Console.WriteLine("Asset Tag Number: " + +// RawStrings[SMBIOS.EnclosureInfo.assetTagNumber - 1]); +// break; +// case SMBIOSTableType.ProcessorInformation: +// SMBIOS.ProcessorInfo = RSMB.ToStruct(pos); +// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - Console.WriteLine("ProcessorInformation"); +// Console.WriteLine("ProcessorInformation"); - Console.ForegroundColor = ConsoleColor.Yellow; +// Console.ForegroundColor = ConsoleColor.Yellow; - if (SMBIOS.ProcessorInfo.processorManufacturer > 0 && - SMBIOS.ProcessorInfo.processorManufacturer <= RawStrings.Length) - Console.WriteLine("Manufacturer: " + - RawStrings[SMBIOS.ProcessorInfo.processorManufacturer - 1]); +// if (SMBIOS.ProcessorInfo.processorManufacturer > 0 && +// SMBIOS.ProcessorInfo.processorManufacturer <= RawStrings.Length) +// Console.WriteLine("Manufacturer: " + +// RawStrings[SMBIOS.ProcessorInfo.processorManufacturer - 1]); - if (SMBIOS.ProcessorInfo.processorType > 0 && - SMBIOS.ProcessorInfo.processorType <= RawStrings.Length) - Console.WriteLine("Model: " + RawStrings[SMBIOS.ProcessorInfo.processorType - 1]); +// if (SMBIOS.ProcessorInfo.processorType > 0 && +// SMBIOS.ProcessorInfo.processorType <= RawStrings.Length) +// Console.WriteLine("Model: " + RawStrings[SMBIOS.ProcessorInfo.processorType - 1]); - if (SMBIOS.ProcessorInfo.processorFamily > 0 && - SMBIOS.ProcessorInfo.processorFamily <= RawStrings.Length) - Console.WriteLine("Family: " + RawStrings[SMBIOS.ProcessorInfo.processorFamily - 1]); +// if (SMBIOS.ProcessorInfo.processorFamily > 0 && +// SMBIOS.ProcessorInfo.processorFamily <= RawStrings.Length) +// Console.WriteLine("Family: " + RawStrings[SMBIOS.ProcessorInfo.processorFamily - 1]); - if (SMBIOS.ProcessorInfo.serialNumber > 0 && - SMBIOS.ProcessorInfo.serialNumber <= RawStrings.Length) - Console.WriteLine( - "Serial Number: " + RawStrings[SMBIOS.ProcessorInfo.serialNumber - 1]); +// if (SMBIOS.ProcessorInfo.serialNumber > 0 && +// SMBIOS.ProcessorInfo.serialNumber <= RawStrings.Length) +// Console.WriteLine( +// "Serial Number: " + RawStrings[SMBIOS.ProcessorInfo.serialNumber - 1]); - if (SMBIOS.ProcessorInfo.assetTag > 0 && - SMBIOS.ProcessorInfo.assetTag <= RawStrings.Length) - Console.WriteLine("Asset Tag: " + RawStrings[SMBIOS.ProcessorInfo.assetTag - 1]); - break; - case SMBIOSTableType.CacheInformation: - SMBIOS.CacheInfo = RSMB.ToStruct(pos); - RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); +// if (SMBIOS.ProcessorInfo.assetTag > 0 && +// SMBIOS.ProcessorInfo.assetTag <= RawStrings.Length) +// Console.WriteLine("Asset Tag: " + RawStrings[SMBIOS.ProcessorInfo.assetTag - 1]); +// break; +// case SMBIOSTableType.CacheInformation: +// SMBIOS.CacheInfo = RSMB.ToStruct(pos); +// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - Console.WriteLine("CacheInformation [" + RawStrings[0] + "]"); +// Console.WriteLine("CacheInformation [" + RawStrings[0] + "]"); - Console.ForegroundColor = ConsoleColor.Yellow; +// Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine("Installed Size: " + SMBIOS.CacheInfo.installedSize); +// Console.WriteLine("Installed Size: " + SMBIOS.CacheInfo.installedSize); - Console.WriteLine("Maximum CacheSize: " + SMBIOS.CacheInfo.maximumCacheSize); - break; - default: - Console.WriteLine(tableEntry.header.type); - RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - break; - } - } - } - } - } - - var tableIndex = 0; - foreach (var biosTable in EnumerateTables(BiosFirmwareTableProvider.FIRM)) - { - var FIRM = GetTable(BiosFirmwareTableProvider.FIRM, biosTable); +// Console.WriteLine("Maximum CacheSize: " + SMBIOS.CacheInfo.maximumCacheSize); +// break; +// default: +// Console.WriteLine(tableEntry.header.type); +// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); +// break; +// } +// } +// } +// } +// } + +// var tableIndex = 0; +// foreach (var biosTable in EnumerateTables(BiosFirmwareTableProvider.FIRM)) +// { +// var FIRM = GetTable(BiosFirmwareTableProvider.FIRM, biosTable); - File.WriteAllBytes("BIOS." + BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(FIRM), 0).Replace("-", "") + ".FIRM" + (tableIndex++) + ".bin", FIRM); +// File.WriteAllBytes("BIOS." + BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(FIRM), 0).Replace("-", "") + ".FIRM" + (tableIndex++) + ".bin", FIRM); - } +// } - Console.WriteLine(); +// Console.WriteLine(); - Console.ForegroundColor = ConsoleColor.White; +// Console.ForegroundColor = ConsoleColor.White; - Console.WriteLine("[CPU]"); - - // Get CPU Information (Count, ID) // - byte[] code_x86 = { - 0x55, 0x89, 0xe5, 0x57, 0x8b, 0x7d, 0x10, 0x6a, 0x01, 0x58, 0x53, 0x0f, 0xa2, 0x89, 0x07, 0x89, 0x57, - 0x04, 0x5b, 0x5f, 0x89, 0xec, 0x5d, 0xc2, 0x10, 0x00 - }; - byte[] code_x64 = { - 0x53, 0x48, 0xc7, 0xc0, 0x01, 0x00, 0x00, 0x00, 0x0f, 0xa2, 0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, - 0x5b, 0xc3 - }; - var CPUID = new byte[8]; - byte[] asmCode; - int protect; - if (IntPtr.Size == 8) asmCode = code_x64; - else asmCode = code_x86; - var asmSize = new IntPtr(asmCode.Length); - if (!VirtualProtect(asmCode, asmSize, 0x40, out protect)) - Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); - asmSize = new IntPtr(CPUID.Length); - if (CallWindowProcW(asmCode, IntPtr.Zero, 0, CPUID, asmSize) == IntPtr.Zero) return; - var RegKey = - Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor"); - var ProcessorName = RegKey.OpenSubKey("0").GetValue("ProcessorNameString").ToString(); - var CPUIdentifier = RegKey.OpenSubKey("0").GetValue("Identifier").ToString(); - var ProcessorCores = RegKey.GetSubKeyNames(); +// Console.WriteLine("[CPU]"); + +// // Get CPU Information (Count, ID) // +// byte[] code_x86 = { +// 0x55, 0x89, 0xe5, 0x57, 0x8b, 0x7d, 0x10, 0x6a, 0x01, 0x58, 0x53, 0x0f, 0xa2, 0x89, 0x07, 0x89, 0x57, +// 0x04, 0x5b, 0x5f, 0x89, 0xec, 0x5d, 0xc2, 0x10, 0x00 +// }; +// byte[] code_x64 = { +// 0x53, 0x48, 0xc7, 0xc0, 0x01, 0x00, 0x00, 0x00, 0x0f, 0xa2, 0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, +// 0x5b, 0xc3 +// }; +// var CPUID = new byte[8]; +// byte[] asmCode; +// int protect; +// if (IntPtr.Size == 8) asmCode = code_x64; +// else asmCode = code_x86; +// var asmSize = new IntPtr(asmCode.Length); +// if (!VirtualProtect(asmCode, asmSize, 0x40, out protect)) +// Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); +// asmSize = new IntPtr(CPUID.Length); +// if (CallWindowProcW(asmCode, IntPtr.Zero, 0, CPUID, asmSize) == IntPtr.Zero) return; +// var RegKey = +// Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor"); +// var ProcessorName = RegKey.OpenSubKey("0").GetValue("ProcessorNameString").ToString(); +// var CPUIdentifier = RegKey.OpenSubKey("0").GetValue("Identifier").ToString(); +// var ProcessorCores = RegKey.GetSubKeyNames(); - Console.ForegroundColor = ConsoleColor.Green; +// Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine(ProcessorName + ", " + CPUIdentifier); +// Console.WriteLine(ProcessorName + ", " + CPUIdentifier); - Console.ForegroundColor = ConsoleColor.Yellow; +// Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine("> Processor Cores: " + ProcessorCores.Length); +// Console.WriteLine("> Processor Cores: " + ProcessorCores.Length); - Console.WriteLine("> ID: " + BitConverter.ToString(CPUID, 0).Replace("-", "")); +// Console.WriteLine("> ID: " + BitConverter.ToString(CPUID, 0).Replace("-", "")); - Binary.Write(ProcessorName); - Binary.Write(CPUIdentifier); - Binary.Write(ProcessorCores.Length); - Binary.Write(CPUID); +// Binary.Write(ProcessorName); +// Binary.Write(CPUIdentifier); +// Binary.Write(ProcessorCores.Length); +// Binary.Write(CPUID); - Console.WriteLine(); +// Console.WriteLine(); - Console.ForegroundColor = ConsoleColor.White; +// Console.ForegroundColor = ConsoleColor.White; - Console.WriteLine("[DRIVES]"); +// Console.WriteLine("[DRIVES]"); - // Get HDD Information // - foreach (var drive in Environment.GetLogicalDrives()) - { - var disk = GetPhysicalDisk(drive); - if (disk.RemovableMedia) continue; +// // Get HDD Information // +// foreach (var drive in Environment.GetLogicalDrives()) +// { +// var disk = GetPhysicalDisk(drive); +// if (disk.RemovableMedia) continue; - Console.ForegroundColor = ConsoleColor.Green; +// Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("Disk: " + drive); +// Console.WriteLine("Disk: " + drive); - Console.ForegroundColor = ConsoleColor.Yellow; +// Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine("> Model: " + disk.Model + ", Firmware: " + disk.Firmware + "\n> Serial: " + - disk.SerialNumber); - if (string.IsNullOrEmpty(disk.Model) || string.IsNullOrEmpty(disk.Firmware)) continue; - Binary.Write(disk.Model); - Binary.Write(disk.Firmware); - Binary.Write(disk.SerialNumber); - } +// Console.WriteLine("> Model: " + disk.Model + ", Firmware: " + disk.Firmware + "\n> Serial: " + +// disk.SerialNumber); +// if (string.IsNullOrEmpty(disk.Model) || string.IsNullOrEmpty(disk.Firmware)) continue; +// Binary.Write(disk.Model); +// Binary.Write(disk.Firmware); +// Binary.Write(disk.SerialNumber); +// } - Console.WriteLine(); +// Console.WriteLine(); - Console.ForegroundColor = ConsoleColor.White; +// Console.ForegroundColor = ConsoleColor.White; - Console.WriteLine("[VIDEO]"); - - // Get VIDEO Information // - try - { - var display = new DISPLAY_DEVICE(); - display.structSize = Marshal.SizeOf(display); - for (uint i = 0; EnumDisplayDevices(null, i, ref display, 0); i++) - { - if (display.DeviceString == null) continue; - if (display.StateFlags.HasFlag(DisplayDeviceStateFlags.PrimaryDevice)) - { +// Console.WriteLine("[VIDEO]"); + +// // Get VIDEO Information // +// try +// { +// var display = new DISPLAY_DEVICE(); +// display.structSize = Marshal.SizeOf(display); +// for (uint i = 0; EnumDisplayDevices(null, i, ref display, 0); i++) +// { +// if (display.DeviceString == null) continue; +// if (display.StateFlags.HasFlag(DisplayDeviceStateFlags.PrimaryDevice)) +// { - Console.ForegroundColor = ConsoleColor.Green; +// Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine(display.DeviceString); +// Console.WriteLine(display.DeviceString); - Console.ForegroundColor = ConsoleColor.Yellow; +// Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine("DeviceID: " + display.DeviceID); +// Console.WriteLine("DeviceID: " + display.DeviceID); - Console.WriteLine("State Flags: " + display.StateFlags); - Binary.Write(display.DeviceString); - if (display.DeviceID != null) Binary.Write(display.DeviceID); - } - } - } - catch (Exception) - { - /* Ignore all exceptions of detecting video */ - } - - // Seek Stream Origin To Beginning and Compute Binary Buffer to MD5 // - Binary.BaseStream.Seek(0, SeekOrigin.Begin); - _MD5 = new MD5CryptoServiceProvider().ComputeHash(Binary.BaseStream); - // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA1 // - Binary.BaseStream.Seek(0, SeekOrigin.Begin); - _SHA1 = new SHA1CryptoServiceProvider().ComputeHash(Binary.BaseStream); - // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA256 // - Binary.BaseStream.Seek(0, SeekOrigin.Begin); - _SHA256 = new SHA256CryptoServiceProvider().ComputeHash(Binary.BaseStream); - // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA512 // - Binary.BaseStream.Seek(0, SeekOrigin.Begin); - _SHA512 = new SHA512CryptoServiceProvider().ComputeHash(Binary.BaseStream); - } - - Console.ResetColor(); - } - - internal byte[] MD5 - { - get - { - if (_MD5 == null || _MD5.Length < 16) return new byte[0]; - return _MD5; - } - } - - internal byte[] SHA1 - { - get - { - if (_SHA1 == null || _SHA1.Length < 16) return new byte[0]; - return _SHA1; - } - } - - internal byte[] SHA256 - { - get - { - if (_SHA256 == null || _SHA256.Length < 16) return new byte[0]; - return _SHA256; - } - } - - internal byte[] SHA512 - { - get - { - if (_SHA512 == null || _SHA512.Length < 16) return new byte[0]; - return _SHA512; - } - } - - internal string MD5String - { - get - { - if (_MD5 == null || _MD5.Length < 16) return ""; - return BitConverter.ToString(_MD5, 0).Replace("-", ""); - } - } - - internal string SHA1String - { - get - { - if (_SHA1 == null || _SHA1.Length < 16) return ""; - return BitConverter.ToString(_SHA1, 0).Replace("-", ""); - } - } - - internal string SHA256String - { - get - { - if (_SHA256 == null || _SHA256.Length < 16) return ""; - return BitConverter.ToString(_SHA256, 0).Replace("-", ""); - } - } - - internal string SHA512String - { - get - { - if (_SHA512 == null || _SHA512.Length < 16) return ""; - return BitConverter.ToString(_SHA512, 0).Replace("-", ""); - } - } - } -} +// Console.WriteLine("State Flags: " + display.StateFlags); +// Binary.Write(display.DeviceString); +// if (display.DeviceID != null) Binary.Write(display.DeviceID); +// } +// } +// } +// catch (Exception) +// { +// /* Ignore all exceptions of detecting video */ +// } + +// // Seek Stream Origin To Beginning and Compute Binary Buffer to MD5 // +// Binary.BaseStream.Seek(0, SeekOrigin.Begin); +// _MD5 = new MD5CryptoServiceProvider().ComputeHash(Binary.BaseStream); +// // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA1 // +// Binary.BaseStream.Seek(0, SeekOrigin.Begin); +// _SHA1 = new SHA1CryptoServiceProvider().ComputeHash(Binary.BaseStream); +// // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA256 // +// Binary.BaseStream.Seek(0, SeekOrigin.Begin); +// _SHA256 = new SHA256CryptoServiceProvider().ComputeHash(Binary.BaseStream); +// // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA512 // +// Binary.BaseStream.Seek(0, SeekOrigin.Begin); +// _SHA512 = new SHA512CryptoServiceProvider().ComputeHash(Binary.BaseStream); +// } + +// Console.ResetColor(); +// } + +// internal byte[] MD5 +// { +// get +// { +// if (_MD5 == null || _MD5.Length < 16) return new byte[0]; +// return _MD5; +// } +// } + +// internal byte[] SHA1 +// { +// get +// { +// if (_SHA1 == null || _SHA1.Length < 16) return new byte[0]; +// return _SHA1; +// } +// } + +// internal byte[] SHA256 +// { +// get +// { +// if (_SHA256 == null || _SHA256.Length < 16) return new byte[0]; +// return _SHA256; +// } +// } + +// internal byte[] SHA512 +// { +// get +// { +// if (_SHA512 == null || _SHA512.Length < 16) return new byte[0]; +// return _SHA512; +// } +// } + +// internal string MD5String +// { +// get +// { +// if (_MD5 == null || _MD5.Length < 16) return ""; +// return BitConverter.ToString(_MD5, 0).Replace("-", ""); +// } +// } + +// internal string SHA1String +// { +// get +// { +// if (_SHA1 == null || _SHA1.Length < 16) return ""; +// return BitConverter.ToString(_SHA1, 0).Replace("-", ""); +// } +// } + +// internal string SHA256String +// { +// get +// { +// if (_SHA256 == null || _SHA256.Length < 16) return ""; +// return BitConverter.ToString(_SHA256, 0).Replace("-", ""); +// } +// } + +// internal string SHA512String +// { +// get +// { +// if (_SHA512 == null || _SHA512.Length < 16) return ""; +// return BitConverter.ToString(_SHA512, 0).Replace("-", ""); +// } +// } +// } +//} diff --git a/AlphaFS/Device/Test2.cs b/AlphaFS/Device/Test2.cs index 8307969a9..f3ed4fa1c 100644 --- a/AlphaFS/Device/Test2.cs +++ b/AlphaFS/Device/Test2.cs @@ -1,67 +1,67 @@ -//using Microsoft.VisualBasic; - -using System; -using System.ComponentModel; -using System.Runtime.InteropServices; -using System.Security; -using Microsoft.Win32.SafeHandles; - -namespace Alphaleonis.Win32.Filesystem -{ - internal static class IOCtl - { - private const int GENERIC_READ = unchecked((int) 0x80000000); - private const int FILE_SHARE_READ = 1; - private const int FILE_SHARE_WRITE = 2; - private const int OPEN_EXISTING = 3; - - //private enum Partition : byte - //{ - // ENTRY_UNUSED = 0, - // FAT_12 = 1, - // XENIX_1 = 2, - // XENIX_2 = 3, - // FAT_16 = 4, - // EXTENDED = 5, - // HUGE = 6, - // IFS = 7, - // OS2BOOTMGR = 0xa, - // FAT32 = 0xb, - // FAT32_XINT13 = 0xc, - // XINT13 = 0xe, - // XINT13_EXTENDED = 0xf, - // PREP = 0x41, - // LDM = 0x42, - // UNIX = 0x63 - //} - - [SuppressUnmanagedCodeSecurity] - private class NativeMethods - { - - [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern SafeFileHandle CreateFile( - string fileName, - int desiredAccess, - int shareMode, - IntPtr securityAttributes, - int creationDisposition, - int flagsAndAttributes, - IntPtr hTemplateFile); - - [DllImport("kernel32", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl( - SafeFileHandle hVol, - Filesystem.NativeMethods.IoControlCode controlCode, - IntPtr inBuffer, - uint inBufferSize, - IntPtr outBuffer, - uint outBufferSize, - ref uint bytesReturned, - IntPtr overlapped); - - } +////using Microsoft.VisualBasic; + +//using System; +//using System.ComponentModel; +//using System.Runtime.InteropServices; +//using System.Security; +//using Microsoft.Win32.SafeHandles; + +//namespace Alphaleonis.Win32.Filesystem +//{ +// internal static class IOCtl +// { +// private const int GENERIC_READ = unchecked((int) 0x80000000); +// private const int FILE_SHARE_READ = 1; +// private const int FILE_SHARE_WRITE = 2; +// private const int OPEN_EXISTING = 3; + +// //private enum Partition : byte +// //{ +// // ENTRY_UNUSED = 0, +// // FAT_12 = 1, +// // XENIX_1 = 2, +// // XENIX_2 = 3, +// // FAT_16 = 4, +// // EXTENDED = 5, +// // HUGE = 6, +// // IFS = 7, +// // OS2BOOTMGR = 0xa, +// // FAT32 = 0xb, +// // FAT32_XINT13 = 0xc, +// // XINT13 = 0xe, +// // XINT13_EXTENDED = 0xf, +// // PREP = 0x41, +// // LDM = 0x42, +// // UNIX = 0x63 +// //} + +// [SuppressUnmanagedCodeSecurity] +// private class NativeMethods +// { + +// [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] +// internal static extern SafeFileHandle CreateFile( +// string fileName, +// int desiredAccess, +// int shareMode, +// IntPtr securityAttributes, +// int creationDisposition, +// int flagsAndAttributes, +// IntPtr hTemplateFile); + +// [DllImport("kernel32", SetLastError = true)] +// [return: MarshalAs(UnmanagedType.Bool)] +// internal static extern bool DeviceIoControl( +// SafeFileHandle hVol, +// Filesystem.NativeMethods.IoControlCode controlCode, +// IntPtr inBuffer, +// uint inBufferSize, +// IntPtr outBuffer, +// uint outBufferSize, +// ref uint bytesReturned, +// IntPtr overlapped); + +// } @@ -70,183 +70,183 @@ internal static extern bool DeviceIoControl( - internal static void Main() - { - SendIoCtlDiskGetDriveLayoutEx(0); - SendIoCtlDiskGetDriveLayoutEx(1); - //SendIoCtlDiskGetDriveLayoutEx(2); - } +// internal static void Main() +// { +// SendIoCtlDiskGetDriveLayoutEx(0); +// SendIoCtlDiskGetDriveLayoutEx(1); +// //SendIoCtlDiskGetDriveLayoutEx(2); +// } - private static void SendIoCtlDiskGetDriveLayoutEx(int PhysicalDrive) - { +// private static void SendIoCtlDiskGetDriveLayoutEx(int PhysicalDrive) +// { - var lie = default(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX); +// var lie = default(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX); - Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies = null; - - using (var hDevice = NativeMethods.CreateFile("\\\\.\\PHYSICALDRIVE" + PhysicalDrive, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero)) - { - if (hDevice.IsInvalid) - throw new Win32Exception(); - - - // We don't know how many partitions there are, so we have to use a blob of memory... - var numPartitions = 1; - var done = false; +// Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies = null; + +// using (var hDevice = NativeMethods.CreateFile("\\\\.\\PHYSICALDRIVE" + PhysicalDrive, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero)) +// { +// if (hDevice.IsInvalid) +// throw new Win32Exception(); + + +// // We don't know how many partitions there are, so we have to use a blob of memory... +// var numPartitions = 1; +// var done = false; - do - { - // 48 = the number of bytes in DRIVE_LAYOUT_INFORMATION_EX up to - // the first PARTITION_INFORMATION_EX in the array. - // And each PARTITION_INFORMATION_EX is 144 bytes. - var outBufferSize = 48 + numPartitions * 144; - var blob = default(IntPtr); - uint bytesReturned = 0; +// do +// { +// // 48 = the number of bytes in DRIVE_LAYOUT_INFORMATION_EX up to +// // the first PARTITION_INFORMATION_EX in the array. +// // And each PARTITION_INFORMATION_EX is 144 bytes. +// var outBufferSize = 48 + numPartitions * 144; +// var blob = default(IntPtr); +// uint bytesReturned = 0; - try - { - blob = Marshal.AllocHGlobal(outBufferSize); +// try +// { +// blob = Marshal.AllocHGlobal(outBufferSize); - var result = NativeMethods.DeviceIoControl(hDevice, Filesystem.NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, blob, (uint) outBufferSize, ref bytesReturned, IntPtr.Zero); +// var result = NativeMethods.DeviceIoControl(hDevice, Filesystem.NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, blob, (uint) outBufferSize, ref bytesReturned, IntPtr.Zero); - // We expect that we might not have enough room in the output buffer. - if (result == false) - { - // If the buffer wasn't too small, then something else went wrong. - if (Marshal.GetLastWin32Error() != Win32Errors.ERROR_INSUFFICIENT_BUFFER) - throw new Win32Exception(); - // We need more space on the next loop. - numPartitions += 1; - } - else - { - // We got the size right, so stop looping. - done = true; +// // We expect that we might not have enough room in the output buffer. +// if (result == false) +// { +// // If the buffer wasn't too small, then something else went wrong. +// if (Marshal.GetLastWin32Error() != Win32Errors.ERROR_INSUFFICIENT_BUFFER) +// throw new Win32Exception(); +// // We need more space on the next loop. +// numPartitions += 1; +// } +// else +// { +// // We got the size right, so stop looping. +// done = true; - // Do something with the data here - we'll free the memory before we leave the loop. - // First we grab the DRIVE_LAYOUT_INFORMATION_EX, it's at the start of the blob of memory: - lie = (Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX) Marshal.PtrToStructure(blob, typeof(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); +// // Do something with the data here - we'll free the memory before we leave the loop. +// // First we grab the DRIVE_LAYOUT_INFORMATION_EX, it's at the start of the blob of memory: +// lie = (Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX) Marshal.PtrToStructure(blob, typeof(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); - // Then loop and add the PARTITION_INFORMATION_EX structures to an array. - pies = new Filesystem.NativeMethods.PARTITION_INFORMATION_EX[lie.PartitionCount]; +// // Then loop and add the PARTITION_INFORMATION_EX structures to an array. +// pies = new Filesystem.NativeMethods.PARTITION_INFORMATION_EX[lie.PartitionCount]; - for (var i = 0; i <= lie.PartitionCount - 1; i++) - { - // Where is this structure in the blob of memory? - var offset = new IntPtr(blob.ToInt64() + 48 + i * 144); +// for (var i = 0; i <= lie.PartitionCount - 1; i++) +// { +// // Where is this structure in the blob of memory? +// var offset = new IntPtr(blob.ToInt64() + 48 + i * 144); - pies[i] = (Filesystem.NativeMethods.PARTITION_INFORMATION_EX) Marshal.PtrToStructure(offset, typeof(Filesystem.NativeMethods.PARTITION_INFORMATION_EX)); - } - } - } - finally - { - Marshal.FreeHGlobal(blob); - } - } while (!done); - } +// pies[i] = (Filesystem.NativeMethods.PARTITION_INFORMATION_EX) Marshal.PtrToStructure(offset, typeof(Filesystem.NativeMethods.PARTITION_INFORMATION_EX)); +// } +// } +// } +// finally +// { +// Marshal.FreeHGlobal(blob); +// } +// } while (!done); +// } - DumpInfo(lie, pies); - } +// DumpInfo(lie, pies); +// } - private static bool IsPart0Aligned(Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies) - { - try - { - return pies[0].StartingOffset % 4096 == 0; - } - catch - { - return false; - } - } +// private static bool IsPart0Aligned(Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies) +// { +// try +// { +// return pies[0].StartingOffset % 4096 == 0; +// } +// catch +// { +// return false; +// } +// } - private static void DumpInfo(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX lie, Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies) - { - //var aaa = new PartitionTypeGuid(PartitionType.LdmMetaDataGuid); +// private static void DumpInfo(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX lie, Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies) +// { +// //var aaa = new PartitionTypeGuid(PartitionType.LdmMetaDataGuid); - - Console.WriteLine("\n\nPart 0 aligned:" + IsPart0Aligned(pies)); - - - Console.WriteLine("Partition Style: {0}", lie.PartitionStyle); - Console.WriteLine("Partition Count: {0}", lie.PartitionCount); - - switch (lie.PartitionStyle) - { - case PartitionStyle.Mbr: - Console.WriteLine("Mbr Signature: {0}", lie.Mbr.Signature); - break; - case PartitionStyle.Gpt: - Console.WriteLine("Gpt DiskId : {0}", lie.Gpt.DiskId); - Console.WriteLine("Gpt StartingUsableOffset: {0}", lie.Gpt.StartingUsableOffset); - Console.WriteLine("Gpt UsableLength : {0}", lie.Gpt.UsableLength); - Console.WriteLine("Gpt UsableLength : {0}", Utils.UnitSizeToText(lie.Gpt.UsableLength)); - Console.WriteLine("Gpt MaxPartitionCount : {0}", lie.Gpt.MaxPartitionCount); - break; - - default: - Console.WriteLine("RAW!"); - break; - } + +// Console.WriteLine("\n\nPart 0 aligned:" + IsPart0Aligned(pies)); + + +// Console.WriteLine("Partition Style: {0}", lie.PartitionStyle); +// Console.WriteLine("Partition Count: {0}", lie.PartitionCount); + +// switch (lie.PartitionStyle) +// { +// case PartitionStyle.Mbr: +// Console.WriteLine("Mbr Signature: {0}", lie.Mbr.Signature); +// break; +// case PartitionStyle.Gpt: +// Console.WriteLine("Gpt DiskId : {0}", lie.Gpt.DiskId); +// Console.WriteLine("Gpt StartingUsableOffset: {0}", lie.Gpt.StartingUsableOffset); +// Console.WriteLine("Gpt UsableLength : {0}", lie.Gpt.UsableLength); +// Console.WriteLine("Gpt UsableLength : {0}", Utils.UnitSizeToText(lie.Gpt.UsableLength)); +// Console.WriteLine("Gpt MaxPartitionCount : {0}", lie.Gpt.MaxPartitionCount); +// break; + +// default: +// Console.WriteLine("RAW!"); +// break; +// } - for (var i = 0; i <= lie.PartitionCount - 1; i++) - { - var storagePartitionInfo = new StoragePartitionInfo(); - - Console.WriteLine(); - Console.WriteLine(); - Console.WriteLine("Partition {0} info...", i + 1); - Console.WriteLine("-------------------"); - - - var _with1 = pies[i]; - Console.WriteLine("Partition style : {0}", (PartitionStyle) _with1.PartitionStyle); - Console.WriteLine("Starting offset : {0}", _with1.StartingOffset); - Console.WriteLine("Partition length : {0}", _with1.PartitionLength); - Console.WriteLine("Partition length : {0}", Utils.UnitSizeToText(_with1.PartitionLength)); - Console.WriteLine("Partition number : {0}", _with1.PartitionNumber); - Console.WriteLine("Rewrite partition: {0}", _with1.RewritePartition); - - - switch ((PartitionStyle) _with1.PartitionStyle) - { - case PartitionStyle.Mbr: - var _with2 = _with1.Mbr; - Console.WriteLine("Mbr PartitionType - raw value: {0}", _with2.PartitionType); - - //Console.WriteLine("Mbr PartitionType - validNTFT: {0}", _with2.IsValidNTFT()); - - //if (_with2.IsValidNTFT()) - // Console.WriteLine("Mbr PartitionType - ntft: {0}", _with2.IsNTFT()); - - //Console.WriteLine("Mbr PartitionType - decoded: {0}", _with2.GetPartition()); - - Console.WriteLine("Mbr BootIndicator : {0}", _with2.BootIndicator); - Console.WriteLine("Mbr RecognizedPartition: {0}", _with2.RecognizedPartition); - Console.WriteLine("Mbr HiddenSectors : {0}", _with2.HiddenSectors); - break; - - case PartitionStyle.Gpt: - var _with3 = _with1.Gpt; - Console.WriteLine("Gpt PartitionType: {0}", _with3.PartitionType); - Console.WriteLine("Gpt PartitionId : {0}", _with3.PartitionId); - Console.WriteLine("Gpt Attributes : {0}", (PartitionAttributes) _with3.Attributes); - Console.WriteLine("Gpt Name : {0}", _with3.Name); - break; - - case PartitionStyle.Raw: - Console.WriteLine("RAW!"); - break; - } - } - } - } -} +// for (var i = 0; i <= lie.PartitionCount - 1; i++) +// { +// var storagePartitionInfo = new StoragePartitionInfo(); + +// Console.WriteLine(); +// Console.WriteLine(); +// Console.WriteLine("Partition {0} info...", i + 1); +// Console.WriteLine("-------------------"); + + +// var _with1 = pies[i]; +// Console.WriteLine("Partition style : {0}", (PartitionStyle) _with1.PartitionStyle); +// Console.WriteLine("Starting offset : {0}", _with1.StartingOffset); +// Console.WriteLine("Partition length : {0}", _with1.PartitionLength); +// Console.WriteLine("Partition length : {0}", Utils.UnitSizeToText(_with1.PartitionLength)); +// Console.WriteLine("Partition number : {0}", _with1.PartitionNumber); +// Console.WriteLine("Rewrite partition: {0}", _with1.RewritePartition); + + +// switch ((PartitionStyle) _with1.PartitionStyle) +// { +// case PartitionStyle.Mbr: +// var _with2 = _with1.Mbr; +// Console.WriteLine("Mbr PartitionType - raw value: {0}", _with2.PartitionType); + +// //Console.WriteLine("Mbr PartitionType - validNTFT: {0}", _with2.IsValidNTFT()); + +// //if (_with2.IsValidNTFT()) +// // Console.WriteLine("Mbr PartitionType - ntft: {0}", _with2.IsNTFT()); + +// //Console.WriteLine("Mbr PartitionType - decoded: {0}", _with2.GetPartition()); + +// Console.WriteLine("Mbr BootIndicator : {0}", _with2.BootIndicator); +// Console.WriteLine("Mbr RecognizedPartition: {0}", _with2.RecognizedPartition); +// Console.WriteLine("Mbr HiddenSectors : {0}", _with2.HiddenSectors); +// break; + +// case PartitionStyle.Gpt: +// var _with3 = _with1.Gpt; +// Console.WriteLine("Gpt PartitionType: {0}", _with3.PartitionType); +// Console.WriteLine("Gpt PartitionId : {0}", _with3.PartitionId); +// Console.WriteLine("Gpt Attributes : {0}", (PartitionAttributes) _with3.Attributes); +// Console.WriteLine("Gpt Name : {0}", _with3.Name); +// break; + +// case PartitionStyle.Raw: +// Console.WriteLine("RAW!"); +// break; +// } +// } +// } +// } +//} diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs index c769d194a..2db848942 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs @@ -69,5 +69,9 @@ internal static partial class NativeMethods /// Invalid FileAttributes = -1 internal const FileAttributes InvalidFileAttributes = (FileAttributes) (-1); + + + /// FILE_ANY_ACCESS = 0 + internal const int FILE_ANY_ACCESS = 0; } } diff --git a/AlphaFS/Filesystem/Native Other/COPY_FILE_FLAGS.cs b/AlphaFS/Filesystem/Native Other/COPY_FILE_FLAGS.cs index 2f348cddf..4a4ac31cc 100644 --- a/AlphaFS/Filesystem/Native Other/COPY_FILE_FLAGS.cs +++ b/AlphaFS/Filesystem/Native Other/COPY_FILE_FLAGS.cs @@ -19,49 +19,40 @@ * THE SOFTWARE. */ +using System; + namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - public enum COPY_FILE_FLAGS + /// Flags that specify how the file is to be copied. This parameter can be a combination of the following values. + [Flags] + internal enum COPY_FILE_FLAGS { - /// COPY_FILE_FAIL_IF_EXISTS - /// The copy operation fails immediately if the target file already exists. - /// + /// The copy operation fails immediately if the target file already exists. COPY_FILE_FAIL_IF_EXISTS = 1, - /// COPY_FILE_RESTARTABLE - /// - /// Progress of the copy is tracked in the target file in case the copy fails. The failed copy can be restarted at a later time by specifying the same values - /// forexisting file name and new file name as those used in the call that failed. This can significantly slow down the copy operation as the new file may be - /// flushed multiple times during the copy operation. - /// + /// Progress of the copy is tracked in the target file in case the copy fails. The failed copy can be restarted at a later time + /// by specifying the same values for existing file name and new file name as those used in the call that failed. This can significantly + /// slow down the copy operation as the new file may be flushed multiple times during the copy operation. /// COPY_FILE_RESTARTABLE = 2, - /// COPY_FILE_OPEN_SOURCE_FOR_WRITE - /// The file is copied and the original file is opened for write access. - /// + /// The file is copied and the original file is opened for write access. COPY_FILE_OPEN_SOURCE_FOR_WRITE = 4, - /// COPY_FILE_ALLOW_DECRYPTED_DESTINATION - /// An attempt to copy an encrypted file will succeed even if the destination copy cannot be encrypted. - /// + /// An attempt to copy an encrypted file will succeed even if the destination copy cannot be encrypted. COPY_FILE_ALLOW_DECRYPTED_DESTINATION = 8, - /// COPY_FILE_COPY_SYMLINK - /// If the source file is a symbolic link, the destination file is also a symbolic link pointing to the same file that the source symbolic link is pointing to. - /// + /// If the source file is a symbolic link, the destination file is also a symbolic link pointing to the same file that the source symbolic link is pointing to. COPY_FILE_COPY_SYMLINK = 2048, - /// COPY_FILE_NO_BUFFERING - /// The copy operation is performed using unbuffered I/O, bypassing system I/O cache resources. Recommended for very large file transfers. - /// + /// The copy operation is performed using unbuffered I/O, bypassing system I/O cache resources. Recommended for very large file transfers. COPY_FILE_NO_BUFFERING = 4096 } } diff --git a/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs b/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs index 320768c2c..6bbc9fe55 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs @@ -19,8 +19,6 @@ * THE SOFTWARE. */ -using System; -using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Alphaleonis.Win32.Filesystem diff --git a/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs b/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs new file mode 100644 index 000000000..ee1e8aee9 --- /dev/null +++ b/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs @@ -0,0 +1,60 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 + { + /// The following table identifies the valid partition types that are used by disk drivers. + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + internal enum DiskPartitionType : byte + { + /// An unused entry partition. + PARTITION_ENTRY_UNUSED = 0, + + /// A FAT12 file system partition. + PARTITION_FAT_12 = 1, + + /// A FAT16 file system partition. + PARTITION_FAT_16 = 4, + + /// An extended partition. + PARTITION_EXTENDED = 5, + + /// An IFS (Installable File System) partition. + PARTITION_IFS = 7, + + /// A FAT32 file system partition. + PARTITION_FAT32 = 11, + + /// An LDM (Logical Disk Manager) partition. + PARTITION_LDM = 66, + + /// An NTFT partition. + PARTITION_NTFT = 128, + + /// A valid NTFT partition. The high bit of a partition type code indicates that a partition is part of an NTFT mirror or striped array. + VALID_NTFT = 192 + } + } +} diff --git a/AlphaFS/Filesystem/Native Other/PartitionAttributes.cs b/AlphaFS/Filesystem/Native Other/EfiPartitionAttributes.cs similarity index 94% rename from AlphaFS/Filesystem/Native Other/PartitionAttributes.cs rename to AlphaFS/Filesystem/Native Other/EfiPartitionAttributes.cs index 227226052..edba7dd76 100644 --- a/AlphaFS/Filesystem/Native Other/PartitionAttributes.cs +++ b/AlphaFS/Filesystem/Native Other/EfiPartitionAttributes.cs @@ -25,8 +25,9 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { + /// The Extensible Firmware Interface (EFI) partition attributes. [Flags] - public enum PartitionAttributes : ulong + internal enum EfiPartitionAttributes : ulong { /// If this attribute is set, the partition is required by a Computer to function properly. GPT_ATTRIBUTE_PLATFORM_REQUIRED = 0x0000000000000001, diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs index 1626c7bdb..6d0844520 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs @@ -44,7 +44,7 @@ internal struct PARTITION_INFORMATION_GPT /// The Extensible Firmware Interface (EFI) attributes of the partition. [FieldOffset(32)] [MarshalAs(UnmanagedType.U8)] - public readonly PartitionAttributes Attributes; + public readonly EfiPartitionAttributes Attributes; /// A wide-character string that describes the partition. [FieldOffset(40)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs index 798f1efc8..3ae6be3f4 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs @@ -33,8 +33,8 @@ internal static partial class NativeMethods [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct PARTITION_INFORMATION_MBR { - /// The type of partition. For a list of values, see . - [MarshalAs(UnmanagedType.U1)] public readonly DiskPartitionTypes PartitionType; + /// The type of partition. For a list of values, see . + [MarshalAs(UnmanagedType.U1)] public readonly DiskPartitionType PartitionType; /// If the member is TRUE, the partition is a boot partition. When this structure is used with the IOCTL_DISK_SET_PARTITION_INFO_EX control code, the value of this parameter is ignored. [MarshalAs(UnmanagedType.Bool)] public readonly bool BootIndicator; diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs b/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs index ea421c3a0..bd0ea38aa 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs @@ -22,7 +22,7 @@ namespace Alphaleonis.Win32.Filesystem { /// The DETECTION_TYPE enumeration type is used in conjunction with the IOCTL_DISK_GET_DRIVE_GEOMETRY_EX request and the DISK_GEOMETRY_EX structure to determine the type of formatting used by the BIOS to record the disk geometry. - public enum DetectionType : uint + public enum DetectionType { /// Indicates that the disk contains neither an INT 13h partition nor an extended INT 13h partition. DetectNone = 0, diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs index 8e5f714d7..b7bb26be7 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs @@ -250,11 +250,13 @@ public enum DeviceGuid /// The GUID_DEVINTERFACE_WPD device interface class is defined for Windows Portable Devices (WPD). /// Available in Windows Vista, Windows XP, and later versions of Windows. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wpd")] [Description("6AC27878-A6FA-4155-BA85-F98F491D4F33")] Wpd, /// The GUID_DEVINTERFACE_WPD_PRIVATE device interface class is defined for specialized Windows Portable Devices (WPD). /// Available in Windows Vista, Windows XP, and later versions of Windows. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wpd")] [Description("BA0C718F-4DED-49B7-BDD3-FABE28661211")] WpdPrivate diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs b/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs index 532d4fd88..43d7e9a67 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs @@ -22,7 +22,7 @@ using System; #if !NET35 -using System.Threading; + #endif namespace Alphaleonis.Win32.Filesystem diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionTypes.cs b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs similarity index 67% rename from AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionTypes.cs rename to AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs index b1c474da3..6d7f8fec0 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionTypes.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs @@ -19,41 +19,41 @@ * THE SOFTWARE. */ +using System.Diagnostics.CodeAnalysis; + namespace Alphaleonis.Win32.Filesystem { /// The following table identifies the valid partition types that are used by disk drivers. - /// - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// - public enum DiskPartitionTypes : byte + public enum DiskPartitionType { /// An unused entry partition. - UnusedEntry = 0, + EntryUnused = NativeMethods.DiskPartitionType.PARTITION_ENTRY_UNUSED, /// A FAT12 file system partition. - Fat12 = 1, + Fat12 = NativeMethods.DiskPartitionType.PARTITION_FAT_12, /// A XENIX1 partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Xenix")] Xenix1 = 2, /// A XENIX2 partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Xenix")] Xenix2 = 3, /// A FAT16 file system partition. - Fat16 = 4, + Fat16 = NativeMethods.DiskPartitionType.PARTITION_FAT_16, /// An extended partition. - Extended = 5, + Extended = NativeMethods.DiskPartitionType.PARTITION_EXTENDED, /// A huge partition. Huge = 6, /// An IFS (Installable File System) partition. - Ifs = 7, + Ifs = NativeMethods.DiskPartitionType.PARTITION_IFS, /// A FAT32 file system partition. - Fat32 = 11, + Fat32 = NativeMethods.DiskPartitionType.PARTITION_FAT32, /// A FAT32 XINT13 partition. Fat32XInt13 = 12, @@ -68,15 +68,18 @@ public enum DiskPartitionTypes : byte Prep = 65, /// An LDM (Logical Disk Manager) partition. - Ldf = 66, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ldm")] + Ldm = NativeMethods.DiskPartitionType.PARTITION_LDM, /// A UNIX partition. Unix = 99, /// An NTFT partition. - Ntft = 128, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ntft")] + Ntft = NativeMethods.DiskPartitionType.PARTITION_NTFT, /// A valid NTFT partition. - ValidNtft = 192, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ntft")] + ValidNtft = NativeMethods.DiskPartitionType.VALID_NTFT } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionAttributes.cs b/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs similarity index 76% rename from AlphaFS/Filesystem/Structures, Enumerations/PartitionAttributes.cs rename to AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs index 14846976b..d712cecb5 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionAttributes.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs @@ -23,31 +23,31 @@ namespace Alphaleonis.Win32.Filesystem { - /// The different (GPT) partition attributes. + /// The Extensible Firmware Interface (EFI) partition attributes. [Flags] - public enum PartitionAttributes : ulong + public enum EfiPartitionAttributes : ulong { /// None. None = 0, /// If this attribute is set, the partition is required by a Computer to function properly. - PlatformRequired = NativeMethods.PartitionAttributes.GPT_ATTRIBUTE_PLATFORM_REQUIRED, + PlatformRequired = NativeMethods.EfiPartitionAttributes.GPT_ATTRIBUTE_PLATFORM_REQUIRED, /// /// /// - LegacyBIOSBootable = 4, + BiosBoot = 4, /// If this attribute is set, the partition is read-only. - ReadOnly = NativeMethods.PartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY, + ReadOnly = NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY, /// If this attribute is set, the partition is a shadow copy of another partition. - ShadowCopy = NativeMethods.PartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY, + ShadowCopy = NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY, /// If this attribute is set, the partition is not detected by the Mount Manager. - Hidden = NativeMethods.PartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_HIDDEN, + Hidden = NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_HIDDEN, /// If this attribute is set, the partition does not receive a drive letter by default when the disk is moved to another Computer or when the disk is seen for the first time by a Computer. - NoDriveletter = NativeMethods.PartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER + NoDriveLetter = NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs index 8f58b2627..9d82dc8bb 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs @@ -19,6 +19,8 @@ * THE SOFTWARE. */ +using System.Diagnostics.CodeAnalysis; + namespace Alphaleonis.Win32.Filesystem { /// Represents the format of a partition. @@ -29,9 +31,11 @@ namespace Alphaleonis.Win32.Filesystem public enum PartitionStyle { /// Master boot record (MBR) format. This corresponds to standard AT-style MBR partitions. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr")] Mbr = NativeMethods.PARTITION_STYLE.PARTITION_STYLE_MBR, /// GUID Partition Table (GPT) format. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] Gpt = NativeMethods.PARTITION_STYLE.PARTITION_STYLE_GPT, /// Partition not formatted in either of the recognized formats; MBR or GPT. diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs index 065821f8b..48cac1df9 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs @@ -20,6 +20,7 @@ */ using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { @@ -29,7 +30,7 @@ public enum PartitionType /// This value can be set for basic and dynamic disks. /// [Description("00000000-0000-0000-0000-000000000000")] - Unused, + EntryUnused, /// PARTITION_BASIC_DATA_GUID: The data partition type that is created and recognized by Windows. /// @@ -43,24 +44,29 @@ public enum PartitionType /// PARTITION_LDM_DATA_GUID: The partition is an LDM data partition on a dynamic disk. /// This value can be set only for dynamic disks. /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ldm")] [Description("AF9B60A0-1431-4F62-BC68-3311714A69AD")] LdmData, /// PARTITION_LDM_METADATA_GUID: The partition is a Logical Disk Manager (LDM) metadata partition on a dynamic disk. /// This value can be set only for dynamic disks. /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ldm")] [Description("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3")] - LdmMetaData, + LdmMetadata, /// PARTITION_MSFT_RECOVERY_GUID: The partition is a Microsoft recovery partition. /// This value can be set for basic and dynamic disks. /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Msft")] [Description("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC")] MsftRecovery, /// PARTITION_MSFT_RESERVED_GUID: The partition is a Microsoft reserved partition. /// This value can be set for basic and dynamic disks. /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Msft")] + [SuppressMessage("Microsoft.Naming", "CA1700:DoNotNameEnumValuesReserved")] [Description("E3C9E316-0B5C-4DB8-817D-F92DF00215AE")] MsftReserved, @@ -68,6 +74,41 @@ public enum PartitionType /// This value can be set for basic and dynamic disks. /// [Description("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")] - System + System, + + + + + // 2018-02-27 GUID Partition Table + // https://en.wikipedia.org/wiki/GUID_Partition_Table + + + /// IBM General Parallel File System (GPFS) partition. + [Description("37AFFC90-EF7D-4E96-91C3-2D7AE055B174")] + IbmGpfs, + + /// Storage Spaces partition. + [Description("E75CAF8F-F680-4CEE-AFA3-B001E56EFC2D")] + StorageSpace, + + /// MBR partition scheme. + [Description("024DEE41-33E7-11D3-9D69-0008C781F39F")] + MbrScheme, + + /// BIOS boot partition. + [Description("21686148-6449-6E6F-744E-656564454649F")] + BiosBoot, + + /// Intel Fast Flash (iFFS) partition (for Intel Rapid Start technology). + [Description("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593")] + iFfs, + + /// Sony boot partition. + [Description("F4019732-066E-4E12-8273-346C5641494F")] + SonyBoot, + + /// Lenovo boot partition. + [Description("BFBFAFE7-A34F-448A-9A5B-6213EB736C22")] + LenovoBoot, } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs index fb769181d..1cc081192 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs @@ -19,6 +19,8 @@ * THE SOFTWARE. */ +using System.Diagnostics.CodeAnalysis; + namespace Alphaleonis.Win32.Filesystem { /// Provides a symbolic means of representing storage bus types. @@ -28,24 +30,30 @@ public enum StorageBusType Unknown = NativeMethods.STORAGE_BUS_TYPE.BusTypeUnknown, /// Indicates a SCSI bus type. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scsi")] Scsi = NativeMethods.STORAGE_BUS_TYPE.BusTypeScsi, /// Indicates an ATAPI bus type. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Atapi")] Atapi = NativeMethods.STORAGE_BUS_TYPE.BusTypeAtapi, /// Indicates an ATA bus type. Ata = NativeMethods.STORAGE_BUS_TYPE.BusTypeAta, /// Indicates an IEEE 1394 bus type. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ieee")] Ieee1394 = NativeMethods.STORAGE_BUS_TYPE.BusType1394, /// Indicates an SSA bus type. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ssa")] Ssa = NativeMethods.STORAGE_BUS_TYPE.BusTypeSsa, /// Indicates a fiber channel bus type. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fibre")] Fibre = NativeMethods.STORAGE_BUS_TYPE.BusTypeFibre, /// Indicates a USB bus type. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usb")] Usb = NativeMethods.STORAGE_BUS_TYPE.BusTypeUsb, /// Indicates a RAID bus type. @@ -53,22 +61,29 @@ public enum StorageBusType /// Indicates an iSCSI bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scsi")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "i")] iScsi = NativeMethods.STORAGE_BUS_TYPE.BusTypeiScsi, /// Indicates a serial-attached SCSI (SAS) bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sas")] Sas = NativeMethods.STORAGE_BUS_TYPE.BusTypeSas, /// Indicates a SATA bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sata")] Sata = NativeMethods.STORAGE_BUS_TYPE.BusTypeSata, /// Indicates a secure digital (SD) bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sd")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Sd")] Sd = NativeMethods.STORAGE_BUS_TYPE.BusTypeSd, /// Indicates a multimedia card (MMC) bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mmc")] Mmc = NativeMethods.STORAGE_BUS_TYPE.BusTypeMmc, /// Indicates a virtual bus type. diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs index 839d6a90a..58925a49a 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs @@ -19,24 +19,35 @@ * THE SOFTWARE. */ +using System.Diagnostics.CodeAnalysis; + namespace Alphaleonis.Win32.Filesystem { /// Specifies various types of storage media. + [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] public enum StorageMediaType { /// Format is unknown. Unknown = NativeMethods.STORAGE_MEDIA_TYPE.Unknown, /// A 5.25" floppy, with 1.2MB and 512 bytes/sector. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] Floppy51Pt2512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_1Pt2_512, /// A 3.5" floppy, with 1.44MB and 512 bytes/sector. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] Floppy31Pt44512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_1Pt44_512, /// A 3.5" floppy, with 2.88MB and 512 bytes/sector. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] Floppy32Pt88512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_2Pt88_512, /// A 3.5" floppy, with 20.8MB and 512 bytes/sector. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] Floppy320Pt8512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_20Pt8_512, /// A 3.5" floppy, with 720KB and 512 bytes/sector. @@ -76,24 +87,33 @@ public enum StorageMediaType Floppy5720512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_720_512, /// A 3.5" floppy, with 1.2MB and 512 bytes/sector. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] Floppy31Pt2512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_1Pt2_512, /// A 3.5" floppy, with 1.23MB and 1024 bytes/sector. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] Floppy31Pt231024 = NativeMethods.STORAGE_MEDIA_TYPE.F3_1Pt23_1024, /// A 5.25" floppy, with 1.23MB and 1024 bytes/sector. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] Floppy51Pt231024 = NativeMethods.STORAGE_MEDIA_TYPE.F5_1Pt23_1024, /// A 3.5" floppy, with 128MB and 512 bytes/sector. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mb")] Floppy3128Mb512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_128Mb_512, /// A 3.5" floppy, with 230MB and 512 bytes/sector. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mb")] Floppy3230Mb512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_230Mb_512, /// An 8" floppy, with 256KB and 128 bytes/sector. Floppy8256128 = NativeMethods.STORAGE_MEDIA_TYPE.F8_256_128, /// A 3.5" floppy, with 200MB and 512 bytes/sector. (HiFD). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mb")] Floppy3200Mb512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_200Mb_512, /// A 3.5" floppy, with 240MB and 512 bytes/sector. (HiFD). @@ -103,54 +123,82 @@ public enum StorageMediaType Floppy332M512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_32M_512, /// One of the following tape types: DAT, DDS1, DDS2, and so on. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dds")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] Dds4Mm = NativeMethods.STORAGE_MEDIA_TYPE.DDS_4mm, /// MiniQIC tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Qic")] MiniQic = NativeMethods.STORAGE_MEDIA_TYPE.MiniQic, /// Travan tape (TR-1, TR-2, TR-3, and so on). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Travan")] Travan = NativeMethods.STORAGE_MEDIA_TYPE.Travan, /// QIC tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Qic")] Qic = NativeMethods.STORAGE_MEDIA_TYPE.QIC, /// An 8mm Exabyte metal particle tape. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mp")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mp")] Mp8Mm = NativeMethods.STORAGE_MEDIA_TYPE.MP_8mm, /// An 8mm Exabyte advanced metal evaporative tape. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ame")] Ame8Mm = NativeMethods.STORAGE_MEDIA_TYPE.AME_8mm, /// An 8mm Sony AIT1 tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ait")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] Ait18Mm = NativeMethods.STORAGE_MEDIA_TYPE.AIT1_8mm, /// DLT compact tape (IIIxt or IV). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dlt")] Dlt = NativeMethods.STORAGE_MEDIA_TYPE.DLT, /// Philips NCTP tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nctp")] Nctp = NativeMethods.STORAGE_MEDIA_TYPE.NCTP, /// IBM 3480 tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] Ibm3480 = NativeMethods.STORAGE_MEDIA_TYPE.IBM_3480, /// IBM 3490E tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] Ibm3490E = NativeMethods.STORAGE_MEDIA_TYPE.IBM_3490E, /// IBM Magstar 3590 tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Magstar")] IbmMagstar3590 = NativeMethods.STORAGE_MEDIA_TYPE.IBM_Magstar_3590, /// IBM Magstar MP tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Magstar")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mp")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mp")] IbmMagstarMp = NativeMethods.STORAGE_MEDIA_TYPE.IBM_Magstar_MP, /// STK data D3 tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Stk")] StkDataD3 = NativeMethods.STORAGE_MEDIA_TYPE.STK_DATA_D3, /// Sony DTF tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dtf")] SonyDtf = NativeMethods.STORAGE_MEDIA_TYPE.SONY_DTF, /// A 6mm digital videotape. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dv")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dv")] Dv6Mm = NativeMethods.STORAGE_MEDIA_TYPE.DV_6mm, /// Exabyte DMI tape (or compatible). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dmi")] Dmi = NativeMethods.STORAGE_MEDIA_TYPE.DMI, /// Sony D2S or D2L tape. @@ -163,136 +211,213 @@ public enum StorageMediaType CDRom = NativeMethods.STORAGE_MEDIA_TYPE.CD_ROM, /// CD (write once). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Cd")] CdR = NativeMethods.STORAGE_MEDIA_TYPE.CD_R, /// CD (rewriteable). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Cd")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] CdRw = NativeMethods.STORAGE_MEDIA_TYPE.CD_RW, /// DVD. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dvd")] DvdRom = NativeMethods.STORAGE_MEDIA_TYPE.DVD_ROM, /// DVD (write once). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dvd")] DvdR = NativeMethods.STORAGE_MEDIA_TYPE.DVD_R, /// DVD (rewriteable). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dvd")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] DvdRw = NativeMethods.STORAGE_MEDIA_TYPE.DVD_RW, /// Magneto-optical 3.5" (rewriteable). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mo")] Mo3Rw = NativeMethods.STORAGE_MEDIA_TYPE.MO_3_RW, /// Magneto-optical 5.25" (write once). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mo")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] Mo5Wo = NativeMethods.STORAGE_MEDIA_TYPE.MO_5_WO, /// Magneto-optical 5.25" (rewriteable; not LIMDOW). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mo")] Mo5Rw = NativeMethods.STORAGE_MEDIA_TYPE.MO_5_RW, /// Magneto-optical 5.25" (rewriteable; LIMDOW). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Limdow")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mo")] Mo5Limdow = NativeMethods.STORAGE_MEDIA_TYPE.MO_5_LIMDOW, /// Phase change 5.25" (write once). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pc")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] Pc5Wo = NativeMethods.STORAGE_MEDIA_TYPE.PC_5_WO, /// Phase change 5.25" (rewriteable). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pc")] Pc5Rw = NativeMethods.STORAGE_MEDIA_TYPE.PC_5_RW, /// Phase change dual (rewriteable). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pd")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pd")] Pd5Rw = NativeMethods.STORAGE_MEDIA_TYPE.PD_5_RW, /// Ablative 5.25" (write once). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Abl")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] Abl5Wo = NativeMethods.STORAGE_MEDIA_TYPE.ABL_5_WO, /// Pinnacle Apex 4.6GB (rewriteable) + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] PinnacleApex5Rw = NativeMethods.STORAGE_MEDIA_TYPE.PINNACLE_APEX_5_RW, /// Sony 12" (write once). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] Sony12Wo = NativeMethods.STORAGE_MEDIA_TYPE.SONY_12_WO, /// Philips/LMS 12" (write once). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] Philips12Wo = NativeMethods.STORAGE_MEDIA_TYPE.PHILIPS_12_WO, /// Hitachi 12" (write once). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] Hitachi12Wo = NativeMethods.STORAGE_MEDIA_TYPE.HITACHI_12_WO, /// Cygnet/ATG 12" (write once). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] Cygnet12Wo = NativeMethods.STORAGE_MEDIA_TYPE.CYGNET_12_WO, /// Kodak 14" (write once). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] Kodak14Wo = NativeMethods.STORAGE_MEDIA_TYPE.KODAK_14_WO, /// MO near field recording (Terastor). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mo")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nfr")] MoNfr525 = NativeMethods.STORAGE_MEDIA_TYPE.MO_NFR_525, /// Nikon 12" (rewriteable). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] Nikon12Rw = NativeMethods.STORAGE_MEDIA_TYPE.NIKON_12_RW, /// Iomega Zip. IomegaZip = NativeMethods.STORAGE_MEDIA_TYPE.IOMEGA_ZIP, /// Iomega Jaz. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Jaz")] IomegaJaz = NativeMethods.STORAGE_MEDIA_TYPE.IOMEGA_JAZ, /// Syquest EZ135. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ez")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ez")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Syquest")] SyquestEz135 = NativeMethods.STORAGE_MEDIA_TYPE.SYQUEST_EZ135, /// Syquest EzFlyer. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ezflyer")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Syquest")] SyquestEzflyer = NativeMethods.STORAGE_MEDIA_TYPE.SYQUEST_EZFLYER, /// Syquest SyJet. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Syjet")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Syquest")] SyquestSyjet = NativeMethods.STORAGE_MEDIA_TYPE.SYQUEST_SYJET, /// Avatar 2.5" floppy. AvatarF2 = NativeMethods.STORAGE_MEDIA_TYPE.AVATAR_F2, /// An 8mm Hitachi tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mp")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mp")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] Mp28Mm = NativeMethods.STORAGE_MEDIA_TYPE.MP2_8mm, /// Ampex DST small tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dst")] DstS = NativeMethods.STORAGE_MEDIA_TYPE.DST_S, /// Ampex DST medium tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dst")] DstM = NativeMethods.STORAGE_MEDIA_TYPE.DST_M, /// Ampex DST large tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dst")] DstL = NativeMethods.STORAGE_MEDIA_TYPE.DST_L, /// Ecrix 8mm tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vxa")] VxaTape1 = NativeMethods.STORAGE_MEDIA_TYPE.VXATape_1, /// Ecrix 8mm tape. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vxa")] VxaTape2 = NativeMethods.STORAGE_MEDIA_TYPE.VXATape_2, /// STK 9840. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Stk")] Stk9840 = NativeMethods.STORAGE_MEDIA_TYPE.STK_9840, /// LTO Ultrium (IBM, HP, Seagate). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lto")] LtoUltrium = NativeMethods.STORAGE_MEDIA_TYPE.LTO_Ultrium, /// LTO Accelis (IBM, HP, Seagate). + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Accelis")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lto")] LtoAccelis = NativeMethods.STORAGE_MEDIA_TYPE.LTO_Accelis, /// DVD-RAM. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dvd")] DvdRam = NativeMethods.STORAGE_MEDIA_TYPE.DVD_RAM, /// AIT tape (AIT2 or higher). + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ait")] Ait8Mm = NativeMethods.STORAGE_MEDIA_TYPE.AIT_8mm, /// OnStream ADR1. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Adr")] Adr1 = NativeMethods.STORAGE_MEDIA_TYPE.ADR_1, /// OnStream ADR2. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Adr")] Adr2 = NativeMethods.STORAGE_MEDIA_TYPE.ADR_2, /// STK 9940. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Stk")] Stk9940 = NativeMethods.STORAGE_MEDIA_TYPE.STK_9940, /// SAIT tape. /// Windows Server 2003: This is not supported before Windows Server 2003 with SP1. /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sait")] Sait = NativeMethods.STORAGE_MEDIA_TYPE.SAIT, /// Exabyte VXA tape. /// Windows Server 2008: This is not supported before Windows Server 2008. /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vxa")] VxaTape = NativeMethods.STORAGE_MEDIA_TYPE.VXATape } } diff --git a/AlphaFS/GlobalSuppressions.cs b/AlphaFS/GlobalSuppressions.cs index 3c8c3f175..750ddece7 100644 --- a/AlphaFS/GlobalSuppressions.cs +++ b/AlphaFS/GlobalSuppressions.cs @@ -42,3 +42,5 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.NotSameDeviceException.#.cctor()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "Dir", Scope = "resource", Target = "Alphaleonis.Win32.Resources.resources")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Filesystem.NativeMethods+PARTITION_INFORMATION_GPT")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Filesystem.NativeMethods+PARTITION_INFORMATION_EX")] diff --git a/AlphaFS/Network/NetworkInfo.cs b/AlphaFS/Network/NetworkInfo.cs index eccd8ef5c..ecf32e083 100644 --- a/AlphaFS/Network/NetworkInfo.cs +++ b/AlphaFS/Network/NetworkInfo.cs @@ -23,7 +23,6 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Net.NetworkInformation; namespace Alphaleonis.Win32.Network { diff --git a/AlphaFS/Security/Native Methods/NativeMethods.GetTokenInformation.cs b/AlphaFS/Security/Native Methods/NativeMethods.GetTokenInformation.cs index 245e74526..1b95b3c46 100644 --- a/AlphaFS/Security/Native Methods/NativeMethods.GetTokenInformation.cs +++ b/AlphaFS/Security/Native Methods/NativeMethods.GetTokenInformation.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; @@ -33,8 +34,9 @@ internal static partial class NativeMethods /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [SuppressUnmanagedCodeSecurity] + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetTokenInformation(SafeTokenHandle tokenHandle, [MarshalAs(UnmanagedType.U4)] TOKEN_INFORMATION_CLASS tokenInformationClass, SafeGlobalMemoryBufferHandle tokenInformation, [MarshalAs(UnmanagedType.U4)] uint tokenInformationLength, [MarshalAs(UnmanagedType.U4)] out uint returnLength); } diff --git a/AlphaFS/Security/Native Methods/NativeMethods.OpenProcessToken.cs b/AlphaFS/Security/Native Methods/NativeMethods.OpenProcessToken.cs index a304459e9..9d373b6cf 100644 --- a/AlphaFS/Security/Native Methods/NativeMethods.OpenProcessToken.cs +++ b/AlphaFS/Security/Native Methods/NativeMethods.OpenProcessToken.cs @@ -20,6 +20,7 @@ */ using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; @@ -34,8 +35,9 @@ internal static partial class NativeMethods /// /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [SuppressUnmanagedCodeSecurity] + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool OpenProcessToken(IntPtr processHandle, [MarshalAs(UnmanagedType.U4)] TOKEN desiredAccess, out SafeTokenHandle tokenHandle); } diff --git a/AlphaFS/Utils.cs b/AlphaFS/Utils.cs index 6f273a6af..db4ff0759 100644 --- a/AlphaFS/Utils.cs +++ b/AlphaFS/Utils.cs @@ -46,6 +46,7 @@ public static string GetEnumDescription(Enum enumValue) } + [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public static T[] EnumToArray() { var enumType = typeof(T); From 779560da1a16bcb43a0fd08357e81c3c2a269511 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 27 Feb 2018 21:23:37 +0100 Subject: [PATCH 058/133] -Fixed enum EfiPartitionAttributes; -Fixed more compiler warnings; --- .../AlphaFS_DeviceTest.cs | 37 --- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 - AlphaFS/AlphaFS.csproj | 3 +- .../Device.GetPhysicalDriveInfo.cs | 4 +- .../Device.GetStorageAdapterInfo.cs | 2 +- .../Device.GetStorageDeviceInfo.cs | 2 +- AlphaFS/Device/StorageGptPartitionInfo.cs | 36 +-- AlphaFS/Device/StoragePartitionInfo.cs | 4 +- AlphaFS/Device/Test.cs | 2 +- AlphaFS/Device/Test2.cs | 252 ------------------ .../Native Other/PARTITION_INFORMATION_GPT.cs | 5 +- .../DirectoryEnumerationFilters.cs | 2 +- .../EfiPartitionAttributes.cs | 23 +- .../PartitionType..cs | 6 + 14 files changed, 51 insertions(+), 328 deletions(-) delete mode 100644 AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs delete mode 100644 AlphaFS/Device/Test2.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs deleted file mode 100644 index 2eab23efe..000000000 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_DeviceTest.cs +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace AlphaFS.UnitTest -{ - public partial class AlphaFS_PhysicalDriveInfoTest - { - [TestMethod] - public void Device_Test() - { - //var hw = new Hardware(); - - //IOCtl.Main(); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index cd31c5e31..856e41307 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -159,7 +159,6 @@ - diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 176a6fab9..31baf49ff 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -221,7 +221,6 @@ - @@ -711,7 +710,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs index d3da090fb..4eedcffce 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs @@ -41,7 +41,7 @@ public static partial class Device /// /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string such as: "\\?\pcistor#disk&...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// [SecurityCritical] public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) @@ -99,7 +99,7 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string such as: "\\?\pcistor#disk&...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// /// A instance. /// A instance. diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs index e71ceeb25..28133d87e 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs @@ -40,7 +40,7 @@ public static partial class Device /// /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string such as: "\\?\pcistor#disk&...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) { diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs index 83521bec3..6287e7be8 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs @@ -40,7 +40,7 @@ public static partial class Device /// /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string such as: "\\?\pcistor#disk&...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { diff --git a/AlphaFS/Device/StorageGptPartitionInfo.cs b/AlphaFS/Device/StorageGptPartitionInfo.cs index 1ddccca8e..f67dae49c 100644 --- a/AlphaFS/Device/StorageGptPartitionInfo.cs +++ b/AlphaFS/Device/StorageGptPartitionInfo.cs @@ -35,7 +35,6 @@ public sealed class StorageGptPartitionInfo private ulong _partitionLength; private ulong _startingOffset; - private static PartitionType[] _partitionTypes; #endregion // Private Fields @@ -45,14 +44,11 @@ public sealed class StorageGptPartitionInfo /// Initializes a StorageGptPartitionInfo instance. public StorageGptPartitionInfo() { - if (null == _partitionTypes) - _partitionTypes = Utils.EnumToArray(); - PartitionNumber = -1; } - - internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partition) : this() + + internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partition, PartitionType[] partitionTypes) : this() { _partitionLength = partition.PartitionLength; @@ -61,23 +57,34 @@ internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio PartitionNumber = (int) partition.PartitionNumber; RewritePartition = partition.RewritePartition; - - - var gptPartition = partition.Gpt; - Attributes = (EfiPartitionAttributes) gptPartition.Attributes; - - - Description = gptPartition.Name.Trim(); PartitionId = gptPartition.PartitionId; - foreach (var guid in _partitionTypes) + var attrs = gptPartition.Attributes; + + if ((attrs & NativeMethods.EfiPartitionAttributes.GPT_ATTRIBUTE_PLATFORM_REQUIRED) != 0) + Attributes |= EfiPartitionAttributes.PlatformRequired; + + if ((attrs & NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY) != 0) + Attributes |= EfiPartitionAttributes.ReadOnly; + + if ((attrs & NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY) != 0) + Attributes |= EfiPartitionAttributes.ShadowCopy; + + if ((attrs & NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_HIDDEN) != 0) + Attributes |= EfiPartitionAttributes.Hidden; + + if ((attrs & NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER) != 0) + Attributes |= EfiPartitionAttributes.NoDriveLetter; + + + foreach (var guid in partitionTypes) if (gptPartition.PartitionType.Equals(new Guid(Utils.GetEnumDescription(guid)))) { PartitionType = guid; @@ -90,7 +97,6 @@ internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio #region Properties - /// The Extensible Firmware Interface (EFI) attributes of the partition. public EfiPartitionAttributes Attributes { get; internal set; } diff --git a/AlphaFS/Device/StoragePartitionInfo.cs b/AlphaFS/Device/StoragePartitionInfo.cs index ee30ed024..cebaeb02e 100644 --- a/AlphaFS/Device/StoragePartitionInfo.cs +++ b/AlphaFS/Device/StoragePartitionInfo.cs @@ -77,8 +77,10 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods GptPartitionInfo = new Collection(); + var partitionTypes = Utils.EnumToArray(); + for (var i = 0; i <= PartitionCount - 1; i++) - GptPartitionInfo.Add(new StorageGptPartitionInfo(partitions[i])); + GptPartitionInfo.Add(new StorageGptPartitionInfo(partitions[i], partitionTypes)); break; diff --git a/AlphaFS/Device/Test.cs b/AlphaFS/Device/Test.cs index 0d008c4da..9cb219398 100644 --- a/AlphaFS/Device/Test.cs +++ b/AlphaFS/Device/Test.cs @@ -1,4 +1,4 @@ -///* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +//* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov // * // * Permission is hereby granted, free of charge, to any person obtaining a copy // * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Test2.cs b/AlphaFS/Device/Test2.cs deleted file mode 100644 index f3ed4fa1c..000000000 --- a/AlphaFS/Device/Test2.cs +++ /dev/null @@ -1,252 +0,0 @@ -////using Microsoft.VisualBasic; - -//using System; -//using System.ComponentModel; -//using System.Runtime.InteropServices; -//using System.Security; -//using Microsoft.Win32.SafeHandles; - -//namespace Alphaleonis.Win32.Filesystem -//{ -// internal static class IOCtl -// { -// private const int GENERIC_READ = unchecked((int) 0x80000000); -// private const int FILE_SHARE_READ = 1; -// private const int FILE_SHARE_WRITE = 2; -// private const int OPEN_EXISTING = 3; - -// //private enum Partition : byte -// //{ -// // ENTRY_UNUSED = 0, -// // FAT_12 = 1, -// // XENIX_1 = 2, -// // XENIX_2 = 3, -// // FAT_16 = 4, -// // EXTENDED = 5, -// // HUGE = 6, -// // IFS = 7, -// // OS2BOOTMGR = 0xa, -// // FAT32 = 0xb, -// // FAT32_XINT13 = 0xc, -// // XINT13 = 0xe, -// // XINT13_EXTENDED = 0xf, -// // PREP = 0x41, -// // LDM = 0x42, -// // UNIX = 0x63 -// //} - -// [SuppressUnmanagedCodeSecurity] -// private class NativeMethods -// { - -// [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] -// internal static extern SafeFileHandle CreateFile( -// string fileName, -// int desiredAccess, -// int shareMode, -// IntPtr securityAttributes, -// int creationDisposition, -// int flagsAndAttributes, -// IntPtr hTemplateFile); - -// [DllImport("kernel32", SetLastError = true)] -// [return: MarshalAs(UnmanagedType.Bool)] -// internal static extern bool DeviceIoControl( -// SafeFileHandle hVol, -// Filesystem.NativeMethods.IoControlCode controlCode, -// IntPtr inBuffer, -// uint inBufferSize, -// IntPtr outBuffer, -// uint outBufferSize, -// ref uint bytesReturned, -// IntPtr overlapped); - -// } - - - - - - - - -// internal static void Main() -// { -// SendIoCtlDiskGetDriveLayoutEx(0); -// SendIoCtlDiskGetDriveLayoutEx(1); -// //SendIoCtlDiskGetDriveLayoutEx(2); -// } - - -// private static void SendIoCtlDiskGetDriveLayoutEx(int PhysicalDrive) -// { - -// var lie = default(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX); - -// Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies = null; - -// using (var hDevice = NativeMethods.CreateFile("\\\\.\\PHYSICALDRIVE" + PhysicalDrive, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero)) -// { -// if (hDevice.IsInvalid) -// throw new Win32Exception(); - - -// // We don't know how many partitions there are, so we have to use a blob of memory... -// var numPartitions = 1; -// var done = false; - -// do -// { -// // 48 = the number of bytes in DRIVE_LAYOUT_INFORMATION_EX up to -// // the first PARTITION_INFORMATION_EX in the array. -// // And each PARTITION_INFORMATION_EX is 144 bytes. -// var outBufferSize = 48 + numPartitions * 144; -// var blob = default(IntPtr); -// uint bytesReturned = 0; - -// try -// { -// blob = Marshal.AllocHGlobal(outBufferSize); - -// var result = NativeMethods.DeviceIoControl(hDevice, Filesystem.NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, blob, (uint) outBufferSize, ref bytesReturned, IntPtr.Zero); - -// // We expect that we might not have enough room in the output buffer. -// if (result == false) -// { -// // If the buffer wasn't too small, then something else went wrong. -// if (Marshal.GetLastWin32Error() != Win32Errors.ERROR_INSUFFICIENT_BUFFER) -// throw new Win32Exception(); -// // We need more space on the next loop. -// numPartitions += 1; -// } -// else -// { -// // We got the size right, so stop looping. -// done = true; - -// // Do something with the data here - we'll free the memory before we leave the loop. -// // First we grab the DRIVE_LAYOUT_INFORMATION_EX, it's at the start of the blob of memory: -// lie = (Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX) Marshal.PtrToStructure(blob, typeof(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); - -// // Then loop and add the PARTITION_INFORMATION_EX structures to an array. -// pies = new Filesystem.NativeMethods.PARTITION_INFORMATION_EX[lie.PartitionCount]; - -// for (var i = 0; i <= lie.PartitionCount - 1; i++) -// { -// // Where is this structure in the blob of memory? -// var offset = new IntPtr(blob.ToInt64() + 48 + i * 144); - -// pies[i] = (Filesystem.NativeMethods.PARTITION_INFORMATION_EX) Marshal.PtrToStructure(offset, typeof(Filesystem.NativeMethods.PARTITION_INFORMATION_EX)); -// } -// } -// } -// finally -// { -// Marshal.FreeHGlobal(blob); -// } -// } while (!done); -// } - - -// DumpInfo(lie, pies); -// } - - -// private static bool IsPart0Aligned(Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies) -// { -// try -// { -// return pies[0].StartingOffset % 4096 == 0; -// } -// catch -// { -// return false; -// } -// } - - -// private static void DumpInfo(Filesystem.NativeMethods.DRIVE_LAYOUT_INFORMATION_EX lie, Filesystem.NativeMethods.PARTITION_INFORMATION_EX[] pies) -// { -// //var aaa = new PartitionTypeGuid(PartitionType.LdmMetaDataGuid); - - -// Console.WriteLine("\n\nPart 0 aligned:" + IsPart0Aligned(pies)); - - -// Console.WriteLine("Partition Style: {0}", lie.PartitionStyle); -// Console.WriteLine("Partition Count: {0}", lie.PartitionCount); - -// switch (lie.PartitionStyle) -// { -// case PartitionStyle.Mbr: -// Console.WriteLine("Mbr Signature: {0}", lie.Mbr.Signature); -// break; -// case PartitionStyle.Gpt: -// Console.WriteLine("Gpt DiskId : {0}", lie.Gpt.DiskId); -// Console.WriteLine("Gpt StartingUsableOffset: {0}", lie.Gpt.StartingUsableOffset); -// Console.WriteLine("Gpt UsableLength : {0}", lie.Gpt.UsableLength); -// Console.WriteLine("Gpt UsableLength : {0}", Utils.UnitSizeToText(lie.Gpt.UsableLength)); -// Console.WriteLine("Gpt MaxPartitionCount : {0}", lie.Gpt.MaxPartitionCount); -// break; - -// default: -// Console.WriteLine("RAW!"); -// break; -// } - - - - -// for (var i = 0; i <= lie.PartitionCount - 1; i++) -// { -// var storagePartitionInfo = new StoragePartitionInfo(); - -// Console.WriteLine(); -// Console.WriteLine(); -// Console.WriteLine("Partition {0} info...", i + 1); -// Console.WriteLine("-------------------"); - - -// var _with1 = pies[i]; -// Console.WriteLine("Partition style : {0}", (PartitionStyle) _with1.PartitionStyle); -// Console.WriteLine("Starting offset : {0}", _with1.StartingOffset); -// Console.WriteLine("Partition length : {0}", _with1.PartitionLength); -// Console.WriteLine("Partition length : {0}", Utils.UnitSizeToText(_with1.PartitionLength)); -// Console.WriteLine("Partition number : {0}", _with1.PartitionNumber); -// Console.WriteLine("Rewrite partition: {0}", _with1.RewritePartition); - - -// switch ((PartitionStyle) _with1.PartitionStyle) -// { -// case PartitionStyle.Mbr: -// var _with2 = _with1.Mbr; -// Console.WriteLine("Mbr PartitionType - raw value: {0}", _with2.PartitionType); - -// //Console.WriteLine("Mbr PartitionType - validNTFT: {0}", _with2.IsValidNTFT()); - -// //if (_with2.IsValidNTFT()) -// // Console.WriteLine("Mbr PartitionType - ntft: {0}", _with2.IsNTFT()); - -// //Console.WriteLine("Mbr PartitionType - decoded: {0}", _with2.GetPartition()); - -// Console.WriteLine("Mbr BootIndicator : {0}", _with2.BootIndicator); -// Console.WriteLine("Mbr RecognizedPartition: {0}", _with2.RecognizedPartition); -// Console.WriteLine("Mbr HiddenSectors : {0}", _with2.HiddenSectors); -// break; - -// case PartitionStyle.Gpt: -// var _with3 = _with1.Gpt; -// Console.WriteLine("Gpt PartitionType: {0}", _with3.PartitionType); -// Console.WriteLine("Gpt PartitionId : {0}", _with3.PartitionId); -// Console.WriteLine("Gpt Attributes : {0}", (PartitionAttributes) _with3.Attributes); -// Console.WriteLine("Gpt Name : {0}", _with3.Name); -// break; - -// case PartitionStyle.Raw: -// Console.WriteLine("RAW!"); -// break; -// } -// } -// } -// } -//} diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs index 6d0844520..771fe75fd 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs @@ -26,11 +26,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Contains GUID partition table (GPT) partition information. - /// + /// Contains GUID partition table (GPT) partition information. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] internal struct PARTITION_INFORMATION_GPT { diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs b/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs index 43d7e9a67..532d4fd88 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs @@ -22,7 +22,7 @@ using System; #if !NET35 - +using System.Threading; #endif namespace Alphaleonis.Win32.Filesystem diff --git a/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs b/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs index d712cecb5..bb8ea42d9 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs @@ -20,34 +20,35 @@ */ using System; +using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { /// The Extensible Firmware Interface (EFI) partition attributes. + [SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Efi")] [Flags] - public enum EfiPartitionAttributes : ulong + public enum EfiPartitionAttributes { /// None. None = 0, - /// If this attribute is set, the partition is required by a Computer to function properly. - PlatformRequired = NativeMethods.EfiPartitionAttributes.GPT_ATTRIBUTE_PLATFORM_REQUIRED, - - /// - /// - /// + /// If this attribute is set, the partition is an MBR partition. BiosBoot = 4, + /// If this attribute is set, the partition is required by a Computer to function properly. + PlatformRequired, + /// If this attribute is set, the partition is read-only. - ReadOnly = NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY, + ReadOnly, /// If this attribute is set, the partition is a shadow copy of another partition. - ShadowCopy = NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY, + ShadowCopy, /// If this attribute is set, the partition is not detected by the Mount Manager. - Hidden = NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_HIDDEN, + Hidden, /// If this attribute is set, the partition does not receive a drive letter by default when the disk is moved to another Computer or when the disk is seen for the first time by a Computer. - NoDriveLetter = NativeMethods.EfiPartitionAttributes.GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER + NoDriveLetter } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs index 48cac1df9..01644de28 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs @@ -24,6 +24,7 @@ namespace Alphaleonis.Win32.Filesystem { + /// Specifies the different types of partition GUIDs. public enum PartitionType { /// PARTITION_ENTRY_UNUSED_GUID: There is no partition. @@ -84,6 +85,8 @@ public enum PartitionType /// IBM General Parallel File System (GPFS) partition. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpfs")] [Description("37AFFC90-EF7D-4E96-91C3-2D7AE055B174")] IbmGpfs, @@ -92,6 +95,7 @@ public enum PartitionType StorageSpace, /// MBR partition scheme. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr")] [Description("024DEE41-33E7-11D3-9D69-0008C781F39F")] MbrScheme, @@ -100,6 +104,8 @@ public enum PartitionType BiosBoot, /// Intel Fast Flash (iFFS) partition (for Intel Rapid Start technology). + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ffs")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "i")] [Description("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593")] iFfs, From 4df4cc3eeb980fa8dec0bcd3349e5e55b34d0c7e Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 27 Feb 2018 22:48:55 +0100 Subject: [PATCH 059/133] Code improvement, work in progress. --- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 1 + .../Device.CreateDirectoryJunction.cs | 2 + .../Device.GetStoragePartitionInfo.cs | 184 ++++++------------ AlphaFS/Device/StorageGptPartitionInfo.cs | 10 +- AlphaFS/Device/StoragePartitionInfo.cs | 2 +- .../EfiPartitionAttributes.cs | 6 +- 6 files changed, 76 insertions(+), 129 deletions(-) diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index 5e93b4d81..ba73460b3 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -27,6 +27,7 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { + /// Retrieves the physical location of a specified volume on one or more disks. private static NativeMethods.VOLUME_DISK_EXTENTS? GetVolumeDiskExtents(SafeFileHandle safeHandle) { NativeMethods.VOLUME_DISK_EXTENTS? structure; diff --git a/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs b/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs index d21d66c3a..8c5852de9 100644 --- a/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs +++ b/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs @@ -21,11 +21,13 @@ using Microsoft.Win32.SafeHandles; using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; namespace Alphaleonis.Win32.Filesystem { + [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public static partial class Device { /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs index ce5f45973..19214a661 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; @@ -118,175 +119,110 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle } - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeHandle, string pathToDevice) - { - SafeFileHandle safeHandleRetry = null; - var isRetry = false; + private static StoragePartitionInfo GetStoragePartitionInfoNative0(SafeFileHandle safeHandle, string pathForException) + { + var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 + var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 + var partitionCount = 1; - StartGetData: + var bufferSize = driveStructureSize + partitionCount * partitionStructureSize; - using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, 0, pathToDevice, NativeMethods.DefaultFileBufferSize / 8)) - { - if (null == safeBuffer) + while (true) + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) { - // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var lastError = Marshal.GetLastWin32Error(); - var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); - if (volDiskExtents.HasValue) + if (success) { - // Use the first disk extent. - - pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); + var drive = safeBuffer.PtrToStructure(0); + var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; - safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); - - isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; - } - - - if (isRetry) - goto StartGetData; - - //return null; - return new NativeMethods.DISK_GEOMETRY_EX(); - } + for (partitionCount = 0; partitionCount <= drive.PartitionCount - 1; partitionCount++) - var typeOf = typeof(NativeMethods.DISK_GEOMETRY); - var sizeOf = Marshal.SizeOf(typeOf); + partitions[partitionCount] = safeBuffer.PtrToStructure(driveStructureSize + partitionCount * partitionStructureSize); - var diskGeometryEx = new NativeMethods.DISK_GEOMETRY_EX - { - Geometry = safeBuffer.PtrToStructure(), - DiskSize = safeBuffer.ReadInt64(sizeOf) - }; + var disk = GetDiskGeometryExNative(safeHandle, pathForException); + return new StoragePartitionInfo(disk, drive, partitions); + } - var offset = sizeOf + sizeof(long); // 32 - diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure(offset); + if (lastError == Win32Errors.ERROR_NOT_READY || + // Dynamic disk. + lastError == Win32Errors.ERROR_INVALID_FUNCTION || - offset += (int)diskGeometryEx.PartitionInformation.SizeOfPartitionInfo; + // Request device number from a DeviceGuid.Image device. + lastError == Win32Errors.ERROR_NOT_SUPPORTED) - diskGeometryEx.DiskDetectionInfo = safeBuffer.PtrToStructure(offset); + return null; - return diskGeometryEx; - } + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + } } + /// Gets the disk geometry extended information + private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeHandle, string pathForException) + { + var bufferSize = 128; - //private static StoragePartitionInfo GetStoragePartitionInfoNative0(SafeFileHandle safeHandle, string pathForException) - //{ - // var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 - // var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 - // var partitionCount = 1; - - // var bufferSize = driveStructureSize + partitionCount * partitionStructureSize; - - // while (true) - // using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) - // { - // var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); - - // var lastError = Marshal.GetLastWin32Error(); - - - // if (success) - // { - // var drive = safeBuffer.PtrToStructure(0); - - // var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; - - - // for (partitionCount = 0; partitionCount <= drive.PartitionCount - 1; partitionCount++) - - // partitions[partitionCount] = safeBuffer.PtrToStructure(driveStructureSize + partitionCount * partitionStructureSize); - - - // var disk = GetDiskGeometryExNative(safeHandle, pathForException); - - // return new StoragePartitionInfo(disk, drive, partitions); - // } - - - // if (lastError == Win32Errors.ERROR_NOT_READY || - - // // Dynamic disk. - // lastError == Win32Errors.ERROR_INVALID_FUNCTION || - - // // Request device number from a DeviceGuid.Image device. - // lastError == Win32Errors.ERROR_NOT_SUPPORTED) - - // return null; - - - // bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); - // } - //} - - - ///// Gets the disk geometry extended information - //private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative0(SafeFileHandle safeHandle, string pathForException) - //{ - // var bufferSize = 128; - - // while (true) - // using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) - // { - // var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + while (true) + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) + { + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); - // var lastError = Marshal.GetLastWin32Error(); + var lastError = Marshal.GetLastWin32Error(); - // if (success) - // { - // var typeOf = typeof(NativeMethods.DISK_GEOMETRY); - // var sizeOf = Marshal.SizeOf(typeOf); + if (success) + { + var typeOf = typeof(NativeMethods.DISK_GEOMETRY); + var sizeOf = Marshal.SizeOf(typeOf); - // var diskGeometryEx = new NativeMethods.DISK_GEOMETRY_EX - // { - // Geometry = safeBuffer.PtrToStructure(), + var diskGeometryEx = new NativeMethods.DISK_GEOMETRY_EX + { + Geometry = safeBuffer.PtrToStructure(), - // DiskSize = safeBuffer.ReadInt64(sizeOf) - // }; + DiskSize = safeBuffer.ReadInt64(sizeOf) + }; - // var offset = sizeOf + sizeof(long); // 32 + var offset = sizeOf + sizeof(long); // 32 - // diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure(offset); + diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure(offset); - // offset += (int) diskGeometryEx.PartitionInformation.SizeOfPartitionInfo; + offset += (int)diskGeometryEx.PartitionInformation.SizeOfPartitionInfo; - // diskGeometryEx.DiskDetectionInfo = safeBuffer.PtrToStructure(offset); + diskGeometryEx.DiskDetectionInfo = safeBuffer.PtrToStructure(offset); - // return diskGeometryEx; - // } + return diskGeometryEx; + } - // if (lastError == Win32Errors.ERROR_NOT_READY || + if (lastError == Win32Errors.ERROR_NOT_READY || - // // Dynamic disk. - // lastError == Win32Errors.ERROR_INVALID_FUNCTION || + // Dynamic disk. + lastError == Win32Errors.ERROR_INVALID_FUNCTION || - // // Request device number from a DeviceGuid.Image device. - // lastError == Win32Errors.ERROR_NOT_SUPPORTED) + // Request device number from a DeviceGuid.Image device. + lastError == Win32Errors.ERROR_NOT_SUPPORTED) - // return new NativeMethods.DISK_GEOMETRY_EX(); + return new NativeMethods.DISK_GEOMETRY_EX(); - // bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); - // } - //} + bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + } + } } } diff --git a/AlphaFS/Device/StorageGptPartitionInfo.cs b/AlphaFS/Device/StorageGptPartitionInfo.cs index f67dae49c..98034e5aa 100644 --- a/AlphaFS/Device/StorageGptPartitionInfo.cs +++ b/AlphaFS/Device/StorageGptPartitionInfo.cs @@ -66,6 +66,10 @@ internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio PartitionId = gptPartition.PartitionId; + + + // Convert the native enum since it is of type ulong. + var attrs = gptPartition.Attributes; if ((attrs & NativeMethods.EfiPartitionAttributes.GPT_ATTRIBUTE_PLATFORM_REQUIRED) != 0) @@ -84,8 +88,12 @@ internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio Attributes |= EfiPartitionAttributes.NoDriveLetter; + + + var partitionType = gptPartition.PartitionType.ToString(); + foreach (var guid in partitionTypes) - if (gptPartition.PartitionType.Equals(new Guid(Utils.GetEnumDescription(guid)))) + if (partitionType.Equals(Utils.GetEnumDescription(guid), StringComparison.OrdinalIgnoreCase)) { PartitionType = guid; break; diff --git a/AlphaFS/Device/StoragePartitionInfo.cs b/AlphaFS/Device/StoragePartitionInfo.cs index cebaeb02e..0ab12959e 100644 --- a/AlphaFS/Device/StoragePartitionInfo.cs +++ b/AlphaFS/Device/StoragePartitionInfo.cs @@ -58,7 +58,7 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods GptDiskId = disk.PartitionInformation.DiskId; MediaType = (StorageMediaType) disk.Geometry.MediaType; - + PartitionStyle = (PartitionStyle) disk.PartitionInformation.PartitionStyle; TotalSize = disk.DiskSize; diff --git a/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs b/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs index bb8ea42d9..0b496c14f 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs @@ -33,12 +33,12 @@ public enum EfiPartitionAttributes /// None. None = 0, - /// If this attribute is set, the partition is an MBR partition. - BiosBoot = 4, - /// If this attribute is set, the partition is required by a Computer to function properly. PlatformRequired, + /// If this attribute is set, the partition is an MBR partition. + BiosBoot = 4, + /// If this attribute is set, the partition is read-only. ReadOnly, From 3e077bc95a7bc643e4aa2fa7a52c3f70056d45af Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 27 Feb 2018 23:43:27 +0100 Subject: [PATCH 060/133] Renamed PhysicalDrive to PhysicalDisk. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs} | 20 +-- ...ice.GetPhysicalDiskInfo_FromDevicePath.cs} | 28 +-- ...e.GetPhysicalDiskInfo_FromLogicalDrive.cs} | 22 +-- ..._Device.GetPhysicalDiskInfo_FromVolume.cs} | 22 +-- ....GetStorageAdapterInfo_FromLogicalDrive.cs | 2 +- ...e.GetStorageDeviceInfo_FromLogicalDrive.cs | 2 +- ...etStoragePartitionInfo_FromLogicalDrive.cs | 2 +- .../AlphaFS_PhysicalDiskInfoTest.cs} | 4 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 16 +- AlphaFS/AlphaFS.csproj | 12 +- AlphaFS/Device/Device.OpenPhysicalDrive.cs | 7 +- .../Device.EnumeratePhysicalDisks.cs | 159 ++++++++++++++++++ .../Device.GetPhysicalDiskInfo.cs} | 52 +++--- .../Device.GetStorageAdapterInfo.cs | 5 +- .../Device.GetStorageDeviceInfo.cs | 9 +- .../Device.GetStoragePartitionInfo.cs | 4 +- .../PhysicalDiskInfo.cs} | 36 ++-- .../Device.EnumeratePhysicalDrives.cs | 159 ------------------ AlphaFS/Device/StorageDeviceInfo.cs | 16 +- .../Filesystem/Path Class/Path.Constants.cs | 2 +- 20 files changed, 292 insertions(+), 287 deletions(-) rename AlphaFS.UnitTest/{AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs => AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs} (65%) rename AlphaFS.UnitTest/{AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs => AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs} (67%) rename AlphaFS.UnitTest/{AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs => AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs} (71%) rename AlphaFS.UnitTest/{AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs => AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs} (73%) rename AlphaFS.UnitTest/{AlphaFS PhysicalDrive Class => AlphaFS PhysicalDisk Class}/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs (97%) rename AlphaFS.UnitTest/{AlphaFS PhysicalDrive Class => AlphaFS PhysicalDisk Class}/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs (97%) rename AlphaFS.UnitTest/{AlphaFS PhysicalDrive Class => AlphaFS PhysicalDisk Class}/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs (98%) rename AlphaFS.UnitTest/{AlphaFS PhysicalDrive Class/AlphaFS_PhysicalDriveInfoTest.cs => AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs} (87%) create mode 100644 AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs rename AlphaFS/Device/{PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs => PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs} (63%) rename AlphaFS/Device/{PhysicalDriveInfo => PhysicalDiskInfo}/Device.GetStorageAdapterInfo.cs (96%) rename AlphaFS/Device/{PhysicalDriveInfo => PhysicalDiskInfo}/Device.GetStorageDeviceInfo.cs (95%) rename AlphaFS/Device/{PhysicalDriveInfo => PhysicalDiskInfo}/Device.GetStoragePartitionInfo.cs (97%) rename AlphaFS/Device/{PhysicalDriveInfo/PhysicalDriveInfo.cs => PhysicalDiskInfo/PhysicalDiskInfo.cs} (86%) delete mode 100644 AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs similarity index 65% rename from AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index 3ff615692..6c921db77 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.EnumeratePhysicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -25,38 +25,38 @@ namespace AlphaFS.UnitTest { - public partial class AlphaFS_PhysicalDriveInfoTest + public partial class AlphaFS_PhysicalDiskInfoTest { // Pattern: ___ [TestMethod] - public void AlphaFS_Device_EnumeratePhysicalDrives_Local_Success() + public void AlphaFS_Device_EnumeratePhysicalDisks_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); var pDriveCount = 0; - var pDrives = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDrives().OrderBy(pDriveInfo => pDriveInfo.StorageDeviceInfo.DeviceNumber).ThenBy(pDriveInfo => pDriveInfo.StorageDeviceInfo.PartitionNumber).ToArray(); + var pDrives = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDisks().OrderBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber).ThenBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.PartitionNumber).ToArray(); - foreach (var pDrive in pDrives) + foreach (var pDisk in pDrives) { Console.WriteLine(); - Console.WriteLine("#{0:000}\tPhysical Drive: [{1}]\t\t{2}\t\t{3}", ++pDriveCount, pDrive.StorageDeviceInfo.DeviceNumber, pDrive.StorageAdapterInfo.ToString(), pDrive.StorageDeviceInfo.ToString()); + Console.WriteLine("#{0:000}\tPhysical Disk: [{1}]\t\t{2}\t\t{3}", ++pDriveCount, pDisk.StorageDeviceInfo.DeviceNumber, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); - UnitTestConstants.Dump(pDrive, -24); + UnitTestConstants.Dump(pDisk, -24); - UnitTestConstants.Dump(pDrive.StorageAdapterInfo, -28, true); + UnitTestConstants.Dump(pDisk.StorageAdapterInfo, -28, true); - UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -17, true); + UnitTestConstants.Dump(pDisk.StorageDeviceInfo, -17, true); - UnitTestConstants.Dump(pDrive.StoragePartitionInfo, -17, true); + UnitTestConstants.Dump(pDisk.StoragePartitionInfo, -17, true); Console.WriteLine(); } - Assert.IsTrue(pDrives.Length > 0, "No physical drives enumerated, but it is expected."); + Assert.IsTrue(pDrives.Length > 0, "No physical disks enumerated, but it is expected."); } } } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs similarity index 67% rename from AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs index 70e1a8533..c975853c1 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromDevicePath.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs @@ -24,13 +24,13 @@ namespace AlphaFS.UnitTest { - public partial class AlphaFS_PhysicalDriveInfoTest + public partial class AlphaFS_PhysicalDiskInfoTest { // Pattern: ___ [TestMethod] - public void AlphaFS_Device_GetPhysicalDriveInfo_FromDevicePath_Success() + public void AlphaFS_Device_GetPhysicalDiskInfo_FromDevicePath_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -39,35 +39,35 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromDevicePath_Success() var sourceDrive = UnitTestConstants.SysDrive; var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - var devicePath = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceDrive).DevicePath; + var devicePath = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDiskInfo(sourceDrive).DevicePath; - var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(devicePath); + var pDisk = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDiskInfo(devicePath); Console.WriteLine(); - Console.WriteLine("#{0:000}\tInput Device Path: [{1}]\t\t{2}\t\t{3}", ++deviceCount, devicePath, pDrive.StorageAdapterInfo.ToString(), pDrive.StorageDeviceInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Device Path: [{1}]\t\t{2}\t\t{3}", ++deviceCount, devicePath, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); - UnitTestConstants.Dump(pDrive, -24); + UnitTestConstants.Dump(pDisk, -24); - UnitTestConstants.Dump(pDrive.StorageAdapterInfo, -28, true); + UnitTestConstants.Dump(pDisk.StorageAdapterInfo, -28, true); - UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -17, true); + UnitTestConstants.Dump(pDisk.StorageDeviceInfo, -17, true); Console.WriteLine(); - Assert.IsNotNull(pDrive); + Assert.IsNotNull(pDisk); - Assert.IsNotNull(pDrive.VolumeGuids); - Assert.IsTrue(pDrive.VolumeGuids.Contains(sourceVolume)); + Assert.IsNotNull(pDisk.VolumeGuids); + Assert.IsTrue(pDisk.VolumeGuids.Contains(sourceVolume)); - Assert.IsNotNull(pDrive.LogicalDrives); + Assert.IsNotNull(pDisk.LogicalDrives); - Assert.IsTrue(pDrive.LogicalDrives.Contains(sourceDrive)); + Assert.IsTrue(pDisk.LogicalDrives.Contains(sourceDrive)); - Assert.IsTrue(pDrive.ContainsVolume(sourceDrive[0].ToString())); + Assert.IsTrue(pDisk.ContainsVolume(sourceDrive[0].ToString())); } } } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs similarity index 71% rename from AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs index 911c1b143..2430ee750 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs @@ -24,13 +24,13 @@ namespace AlphaFS.UnitTest { - public partial class AlphaFS_PhysicalDriveInfoTest + public partial class AlphaFS_PhysicalDiskInfoTest { // Pattern: ___ [TestMethod] - public void AlphaFS_Device_GetPhysicalDriveInfo_FromLogicalDrive_Success() + public void AlphaFS_Device_GetPhysicalDiskInfo_FromLogicalDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -40,26 +40,26 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromLogicalDrive_Success() // Use lowercase drive letter because .Contains() is case sensitive by default. var sourceDrive = UnitTestConstants.SysDrive.ToLowerInvariant() + System.IO.Path.DirectorySeparatorChar; - var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceDrive); + var pDisk = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDiskInfo(sourceDrive); Console.WriteLine(); - Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}\t\t{3}", ++driveCount, sourceDrive, pDrive.StorageAdapterInfo.ToString(), pDrive.StorageDeviceInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}\t\t{3}", ++driveCount, sourceDrive, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); - UnitTestConstants.Dump(pDrive, -24); + UnitTestConstants.Dump(pDisk, -24); - UnitTestConstants.Dump(pDrive.StorageAdapterInfo, -28, true); + UnitTestConstants.Dump(pDisk.StorageAdapterInfo, -28, true); - UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -17, true); + UnitTestConstants.Dump(pDisk.StorageDeviceInfo, -17, true); Console.WriteLine(); - Assert.IsNotNull(pDrive); + Assert.IsNotNull(pDisk); - Assert.IsNotNull(pDrive.LogicalDrives); - //Assert.IsTrue(pDrive.LogicalDrives.Contains(sourceDrive)); - Assert.IsTrue(pDrive.ContainsVolume(sourceDrive)); + Assert.IsNotNull(pDisk.LogicalDrives); + //Assert.IsTrue(pDisk.LogicalDrives.Contains(sourceDrive)); + Assert.IsTrue(pDisk.ContainsVolume(sourceDrive)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs similarity index 73% rename from AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs index 6f5de7d6c..4a3226def 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetPhysicalDriveInfo_FromVolume.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs @@ -24,13 +24,13 @@ namespace AlphaFS.UnitTest { - public partial class AlphaFS_PhysicalDriveInfoTest + public partial class AlphaFS_PhysicalDiskInfoTest { // Pattern: ___ [TestMethod] - public void AlphaFS_Device_GetPhysicalDriveInfo_FromVolume_Success() + public void AlphaFS_Device_GetPhysicalDiskInfo_FromVolume_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -44,27 +44,27 @@ public void AlphaFS_Device_GetPhysicalDriveInfo_FromVolume_Success() var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive).ToUpperInvariant(); - var pDrive = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDriveInfo(sourceVolume); + var pDisk = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDiskInfo(sourceVolume); Console.WriteLine(); - Console.WriteLine("#{0:000}\tInput Volume: [{1}]\t\t{2}\t\t{3}", ++volumeCount, sourceVolume, pDrive.StorageAdapterInfo.ToString(), pDrive.StorageDeviceInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Volume: [{1}]\t\t{2}\t\t{3}", ++volumeCount, sourceVolume, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); - UnitTestConstants.Dump(pDrive, -24); + UnitTestConstants.Dump(pDisk, -24); - UnitTestConstants.Dump(pDrive.StorageAdapterInfo, -28, true); + UnitTestConstants.Dump(pDisk.StorageAdapterInfo, -28, true); - UnitTestConstants.Dump(pDrive.StorageDeviceInfo, -17, true); + UnitTestConstants.Dump(pDisk.StorageDeviceInfo, -17, true); Console.WriteLine(); - Assert.IsNotNull(pDrive); + Assert.IsNotNull(pDisk); - Assert.IsNotNull(pDrive.VolumeGuids); - //Assert.IsTrue(pDrive.VolumeGuids.Contains(sourceVolume)); - Assert.IsTrue(pDrive.ContainsVolume(sourceVolume)); + Assert.IsNotNull(pDisk.VolumeGuids); + //Assert.IsTrue(pDisk.VolumeGuids.Contains(sourceVolume)); + Assert.IsTrue(pDisk.ContainsVolume(sourceVolume)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs similarity index 97% rename from AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs index 4a4e8988d..5ffeda9e4 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs @@ -24,7 +24,7 @@ namespace AlphaFS.UnitTest { - public partial class AlphaFS_PhysicalDriveInfoTest + public partial class AlphaFS_PhysicalDiskInfoTest { // Pattern: ___ diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs similarity index 97% rename from AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index 669f37590..e4d15569a 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -24,7 +24,7 @@ namespace AlphaFS.UnitTest { - public partial class AlphaFS_PhysicalDriveInfoTest + public partial class AlphaFS_PhysicalDiskInfoTest { // Pattern: ___ diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs similarity index 98% rename from AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs index c92486036..ad6d1d730 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs @@ -24,7 +24,7 @@ namespace AlphaFS.UnitTest { - public partial class AlphaFS_PhysicalDriveInfoTest + public partial class AlphaFS_PhysicalDiskInfoTest { // Pattern: ___ diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_PhysicalDriveInfoTest.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs similarity index 87% rename from AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_PhysicalDriveInfoTest.cs rename to AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs index 1d670d5cf..5889f48e2 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDrive Class/AlphaFS_PhysicalDriveInfoTest.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs @@ -23,9 +23,9 @@ namespace AlphaFS.UnitTest { - /// This is a test class for PhysicalDriveInfo and is intended to contain all PhysicalDriveInfo Unit Tests. + /// This is a test class for PhysicalDiskInfo and is intended to contain all PhysicalDiskInfo Unit Tests. [TestClass] - public partial class AlphaFS_PhysicalDriveInfoTest + public partial class AlphaFS_PhysicalDiskInfoTest { } } diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 856e41307..6c40c08a7 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -152,14 +152,14 @@ - - - - - - - - + + + + + + + + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 31baf49ff..43c830616 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -196,7 +196,7 @@ True - + @@ -206,15 +206,15 @@ - + - - - + + + - + diff --git a/AlphaFS/Device/Device.OpenPhysicalDrive.cs b/AlphaFS/Device/Device.OpenPhysicalDrive.cs index 786eaffaf..1ad1d5f1e 100644 --- a/AlphaFS/Device/Device.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/Device.OpenPhysicalDrive.cs @@ -29,20 +29,21 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// Opens a physical disk, volume/logical drive for read access. + /// Opens a physical disk or volume/logical drive for read access. /// A instance. /// /// /// /// /// + /// A disk path such as: "\\.\PhysicalDrive0" /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// - /// If no elevated access is needed to access the physical device, specify 0 for this parameter. + /// If no elevated access is needed to access the physical disk or volume/logical drive, specify 0 for this parameter. [SecurityCritical] - public static SafeFileHandle OpenPhysicalDrive(string devicePath, FileSystemRights fileSystemRights) + public static SafeFileHandle OpenPhysicalDisk(string devicePath, FileSystemRights fileSystemRights) { // fileSystemRights: If this parameter is 0 (FILE_ANY_ACCESS), the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs new file mode 100644 index 000000000..3ef7d0ec2 --- /dev/null +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs @@ -0,0 +1,159 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Collections.ObjectModel; +using System.Linq; +using System.Security; + +namespace Alphaleonis.Win32.Filesystem +{ + public static partial class Device + { + /// [AlphaFS] Enumerates the physical disks on the Computer, populated with volume- and logical drive information. + /// An collection that represents the physical disks on the Computer. + [SecurityCritical] + public static IEnumerable EnumeratePhysicalDisks() + { + return EnumeratePhysicalDisksCore(Security.ProcessContext.IsElevatedProcess); + } + + + + + /// [AlphaFS] Enumerates the physical disks on the Computer, populated with volume- and logical drive information. + /// An collection that represents the physical disks on the Computer. + [SecurityCritical] + internal static IEnumerable EnumeratePhysicalDisksCore(bool isElevated) + { + var physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDiskInfoCore(isElevated, null, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + + var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDiskInfoCore(false, volumeGuid, null, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + + var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDiskInfoCore(false, driveName, null, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + + + foreach (var pDisk in physicalDisks) + + yield return PopulatePhysicalDisk(pDisk, pVolumeGuids, pLogicalDrives); + + + // Windows Disk Management shows CD-ROM so mimic that behaviour. + + var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => GetPhysicalDiskInfoCore(isElevated, null, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + + foreach (var pCdRom in cdRoms) + + yield return PopulatePhysicalCDRom(pCdRom, pVolumeGuids, pLogicalDrives); + } + + + private static void PopulateLogicalDriveDetails(PhysicalDiskInfo pDiskInfo, string drivePath) + { + // Add device logical drive. + + if (null == pDiskInfo.LogicalDrives) + pDiskInfo.LogicalDrives = new Collection(); + + pDiskInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(drivePath)); + } + + + private static void PopulateVolumeDetails(PhysicalDiskInfo pDiskInfo, int partitionNumber, string volumeGuid) + { + //// Add device volume labels. + + //if (null == pDiskInfo.VolumeLabels) + // pDiskInfo.VolumeLabels = new Collection(); + + //pDiskInfo.VolumeLabels.Add(pVolume.Name); + + + // Add device partition index numbers. + + if (null == pDiskInfo.PartitionIndexes) + pDiskInfo.PartitionIndexes = new Collection(); + + pDiskInfo.PartitionIndexes.Add(partitionNumber); + + + // Add device volume GUIDs. + + if (null == pDiskInfo.VolumeGuids) + pDiskInfo.VolumeGuids = new Collection(); + + pDiskInfo.VolumeGuids.Add(volumeGuid); + } + + + private static PhysicalDiskInfo PopulatePhysicalCDRom(PhysicalDiskInfo pCdRom, PhysicalDiskInfo[] pVolumes, PhysicalDiskInfo[] pLogicalDrives) + { + var pDiskInfo = new PhysicalDiskInfo(pCdRom) {StorageDeviceInfo = pCdRom.StorageDeviceInfo}; + + + // Get volume from CDRom matching DeviceNumber. + + var pVolume = pVolumes.SingleOrDefault(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber && pVol.StorageDeviceInfo.PartitionNumber == pDiskInfo.StorageDeviceInfo.PartitionNumber); + + if (null != pVolume) + { + PopulateVolumeDetails(pDiskInfo, pVolume.StorageDeviceInfo.PartitionNumber, pVolume.DevicePath); + + + // Get logical drive from CDRom matching DeviceNumber and PartitionNumber. + + var pLogicalDrive = pLogicalDrives.SingleOrDefault(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pVolume.StorageDeviceInfo.PartitionNumber); + + if (null != pLogicalDrive) + PopulateLogicalDriveDetails(pDiskInfo, pLogicalDrive.DevicePath); + } + + + return pDiskInfo; + } + + + private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, PhysicalDiskInfo[] pVolumes, PhysicalDiskInfo[] pLogicalDrives) + { + var pDiskInfo = new PhysicalDiskInfo(pDisk) {StorageDeviceInfo = pDisk.StorageDeviceInfo}; + + + foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber)) + { + var volumeDriveNumber = pVolume.StorageDeviceInfo.DeviceNumber; + var volumePartitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; + + + PopulateVolumeDetails(pDiskInfo, pVolume.StorageDeviceInfo.PartitionNumber, pVolume.DevicePath); + + + // Get logical drive from volume matching DeviceNumber and PartitionNumber. + + foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == volumeDriveNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == volumePartitionNumber)) + + PopulateLogicalDriveDetails(pDiskInfo, pLogicalDrive.DevicePath); + } + + + return pDiskInfo; + } + } +} diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs similarity index 63% rename from AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs rename to AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs index 4eedcffce..ddd9085cc 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetPhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs @@ -29,22 +29,23 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - /// [AlphaFS] Retrieves the physical drive on the Computer that is related to the logical drive name, volume GUID or . - /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every volume or logical drive on the system as each call queries all physical drives and associated volumes and logical drives. - /// Instead, use method and property and/or . + /// [AlphaFS] Retrieves the physical disk on the Computer that is related to the logical drive name, volume GUID or . + /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. + /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks and associated volumes and logical drives. + /// Instead, use method and property and/or . /// - /// A instance that represents the physical drive on the Computer or null on error/no data available. + /// A instance that represents the physical disk on the Computer or null on error/no data available. /// /// /// /// + /// A disk path such as: "\\.\PhysicalDrive0"s /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// [SecurityCritical] - public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) + public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) { bool isDrive; bool isVolume; @@ -67,36 +68,37 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) GetDevicePath(devicePath, out devicePath); - var pDriveInfo = isDeviceInfo + var pDiskInfo = isDeviceInfo - ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => pDrive.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber && pDrive.StorageDeviceInfo.PartitionNumber == storageDeviceInfo.PartitionNumber) + ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => pDisk.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber && pDisk.StorageDeviceInfo.PartitionNumber == storageDeviceInfo.PartitionNumber) : isVolume - ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => null != pDrive.VolumeGuids && pDrive.VolumeGuids.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) + ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => null != pDisk.VolumeGuids && pDisk.VolumeGuids.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) : isDrive - ? EnumeratePhysicalDrivesCore(isElevated).SingleOrDefault(pDrive => null != pDrive.LogicalDrives && pDrive.LogicalDrives.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) + ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => null != pDisk.LogicalDrives && pDisk.LogicalDrives.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) : null; - if (null != pDriveInfo && null != pDriveInfo.StorageDeviceInfo) - pDriveInfo.StorageDeviceInfo.PartitionNumber = storageDeviceInfo.PartitionNumber; + if (null != pDiskInfo && null != pDiskInfo.StorageDeviceInfo) + pDiskInfo.StorageDeviceInfo.PartitionNumber = storageDeviceInfo.PartitionNumber; - return pDriveInfo; + return pDiskInfo; } - /// [AlphaFS] Retrieves the physical drive on the Computer that is related to the logical drive name, volume GUID or . - /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. + /// [AlphaFS] Retrieves the physical disk on the Computer that is related to the logical drive name, volume GUID or . + /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. /// - /// A instance that represents the physical drive on the Computer or null on error/no data available. + /// A instance that represents the physical disk on the Computer or null on error/no data available. /// /// /// /// /// indicates the current process is in an elevated state, allowing to retrieve more data. /// + /// A disk path such as: "\\.\PhysicalDrive0" /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". @@ -106,7 +108,7 @@ public static PhysicalDriveInfo GetPhysicalDriveInfo(string devicePath) /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) + internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) { var isDeviceInfo = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); @@ -121,7 +123,7 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, stri return null; - var pDriveInfo = new PhysicalDriveInfo + var pDiskInfo = new PhysicalDiskInfo { DevicePath = devicePath, @@ -140,28 +142,28 @@ internal static PhysicalDriveInfo GetPhysicalDriveInfoCore(bool isElevated, stri //GetDriveStuff(@"\\.\C:"); - using (var safeHandle = OpenPhysicalDrive(devicePath, FileSystemRights.Read)) + using (var safeHandle = OpenPhysicalDisk(devicePath, FileSystemRights.Read)) { - pDriveInfo.StorageAdapterInfo = GetStorageAdapterInfoNative(safeHandle, devicePath); + pDiskInfo.StorageAdapterInfo = GetStorageAdapterInfoNative(safeHandle, devicePath); storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, devicePath, storageDeviceInfo); } } - pDriveInfo.StorageDeviceInfo = storageDeviceInfo; + pDiskInfo.StorageDeviceInfo = storageDeviceInfo; if (isDeviceInfo) { - if (null == pDriveInfo.StorageAdapterInfo) - pDriveInfo.StorageAdapterInfo = new StorageAdapterInfo(); + if (null == pDiskInfo.StorageAdapterInfo) + pDiskInfo.StorageAdapterInfo = new StorageAdapterInfo(); - pDriveInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; + pDiskInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; } - return pDriveInfo; + return pDiskInfo; } } } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs similarity index 96% rename from AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs rename to AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs index 28133d87e..c65536290 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs @@ -38,6 +38,7 @@ public static partial class Device /// /// /// + /// A disk path such as: "\\.\PhysicalDrive0" /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". @@ -73,7 +74,7 @@ internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath) return null; - using (var safeHandle = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read)) + using (var safeHandle = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read)) return GetStorageAdapterInfoNative(safeHandle, devicePath); } @@ -112,7 +113,7 @@ private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle saf pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); + safeHandleRetry = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs similarity index 95% rename from AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs rename to AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs index 6287e7be8..a5d774faf 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs @@ -38,6 +38,7 @@ public static partial class Device /// /// /// + /// A disk path such as: "\\.\PhysicalDrive0" /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". @@ -81,7 +82,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri // Get storage device info. - using (var safeHandle = OpenPhysicalDrive(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = OpenPhysicalDisk(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) { var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); @@ -110,7 +111,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri if (null != storageDeviceInfo && isElevated) { - using (var safeHandle = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read)) + using (var safeHandle = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read)) storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, pathToDevice, storageDeviceInfo); } @@ -120,7 +121,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri } - /// Sets the physical drive properties such as FriendlyName, device size and serial number. + /// Sets the physical disk properties such as FriendlyName, device size and serial number. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeHandle, string pathToDevice, StorageDeviceInfo storageDeviceInfo) { @@ -154,7 +155,7 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); + safeHandleRetry = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; } diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs similarity index 97% rename from AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs rename to AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs index 19214a661..94e8ee532 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs @@ -49,7 +49,7 @@ internal static StoragePartitionInfo GetStoragePartitionInfoCore(string devicePa return null; - using (var safeHandle = OpenPhysicalDrive(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = OpenPhysicalDisk(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) return GetStoragePartitionInfoNative(safeHandle, devicePath); } @@ -82,7 +82,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - safeHandleRetry = OpenPhysicalDrive(pathToDevice, FileSystemRights.Read); + safeHandleRetry = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; } diff --git a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs similarity index 86% rename from AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs rename to AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs index ea97177e3..522cde204 100644 --- a/AlphaFS/Device/PhysicalDriveInfo/PhysicalDriveInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs @@ -26,23 +26,23 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides access to information of a physical drive. + /// Provides access to information of a physical disk. [Serializable] [SecurityCritical] - public sealed class PhysicalDriveInfo + public sealed class PhysicalDiskInfo { #region Constructors - /// Initializes a PhysicalDriveInfo instance. - public PhysicalDriveInfo() + /// Initializes a PhysicalDiskInfo instance. + public PhysicalDiskInfo() { } - /// Initializes a PhysicalDriveInfo instance. - public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) + /// Initializes a PhysicalDiskInfo instance. + public PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) { - CopyTo(physicalDriveInfo, this); + CopyTo(physicalDiskInfo, this); } #endregion // Constructors @@ -63,15 +63,15 @@ public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) public string DevicePath { get; internal set; } - /// The logical drives that are located on the physical drive. + /// The logical drives that are located on the physical disk. public Collection LogicalDrives { get; internal set; } - /// The "FriendlyName" of the physical drive. + /// The "FriendlyName" of the physical disk. public string Name { get; internal set; } - /// The partition index numbers that are located on the physical drive. + /// The partition index numbers that are located on the physical disk. public Collection PartitionIndexes { get; internal set; } @@ -91,11 +91,11 @@ public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) public StoragePartitionInfo StoragePartitionInfo { get; internal set; } - /// A collection of volume GUID strings of volumes that are located on the physical drive. + /// A collection of volume GUID strings of volumes that are located on the physical disk. public Collection VolumeGuids { get; internal set; } - ///// A collection of volume label strings of volumes that are located on the physical drive. + ///// A collection of volume label strings of volumes that are located on the physical disk. //public Collection VolumeLabels { get; internal set; } #endregion // Properties @@ -103,7 +103,7 @@ public PhysicalDriveInfo(PhysicalDriveInfo physicalDriveInfo) #region Methods - /// Checks if the logical drive or volume is located on the physical drive. + /// Checks if the volume or logical drive or is located on the physical disk. /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// @@ -128,7 +128,7 @@ public bool ContainsVolume(string devicePath) } - /// Returns the "FriendlyName" of the physical drive. + /// Returns the "FriendlyName" of the physical disk. /// A string that represents this instance. public override string ToString() { @@ -144,7 +144,7 @@ public override bool Equals(object obj) if (null == obj || GetType() != obj.GetType()) return false; - var other = obj as PhysicalDriveInfo; + var other = obj as PhysicalDiskInfo; return null != other && null != other.DevicePath && null != other.StorageDeviceInfo && @@ -168,7 +168,7 @@ public override int GetHashCode() /// A. /// B. /// The result of the operator. - public static bool operator ==(PhysicalDriveInfo left, PhysicalDriveInfo right) + public static bool operator ==(PhysicalDiskInfo left, PhysicalDiskInfo right) { return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); } @@ -178,7 +178,7 @@ public override int GetHashCode() /// A. /// B. /// The result of the operator. - public static bool operator !=(PhysicalDriveInfo left, PhysicalDriveInfo right) + public static bool operator !=(PhysicalDiskInfo left, PhysicalDiskInfo right) { return !(left == right); } @@ -186,7 +186,7 @@ public override int GetHashCode() private static void CopyTo(T source, T destination) { - // Properties listed here should not be overwritten by the physical drive template. + // Properties listed here should not be overwritten by the physical disk template. //var excludedProps = new[] {"PartitionNumber"}; diff --git a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs b/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs deleted file mode 100644 index f61605da2..000000000 --- a/AlphaFS/Device/PhysicalDriveInfo/Device.EnumeratePhysicalDrives.cs +++ /dev/null @@ -1,159 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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.Collections.ObjectModel; -using System.Linq; -using System.Security; - -namespace Alphaleonis.Win32.Filesystem -{ - public static partial class Device - { - /// [AlphaFS] Enumerates the physical drives on the Computer, populated with volume- and logical drive information. - /// An collection that represents the physical drives on the Computer. - [SecurityCritical] - public static IEnumerable EnumeratePhysicalDrives() - { - return EnumeratePhysicalDrivesCore(Security.ProcessContext.IsElevatedProcess); - } - - - - - /// [AlphaFS] Enumerates the physical drives on the Computer, populated with volume- and logical drive information. - /// An collection that represents the physical drives on the Computer. - [SecurityCritical] - internal static IEnumerable EnumeratePhysicalDrivesCore(bool isElevated) - { - var physicalDrives = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDriveInfoCore(isElevated, null, null, deviceInfo)).Where(physicalDrive => null != physicalDrive).ToArray(); - - var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDriveInfoCore(false, volumeGuid, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); - - var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDriveInfoCore(false, driveName, null, null)).Where(physicalDrive => null != physicalDrive).ToArray(); - - - foreach (var pDrive in physicalDrives) - - yield return PopulatePhysicalDrive(pDrive, pVolumeGuids, pLogicalDrives); - - - // Windows Disk Management shows CD-ROM so mimic that behaviour. - - var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => GetPhysicalDriveInfoCore(isElevated, null, null, deviceInfo)).Where(physicalDrive => null != physicalDrive).ToArray(); - - foreach (var pCdRom in cdRoms) - - yield return PopulatePhysicalCDRom(pCdRom, pVolumeGuids, pLogicalDrives); - } - - - private static void PopulateLogicalDriveDetails(PhysicalDriveInfo pDriveInfo, string drivePath) - { - // Add device logical drive. - - if (null == pDriveInfo.LogicalDrives) - pDriveInfo.LogicalDrives = new Collection(); - - pDriveInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(drivePath)); - } - - - private static void PopulateVolumeDetails(PhysicalDriveInfo pDriveInfo, int partitionNumber, string volumeGuid) - { - //// Add device volume labels. - - //if (null == pDriveInfo.VolumeLabels) - // pDriveInfo.VolumeLabels = new Collection(); - - //pDriveInfo.VolumeLabels.Add(pVolume.Name); - - - // Add device partition index numbers. - - if (null == pDriveInfo.PartitionIndexes) - pDriveInfo.PartitionIndexes = new Collection(); - - pDriveInfo.PartitionIndexes.Add(partitionNumber); - - - // Add device volume GUIDs. - - if (null == pDriveInfo.VolumeGuids) - pDriveInfo.VolumeGuids = new Collection(); - - pDriveInfo.VolumeGuids.Add(volumeGuid); - } - - - private static PhysicalDriveInfo PopulatePhysicalCDRom(PhysicalDriveInfo pCdRom, PhysicalDriveInfo[] pVolumes, PhysicalDriveInfo[] pLogicalDrives) - { - var pDriveInfo = new PhysicalDriveInfo(pCdRom) {StorageDeviceInfo = pCdRom.StorageDeviceInfo}; - - - // Get volume from CDRom matching DeviceNumber. - - var pVolume = pVolumes.SingleOrDefault(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDriveInfo.StorageDeviceInfo.DeviceNumber && pVol.StorageDeviceInfo.PartitionNumber == pDriveInfo.StorageDeviceInfo.PartitionNumber); - - if (null != pVolume) - { - PopulateVolumeDetails(pDriveInfo, pVolume.StorageDeviceInfo.PartitionNumber, pVolume.DevicePath); - - - // Get logical drive from CDRom matching DeviceNumber and PartitionNumber. - - var pLogicalDrive = pLogicalDrives.SingleOrDefault(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pVolume.StorageDeviceInfo.PartitionNumber); - - if (null != pLogicalDrive) - PopulateLogicalDriveDetails(pDriveInfo, pLogicalDrive.DevicePath); - } - - - return pDriveInfo; - } - - - private static PhysicalDriveInfo PopulatePhysicalDrive(PhysicalDriveInfo pDrive, PhysicalDriveInfo[] pVolumes, PhysicalDriveInfo[] pLogicalDrives) - { - var pDriveInfo = new PhysicalDriveInfo(pDrive) {StorageDeviceInfo = pDrive.StorageDeviceInfo}; - - - foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDriveInfo.StorageDeviceInfo.DeviceNumber)) - { - var volumeDriveNumber = pVolume.StorageDeviceInfo.DeviceNumber; - var volumePartitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; - - - PopulateVolumeDetails(pDriveInfo, pVolume.StorageDeviceInfo.PartitionNumber, pVolume.DevicePath); - - - // Get logical drive from volume matching DeviceNumber and PartitionNumber. - - foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == volumeDriveNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == volumePartitionNumber)) - - PopulateLogicalDriveDetails(pDriveInfo, pLogicalDrive.DevicePath); - } - - - return pDriveInfo; - } - } -} diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs index 10dae1dbd..6be9cdb62 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -62,7 +62,7 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public StorageBusType BusType { get; internal set; } - /// Indicates if the physical drive supports multiple outstanding commands (SCSI tagged queuing or equivalent). When false the physical drive does not support SCSI-tagged queuing or the equivalent. + /// Indicates if the physical disk supports multiple outstanding commands (SCSI tagged queuing or equivalent). When false the physical disk does not support SCSI-tagged queuing or the equivalent. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Queueing")] public bool CommandQueueing { get; internal set; } @@ -79,34 +79,34 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public int PartitionNumber { get; internal set; } - /// The product ID of the physical drive. + /// The product ID of the physical disk. public string ProductId { get; internal set; } - /// The product revision of the physical drive. + /// The product revision of the physical disk. public string ProductRevision { get; internal set; } - /// Indicates if the physical drive is removable. When true the physical drive's media (if any) is removable. If the device has no media, this member should be ignored. When false the physical drive's media is not removable. + /// Indicates if the physical disk is removable. When true the physical disk's media (if any) is removable. If the device has no media, this member should be ignored. When false the physical disk's media is not removable. public bool RemovableMedia { get; internal set; } - /// The serial number of the physical drive. If the physical drive has no serial number or the session is not elevated -1 is returned. + /// The serial number of the physical disk. If the physical disk has no serial number or the session is not elevated -1 is returned. public string SerialNumber { get; internal set; } - /// The total size of the physical drive. + /// The total size of the physical disk. public long TotalSize { get; internal set; } - /// The total size of the physical drive, formatted as a unit size. + /// The total size of the physical disk, formatted as a unit size. public string TotalSizeUnitSize { get { return Utils.UnitSizeToText(TotalSize); } } - /// The Vendor ID of the physical drive. + /// The Vendor ID of the physical disk. public string VendorId { get; internal set; } #endregion // Properties diff --git a/AlphaFS/Filesystem/Path Class/Path.Constants.cs b/AlphaFS/Filesystem/Path Class/Path.Constants.cs index bcbbb80bc..f5a3f12b0 100644 --- a/AlphaFS/Filesystem/Path Class/Path.Constants.cs +++ b/AlphaFS/Filesystem/Path Class/Path.Constants.cs @@ -107,7 +107,7 @@ public static partial class Path /// [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. public static readonly string LogicalDrivePrefix = string.Format(CultureInfo.InvariantCulture, "{0}{0}.{0}", DirectorySeparatorChar); - /// [AlphaFS] PhysicalDrivePrefix = "\\.\PhysicalDrive" Provides standard physical drive prefix. + /// [AlphaFS] PhysicalDrivePrefix = "\\.\PhysicalDrive" Provides standard physical disk prefix. public static readonly string PhysicalDrivePrefix = string.Format(CultureInfo.InvariantCulture, "{0}PhysicalDrive", LogicalDrivePrefix); From 89429eb7b36cb36e52d6f8ee0b0aa6a3a2e80c81 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 28 Feb 2018 11:37:24 +0100 Subject: [PATCH 061/133] Added more PartitionType enum members. Code improvement, work in progress. --- AlphaFS/Device/Device.EnumerateDevices.cs | 2 +- AlphaFS/Device/Device.GetDeviceIoData.cs | 2 +- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 50 +- AlphaFS/Device/Device.InvokeDeviceIoData.cs | 2 +- AlphaFS/Device/Device.cs | 7 +- .../Junctions, Links/Device.GetLinkTarget.cs | 2 +- .../Device.GetStorageAdapterInfo.cs | 2 +- .../Device.GetStorageDeviceInfo.cs | 4 +- .../Device.GetStoragePartitionInfo.cs | 6 +- AlphaFS/Device/StoragePartitionInfo.cs | 2 +- .../DiskPartitionType.cs | 23 +- .../PartitionType..cs | 660 ++++++++++++++++-- 12 files changed, 651 insertions(+), 111 deletions(-) diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Device.EnumerateDevices.cs index d2d6c05e4..c1dad9bb4 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -235,7 +235,7 @@ private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMet return null; - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, property.ToString()); + bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, property.ToString()); } } diff --git a/AlphaFS/Device/Device.GetDeviceIoData.cs b/AlphaFS/Device/Device.GetDeviceIoData.cs index ec1c9cf75..112e6b8aa 100644 --- a/AlphaFS/Device/Device.GetDeviceIoData.cs +++ b/AlphaFS/Device/Device.GetDeviceIoData.cs @@ -64,7 +64,7 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa return null; } - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); } } } diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index ba73460b3..db3f0b0c4 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -28,49 +28,28 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Device { /// Retrieves the physical location of a specified volume on one or more disks. - private static NativeMethods.VOLUME_DISK_EXTENTS? GetVolumeDiskExtents(SafeFileHandle safeHandle) + private static NativeMethods.VOLUME_DISK_EXTENTS? GetVolumeDiskExtents(SafeFileHandle safeHandle, string pathForException) { - NativeMethods.VOLUME_DISK_EXTENTS? structure; var structSize = Marshal.SizeOf(typeof(NativeMethods.VOLUME_DISK_EXTENTS)); - var bufferSize = structSize; - bool success; - int lastError; - - - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) - { - success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); - - lastError = Marshal.GetLastWin32Error(); - - structure = safeBuffer.PtrToStructure(0); - } - - - if (!success) - { - if (lastError != Win32Errors.ERROR_MORE_DATA) - return null; - - - // 2018-02-15 Yomodo: Not fully tested. - - - var numberOfExtents = ((NativeMethods.VOLUME_DISK_EXTENTS) structure).NumberOfDiskExtents; - - bufferSize = (int) (structSize * numberOfExtents); + var numberOfExtents = 1; + var bufferSize = structSize * numberOfExtents; + while(true) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) { - success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + + var lastError = Marshal.GetLastWin32Error(); - lastError = Marshal.GetLastWin32Error(); + // https://stackoverflow.com/questions/19825910/get-size-of-volume-on-windows + // https://stackoverflow.com/questions/327718/how-to-list-physical-disks + // https://github.com/Invoke-IR/PowerForensics/blob/master/src/PowerForensicsCore/src/PowerForensics.BootSectors/GuidPartitionTable.cs if (success) { - numberOfExtents = (uint) safeBuffer.PtrToStructure(0).NumberOfExtents; + numberOfExtents = safeBuffer.PtrToStructure(0).NumberOfExtents; var diskExtent = new NativeMethods.DISK_EXTENT[numberOfExtents]; @@ -82,11 +61,10 @@ public static partial class Device return new NativeMethods.VOLUME_DISK_EXTENTS {Extents = diskExtent}; } - } - } - - return structure; + + bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); + } } } } diff --git a/AlphaFS/Device/Device.InvokeDeviceIoData.cs b/AlphaFS/Device/Device.InvokeDeviceIoData.cs index 83f2c821b..df810f8d4 100644 --- a/AlphaFS/Device/Device.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Device.InvokeDeviceIoData.cs @@ -65,7 +65,7 @@ private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle return null; } - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); } } } diff --git a/AlphaFS/Device/Device.cs b/AlphaFS/Device/Device.cs index 3bff779e2..75f133463 100644 --- a/AlphaFS/Device/Device.cs +++ b/AlphaFS/Device/Device.cs @@ -36,7 +36,7 @@ public static partial class Device [SecurityCritical] - internal static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHandle safeBuffer, int bufferSize, string pathForException) + private static int GetDoubledBufferSizeOrThrowException(SafeHandle safeBuffer, int lastError, int bufferSize, string pathForException) { if (null != safeBuffer && !safeBuffer.IsClosed) safeBuffer.Close(); @@ -46,6 +46,11 @@ internal static int GetDoubledBufferSizeOrThrowException(int lastError, SafeHand { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: + case Win32Errors.ERROR_INVALID_PARAMETER: + + if (bufferSize == 0) + bufferSize = NativeMethods.DefaultFileBufferSize / 32; // 128 + bufferSize *= 2; break; diff --git a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs index ba56e7978..9073da111 100644 --- a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs +++ b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs @@ -104,7 +104,7 @@ private static SafeGlobalMemoryBufferHandle GetLinkTargetData(SafeFileHandle saf if (success) return safeBuffer; - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, reparsePath); + bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, reparsePath); } } } diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs index c65536290..52de8f197 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs @@ -104,7 +104,7 @@ private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle saf // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); + var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle, pathToDevice); if (volDiskExtents.HasValue) { diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs index a5d774faf..decaf0920 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs @@ -91,7 +91,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - var volDiskExtents = GetVolumeDiskExtents(safeHandle); + var volDiskExtents = GetVolumeDiskExtents(safeHandle, pathToDevice); if (volDiskExtents.HasValue) { @@ -146,7 +146,7 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); + var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle, pathToDevice); if (volDiskExtents.HasValue) { diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs index 94e8ee532..0eb4bfdbc 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs @@ -73,7 +73,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle); + var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle, pathToDevice); if (volDiskExtents.HasValue) { @@ -165,7 +165,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative0(SafeFileHandl return null; - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); } } @@ -221,7 +221,7 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHa return new NativeMethods.DISK_GEOMETRY_EX(); - bufferSize = GetDoubledBufferSizeOrThrowException(lastError, safeBuffer, bufferSize, pathForException); + bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); } } } diff --git a/AlphaFS/Device/StoragePartitionInfo.cs b/AlphaFS/Device/StoragePartitionInfo.cs index 0ab12959e..0ee788b24 100644 --- a/AlphaFS/Device/StoragePartitionInfo.cs +++ b/AlphaFS/Device/StoragePartitionInfo.cs @@ -93,7 +93,7 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods // MSDN: PartitionCount: On hard disks with the MBR layout, this value will always be a multiple of 4. // Any partitions that are actually unused will have a partition type of PARTITION_ENTRY_UNUSED (0). - if (partition.Mbr.PartitionType == (NativeMethods.DiskPartitionType) DiskPartitionType.EntryUnused) + if (partition.Mbr.PartitionType == (NativeMethods.DiskPartitionType) DiskPartitionType.UnusedEntry) continue; diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs index 6d7f8fec0..244746f5c 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs @@ -24,32 +24,33 @@ namespace Alphaleonis.Win32.Filesystem { /// The following table identifies the valid partition types that are used by disk drivers. + /// http://www.win.tue.nl/~aeb/partitions/partition_types-1.html public enum DiskPartitionType { /// An unused entry partition. - EntryUnused = NativeMethods.DiskPartitionType.PARTITION_ENTRY_UNUSED, + UnusedEntry = NativeMethods.DiskPartitionType.PARTITION_ENTRY_UNUSED, - /// A FAT12 file system partition. + /// DOS 12-bit FAT partition. Fat12 = NativeMethods.DiskPartitionType.PARTITION_FAT_12, - /// A XENIX1 partition. + /// A XENIX root partition. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Xenix")] - Xenix1 = 2, + XenixRoot = 2, - /// A XENIX2 partition. + /// A XENIX /usr partition. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Xenix")] - Xenix2 = 3, + XenixUser = 3, - /// A FAT16 file system partition. + /// DOS 3.0+ 16-bit FAT partition (up to 32M). Fat16 = NativeMethods.DiskPartitionType.PARTITION_FAT_16, - /// An extended partition. + /// DOS 3.3+ Extended partition. Extended = NativeMethods.DiskPartitionType.PARTITION_EXTENDED, - /// A huge partition. - Huge = 6, + /// DOS 3.31+ 16-bit FAT partition (over 32M). + Fat16Big = 6, - /// An IFS (Installable File System) partition. + /// OS/2 IFS (Installable File System) (e.g., HPFS) partition. Ifs = NativeMethods.DiskPartitionType.PARTITION_IFS, /// A FAT32 file system partition. diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs index 01644de28..21176ab79 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs @@ -24,16 +24,59 @@ namespace Alphaleonis.Win32.Filesystem { - /// Specifies the different types of partition GUIDs. + /// Specifies the different types of partition GUIDs. + /// https://en.wikipedia.org/wiki/GUID_Partition_Table + /// public enum PartitionType { - /// PARTITION_ENTRY_UNUSED_GUID: There is no partition. + #region Non-OS + + /// There is no partition. /// This value can be set for basic and dynamic disks. /// [Description("00000000-0000-0000-0000-000000000000")] - EntryUnused, + UnusedEntry, + + /// Legacy MBR partition. A partition that is sub-partitioned by a Master Boot Record; "partitions-inside-a-slice configuration". + [Description("024DEE41-33E7-11D3-9D69-0008C781F39F")] + LegacyMbr, + + /// The partition is an EFI system partition. + /// This value can be set for basic and dynamic disks. + /// + [Description("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")] + EfiSystem, - /// PARTITION_BASIC_DATA_GUID: The data partition type that is created and recognized by Windows. + /// BIOS boot partition. + [Description("21686148-6449-6E6F-744E-656564454649F")] + BiosBoot, + + /// Intel Fast Flash (iFFS, Intel Rapid Start technology) partition. + [Description("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593")] + Iffs, + + /// Sony boot partition. + [Description("F4019732-066E-4E12-8273-346C5641494F")] + SonyBoot, + + /// Lenovo boot partition. + [Description("BFBFAFE7-A34F-448A-9A5B-6213EB736C22")] + LenovoBoot, + + #endregion // Non-OS + + + #region Windows + + /// The partition is a Microsoft reserved partition. + /// This value can be set for basic and dynamic disks. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Msft")] + [SuppressMessage("Microsoft.Naming", "CA1700:DoNotNameEnumValuesReserved")] + [Description("E3C9E316-0B5C-4DB8-817D-F92DF00215AE")] + MsftReserved, + + /// The data partition type that is created and recognized by Windows. /// /// This value can be set only for basic disks, with one exception. /// Only partitions of this type can be assigned drive letters, receive volume GUID paths, host mounted folders (also called volume mount points), and be enumerated by calls to FindFirstVolume and FindNextVolume. @@ -42,79 +85,592 @@ public enum PartitionType [Description("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7")] BasicData, - /// PARTITION_LDM_DATA_GUID: The partition is an LDM data partition on a dynamic disk. + /// The partition is a Logical Disk Manager (LDM) metadata partition on a dynamic disk. /// This value can be set only for dynamic disks. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ldm")] - [Description("AF9B60A0-1431-4F62-BC68-3311714A69AD")] - LdmData, + [Description("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3")] + LdmMetadata, - /// PARTITION_LDM_METADATA_GUID: The partition is a Logical Disk Manager (LDM) metadata partition on a dynamic disk. + /// The partition is an LDM data partition on a dynamic disk. /// This value can be set only for dynamic disks. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ldm")] - [Description("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3")] - LdmMetadata, - - /// PARTITION_MSFT_RECOVERY_GUID: The partition is a Microsoft recovery partition. + [Description("AF9B60A0-1431-4F62-BC68-3311714A69AD")] + LdmData, + + /// The partition is a Microsoft recovery partition. /// This value can be set for basic and dynamic disks. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Msft")] [Description("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC")] MsftRecovery, + + /// IBM General Parallel File System (GPFS) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpfs")] + [Description("37AFFC90-EF7D-4E96-91C3-2D7AE055B174")] + IbmGpfs, - /// PARTITION_MSFT_RESERVED_GUID: The partition is a Microsoft reserved partition. - /// This value can be set for basic and dynamic disks. - /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Msft")] - [SuppressMessage("Microsoft.Naming", "CA1700:DoNotNameEnumValuesReserved")] - [Description("E3C9E316-0B5C-4DB8-817D-F92DF00215AE")] - MsftReserved, + /// Storage Spaces partition. + [Description("E75CAF8F-F680-4CEE-AFA3-B001E56EFC2D")] + StorageSpace, - /// PARTITION_SYSTEM_GUID: The partition is an EFI system partition. - /// This value can be set for basic and dynamic disks. - /// - [Description("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")] - System, + #endregion // Windows + #region HP-UX + /// HP-UX Data partition. + [Description("75894C1E-3AEB-11D3-B7C1-7B03A0000000")] + HpUxData, - // 2018-02-27 GUID Partition Table - // https://en.wikipedia.org/wiki/GUID_Partition_Table + /// HP-UX Service partition. + [Description("E2A1E728-32E3-11D6-A682-7B03A0000000")] + HpUxService, + #endregion // HP-UX - /// IBM General Parallel File System (GPFS) partition. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpfs")] - [Description("37AFFC90-EF7D-4E96-91C3-2D7AE055B174")] - IbmGpfs, - /// Storage Spaces partition. - [Description("E75CAF8F-F680-4CEE-AFA3-B001E56EFC2D")] - StorageSpace, + #region Linux + + /// Linux filesystem data partition. + [Description("0FC63DAF-8483-4772-8E79-3D69D8477DE4")] + LinuxData, - /// MBR partition scheme. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr")] - [Description("024DEE41-33E7-11D3-9D69-0008C781F39F")] - MbrScheme, + /// Linux RAID partition. + [Description("A19D880F-05FC-4D3B-A006-743F0F84911E")] + LinuxRaid, - /// BIOS boot partition. - [Description("21686148-6449-6E6F-744E-656564454649F")] - BiosBoot, + /// Linux Root (x86) partition. + [Description("44479540-F297-41B2-9AF7-D131D5F0458A")] + LinuxRootX86, - /// Intel Fast Flash (iFFS) partition (for Intel Rapid Start technology). - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ffs")] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "i")] - [Description("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593")] - iFfs, + /// Linux Root (x86-64) partition. + [Description("4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709")] + LinuxRootX8664, - /// Sony boot partition. - [Description("F4019732-066E-4E12-8273-346C5641494F")] - SonyBoot, + /// Linux Root (32bit ARM) partition. + [Description("69DAD710-2CE4-4E3C-B16C-21A1D49ABED3")] + LinuxRoot32bitArm, - /// Lenovo boot partition. - [Description("BFBFAFE7-A34F-448A-9A5B-6213EB736C22")] - LenovoBoot, + /// Linux Root (64bit ARM/AArch64) partition. + [Description("B921B045-1DF0-41C3-AF44-4C6F280D3FAE")] + LinuxRoot64bitArm, + + /// Linux Swap partition. + [Description("0657FD6D-A4AB-43C4-84E5-0933C84B4F4F")] + LinuxSwap, + + /// Linux Logical Volume Manager(LVM) partition. + [Description("E6D6D379-F507-44C2-A23C-238F2A3DF928")] + LinuxLvm, + + /// LinuxLinux /home partition. + [Description("933AC7E1-2EB4-4F13-B844-0E14E2AEF915")] + LinuxHome, + + /// Linux /srv (server data) partition. + [Description("3B8F8425-20E0-4F3B-907F-1A25A76F98E8")] + LinuxSrv, + + /// Linux Plain dm-crypt partition. + [Description("7FFEC5C9-2D00-49B7-8941-3EA10A5586B7")] + LinuxPlainDmCrypt, + + /// Linux LUKS partition. + [Description("CA7D7CCB-63ED-4C53-861C-1742536059CC")] + LinuxLuks, + + /// Linux Reserved partition. + [Description("8DA63339-0007-60C0-C436-083AC8230908")] + LinuxReserved, + + #endregion // Linux + + + #region FreeBSD + + /// FreeBSD Boot partition. + [Description("83BD6B9D-7F41-11DC-BE0B-001560B84F0F")] + FreeBsdBoot, + + /// FreeBSD Data partition. + [Description("516E7CB4-6ECF-11D6-8FF8-00022D09712B")] + FreeBsdData, + + /// FreeBSD Swap partition. + [Description("516E7CB5-6ECF-11D6-8FF8-00022D09712B")] + FreeBsdSwap, + + /// FreeBSD Unix File System (UFS) partition. + [Description("516E7CB6-6ECF-11D6-8FF8-00022D09712B")] + FreeBsdUfs, + + /// FreeBSD Vinum Volume Manager partition. + [Description("516E7CB8-6ECF-11D6-8FF8-00022D09712B")] + FreeBsdVvm, + + /// FreeBSD ZFS partition. + [Description("516E7CBA-6ECF-11D6-8FF8-00022D09712B")] + FreeBsdZfs, + + #endregion // FreeBSD + + + #region MacOS Darwin + + /// OSX Hierarchical File System Plus (HFS+) partition. + [Description("48465300-0000-11AA-AA11-00306543ECAC")] + OsXHfs, + + /// OSX Apple APFS partition. + [Description("7C3457EF-0000-11AA-AA11-00306543ECAC")] + OsXAppleApfs, + + /// OSX Apple UFS partition. + [Description("55465300-0000-11AA-AA11-00306543ECAC")] + OsXAppleUfs, + + /// OSX ZFS partition. + [Description("6A898CC3-1DD2-11B2-99A6-080020736631")] + OsXZfs, + + /// OSX Apple RAID partition. + [Description("52414944-0000-11AA-AA11-00306543ECAC")] + OsXAppleRaid, + + /// OSX Apple RAID offline partition. + [Description("52414944-5F4F-11AA-AA11-00306543ECAC")] + OsXAppleRaidOffline, + + /// OSX Apple Boot (Recovery HD) partition. + [Description("426F6F74-0000-11AA-AA11-00306543ECAC")] + OsXBootRecovery, + + /// OSX Apple Label partition. + [Description("C616265-6C00-11AA-AA11-00306543ECAC")] + OsXLabel, + + /// OSX Apple TV Recovery partition. + [Description("5265636F-7665-11AA-AA11-00306543ECAC")] + OsXTvRecovery, + + /// OSX Apple Core Storage (i.e. Lion FileVault) partition. + [Description("53746F72-6167-11AA-AA11-00306543ECAC")] + OsXCoreStorage, + + /// OSX SoftRAID_Status partition. + [Description("B6FA30DA-92D2-4A9A-96F1-871EC6486200")] + OsXSoftRaidStatus, + + /// OSX SoftRAID_Scratch partition. + [Description("2E313465-19B9-463F-8126-8A7993773801")] + OsXSoftRaidScratch, + + /// OSX SoftRAID_Volume partition. + [Description("FA709C7E-65B1-4593-BFD5-E71D61DE9B02")] + OsXSoftRaidVolume, + + /// OSX SoftRAID_Cache partition. + [Description("BBBA6DF5-F46F-4A89-8F59-8765B2727503")] + OsXSoftRaidCache, + + #endregion // MacOS Darwin + + + #region Solaris Illumos + + /// Solaris Boot partition. + [Description("6A82CB45-1DD2-11B2-99A6-080020736631")] + SolarisBoot, + + /// Solaris Root partition. + [Description("6A85CF4D-1DD2-11B2-99A6-080020736631")] + SolarisRoot, + + /// Solaris Swap partition. + [Description("6A87C46F-1DD2-11B2-99A6-080020736631")] + SolarisSwap, + + /// Solaris Backup partition. + [Description("6A8B642B-1DD2-11B2-99A6-080020736631")] + SolarisBackup, + + /// Solaris /usr partition. + [Description("6A898CC3-1DD2-11B2-99A6-080020736631")] + SolarisUsr, + + /// Solaris /var partition. + [Description("6A8EF2E9-1DD2-11B2-99A6-080020736631")] + SolarisVar, + + /// Solaris /home partition. + [Description("6A90BA39-1DD2-11B2-99A6-080020736631")] + SolarisHome, + + /// Solaris Alternate sector partition. + [Description("6A9283A5-1DD2-11B2-99A6-080020736631")] + SolarisAlternateSector, + + /// Solaris Reserved partition. + [Description("6A945A3B-1DD2-11B2-99A6-080020736631")] + SolarisReserved1, + + /// Solaris Reserved partition. + [Description("6A9630D1-1DD2-11B2-99A6-080020736631")] + SolarisReserved2, + + /// Solaris Reserved partition. + [Description("6A980767-1DD2-11B2-99A6-080020736631")] + SolarisReserved3, + + /// Solaris Reserved partition. + [Description("6A96237F-1DD2-11B2-99A6-080020736631")] + SolarisReserved4, + + /// Solaris Reserved partition. + [Description("6A8D2AC7-1DD2-11B2-99A6-080020736631")] + SolarisReserved5, + + #endregion // Solaris Illumos + + + #region NetBSD + + /// NetBSD Swap partition. + [Description("6A82CB45-1DD2-11B2-99A6-080020736631")] + NetBsdSwap, + + /// NetBSD Fast File System (FFS) partition. + [Description("49F48D5A-B10E-11DC-B99B-0019D1879648")] + NetBsdFfs, + + /// NetBSD Log-Structured File System (LFS) partition. + [Description("49F48D82-B10E-11DC-B99B-0019D1879648")] + NetBsdLfs, + + /// NetBSD RAID partition. + [Description("49F48DAA-B10E-11DC-B99B-0019D1879648")] + NetBsdRaid, + + /// NetBSD Concatenated partition. + [Description("2DB519C4-B10F-11DC-B99B-0019D1879648")] + NetBsdConcatenated, + + /// NetBSD Encrypted partition. + [Description("2DB519EC-B10F-11DC-B99B-0019D1879648")] + NetBsdEncrypted, + + #endregion // NetBSD + + + #region Chrome OS + + /// Chrome OS Kernel partition. + [Description("FE3A2A5D-4F32-41A7-B725-ACCC3285A309")] + ChromseOsKernel, + + /// Chrome OS RootFS partition. + [Description("3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC")] + ChromseOsRootFs, + + /// Chrome OS (future use) partition. + [Description("2E0A753D-9E48-43B0-8337-B15192CB1B5E")] + ChromseOsFutureUse, + + #endregion // Chrome OS + + + #region Haiku + + /// Haiku Be File System (BFS) partition. + [Description("42465331-3BA3-10F1-802A-4861696B7521")] + HaikuBfs, + + #endregion // Haiku + + + #region MidnightBSD + + /// MidnightBSD Boot partition. + [Description("85D5E45E-237C-11E1-B4B3-E89A8F7FC3A7")] + MidnightBsdBoot, + + /// MidnightBSD Data partition. + [Description("85D5E45A-237C-11E1-B4B3-E89A8F7FC3A7")] + MidnightBsdData, + + /// MidnightBSD Swap partition. + [Description("85D5E45B-237C-11E1-B4B3-E89A8F7FC3A7")] + MidnightBsdSwap, + + /// MidnightBSD Unix File System (UFS) partition. + [Description("0394EF8B-237E-11E1-B4B3-E89A8F7FC3A7")] + MidnightBsdUfs, + + /// MidnightBSD Vinum Volume Manager partition. + [Description("85D5E45C-237C-11E1-B4B3-E89A8F7FC3A7")] + MidnightBsdVvm, + + /// MidnightBSD ZFS partition. + [Description("85D5E45D-237C-11E1-B4B3-E89A8F7FC3A7")] + MidnightBsdZfs, + + #endregion // MidnightBSD + + + #region Ceph + + /// Ceph journal partition. + [Description("45B0969E-9B03-4F30-B4C6-B4B80CEFF106")] + CephJournal, + + /// Ceph dm-crypt journal partition. + [Description("45B0969E-9B03-4F30-B4C6-5EC00CEFF106")] + CephDmCryptJournal, + + /// Ceph OSD partition. + [Description("4FBD7E29-9D25-41B8-AFD0-062C0CEFF05D")] + CephOsd, + + /// Ceph dm-crypt OSD partition. + [Description("4FBD7E29-9D25-41B8-AFD0-5EC00CEFF05D")] + CephDmCryptOsd, + + /// Ceph disk in creation partition. + [Description("89C57F98-2FE5-4DC0-89C1-F3AD0CEFF2BE")] + CephDiskInCreation, + + /// Ceph dm-crypt disk in creation partition. + [Description("89C57F98-2FE5-4DC0-89C1-5EC00CEFF2BE")] + CephDmCryptDiskInCreation, + + /// Ceph block partition. + [Description("CAFECAFE-9B03-4F30-B4C6-B4B80CEFF106")] + CephBlock, + + /// Ceph block DB partition. + [Description("30CD0809-C2B2-499C-8879-2D6B78529876")] + CephBlockDb, + + /// Ceph block write-ahead log partition. + [Description("5CE17FCE-4087-4169-B7FF-056CC58473F9")] + CephBlockWriteAheadLog, + + /// Ceph lockbox for dm-crypt keys partition. + [Description("FB3AABF9-D25F-47CC-BF5E-721D1816496B")] + CephDmCryptKeysLockbox, + + /// Ceph multipath OSD partition. + [Description("4FBD7E29-8AE0-4982-BF9D-5A8D867AF560")] + CephMultipathOsd, + + /// Ceph multipath journal partition. + [Description("45B0969E-8AE0-4982-BF9D-5A8D867AF560")] + CephMultipathJournal, + + /// Ceph multipath block partition. + [Description("CAFECAFE-8AE0-4982-BF9D-5A8D867AF560")] + CephMultipathBlock1, + + /// Ceph multipath block partition. + [Description("7F4A666A-16F3-47A2-8445-152EF4D03F6C")] + CephMultipathBlock2, + + /// Ceph multipath block DB partition. + [Description("EC6D6385-E346-45DC-BE91-DA2A7C8B3261")] + CephMultipathBlockDb, + + /// Ceph multipath block write-ahead log partition. + [Description("01B41E1B-002A-453C-9F17-88793989FF8F")] + CephMultipathBlockWriteAheadLog, + + /// Ceph dm-crypt block partition. + [Description("CAFECAFE-9B03-4F30-B4C6-5EC00CEFF106")] + CephDmCryptBlock, + + /// Ceph dm-crypt block DB partition. + [Description("93B0052D-02D9-4D8A-A43B-33A3EE4DFBC3")] + CephDmCryptBlockDb, + + /// Ceph dm-crypt block write-ahead log partition. + [Description("306E8683-4FE2-4330-B7C0-00A917C16966")] + CephDmCryptBlockWriteAheadLog, + + /// Ceph dm-crypt LUKS journal partition. + [Description("45B0969E-9B03-4F30-B4C6-35865CEFF106")] + CephDmCryptLuksJournal, + + /// Ceph dm-crypt LUKS block partition. + [Description("CAFECAFE-9B03-4F30-B4C6-35865CEFF106")] + CephDmCryptLuksBlock, + + /// Ceph dm-crypt LUKS block DB partition. + [Description("166418DA-C469-4022-ADF4-B30AFD37F176")] + CephDmCryptLuksBlockDb, + + /// Ceph dm-crypt LUKS block write-ahead log partition. + [Description("166418DA-C469-4022-ADF4-B30AFD37F176")] + CephDmCryptLuksBlockWriteAheadLog, + + /// Ceph dm-crypt LUKS OSD partition. + [Description("166418DA-C469-4022-ADF4-B30AFD37F176")] + CephDmCryptLuksOsd, + + #endregion // Ceph + + + #region OpenBSD + + /// OpenBSD Data partition. + [Description("824CC7A0-36A8-11E3-890A-952519AD3F61")] + OpenBsdData, + + #endregion // OpenBSD + + + #region QNX + + /// QNX Power-safe (QNX6) file system partition. + [Description("CEF5A9AD-73BC-4601-89F3-CDEEEEE321A1")] + Qnx6, + + #endregion // QNX + + + #region Plan 9 + + /// Plan 9 partition. + [Description("C91818F9-8025-47AF-89D2-F030D7000C2C")] + Plan9, + + #endregion // Plan 9 + + + #region VMware ESX + + /// VMware ESX vmkcore (coredump) partition. + [Description("9D275380-40AD-11DB-BF97-000C2911D1B8")] + VmWareEsxCore, + + /// VMware ESX Virtual Machine File System (VMFS) partition. + [Description("AA31E02A-400F-11DB-9590-000C2911D1B8")] + VmWareEsxVmfs, + + /// VMware ESX Reserved partition. + [Description("9198EFFC-31C0-11DB-8F78-000C2911D1B8")] + VmWareEsxReserved, + + #endregion // VMware ESX + + + #region Android-IA + + /// Android-IA Bootloader partition. + [Description("2568845D-2332-4675-BC39-8FA5A4748D15")] + AndroidIaBootloader, + + /// Android-IA Bootloader2 partition. + [Description("114EAFFE-1552-4022-B26E-9B053604CF84")] + AndroidIaBootloader2, + + /// Android-IA Boot partition. + [Description("49A4D17F-93A3-45C1-A0DE-F50B2EBE2599")] + AndroidIaBoot, + + /// Android-IA Recovery partition. + [Description("4177C722-9E92-4AAB-8644-43502BFD5506")] + AndroidIaRecovery, + + /// Android-IA Misc partition. + [Description("EF32A33B-A409-486C-9141-9FFB711F6266")] + AndroidIaMisc, + + /// Android-IA Metadata partition. + [Description("20AC26BE-20B7-11E3-84C5-6CFDB94711E9")] + AndroidIaMetadata, + + /// Android-IA System partition. + [Description("38F428E6-D326-425D-9140-6E0EA133647C")] + AndroidIaSystem, + + /// Android-IA Cache partition. + [Description("A893EF21-E428-470A-9E55-0668FD91A2D9")] + AndroidIaCache, + + /// Android-IA Data partition. + [Description("DC76DDA9-5AC1-491C-AF42-A82591580C0D")] + AndroidIaData, + + /// Android-IA Persistent partition. + [Description("EBC597D0-2053-4B15-8B64-E0AAC75F4DB1")] + AndroidIaPersistent, + + /// Android-IA Vendor partition. + [Description("C5A0AEEC-13EA-11E5-A1B1-001E67CA0C3C")] + AndroidIaVendor, + + /// Android-IA Config partition. + [Description("BD59408B-4514-490D-BF12-9878D963F378")] + AndroidIaConfig, + + /// Android-IA Factory partition. + [Description("8F68CC74-C5E5-48DA-BE91-A0C8C15E9C80")] + AndroidIaFactory, + + /// Android-IA Factory (Alternate) partition. + [Description("9FDAA6EF-4B3F-40D2-BA8D-BFF16BFB887B")] + AndroidIaFactoryAlternate, + + /// Android-IA Tertiary partition. + [Description("767941D0-2085-11E3-AD3B-6CFDB94711E9")] + AndroidIaTertiary, + + /// Android-IA OEM partition. + [Description("AC6D7924-EB71-4DF8-B48D-E267B27148FF")] + AndroidIaOem, + + #endregion // Android-IA + + + #region ONIE + + /// Open Network Install Environment (ONIE) Boot partition. + [Description("7412F7D5-A156-4B13-81DC-867174929325")] + OnieBoot, + + /// Open Network Install Environment (ONIE) Config partition. + [Description("D4E6E2CD-4469-46F3-B5CB-1BFF57AFC149")] + OnieConfig, + + #endregion // ONIE + + + #region PowerPC + + /// PowerPC PReP Boot partition. + [Description("9E1A2D38-C612-4316-AA26-8B49521E5A8B")] + PowerPcPrepBoot, + + #endregion // PowerPC + + + #region freedesktop.org OSes (Linux, etc.) + + /// Shared boot loader configuration partition. + [Description("BC13C2FF-59E6-4262-A352-B275FD6F7172")] + SharedBootloaderConfiguration, + + #endregion // freedesktop.org OSes (Linux, etc.) + + + #region Atari TOS + + /// Atari TOS Basic data (GEM, BGM, F32) partition. + [Description("734E5AFE-F61A-11E6-BC64-92361F002671")] + AtariTosBasicData + + #endregion // Atari TOS } } From f48d3702c27e74e3bf22214801154ebb0ca61e2d Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 28 Feb 2018 15:32:56 +0100 Subject: [PATCH 062/133] Code improvement, work in progress. --- ...reateSymbolicLink_And_GetLinkTargetInfo.cs | 2 +- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 7 +- .../Junctions, Links/Device.GetLinkTarget.cs | 2 +- .../Device.GetStorageAdapterInfo.cs | 2 +- .../Device.GetStorageDeviceInfo.cs | 4 +- .../Device.GetStoragePartitionInfo.cs | 9 +- .../File.EnumerateAlternateDataStreams.cs | 2 +- .../File Class/File.GetChangeTime.cs | 2 +- .../File Class/File.GetFileIdInfo.cs | 2 +- .../Link Stream/BackupFileStream.cs | 2 +- .../Filesystem/Native Other/DISK_EXTENT.cs | 18 +- .../DRIVE_LAYOUT_INFORMATION_EX.cs | 5 +- .../DRIVE_LAYOUT_INFORMATION_GPT.cs | 5 +- .../DRIVE_LAYOUT_INFORMATION_MBR.cs | 5 +- .../Native Other/DiskPartitionType.cs | 14 +- .../Native Other/MountPointReparseBuffer.cs | 11 +- .../Native Other/PARTITION_INFORMATION_EX.cs | 5 +- .../Native Other/PARTITION_INFORMATION_MBR.cs | 5 +- .../Native Other/PARTITION_STYLE.cs | 5 +- .../STORAGE_ADAPTER_DESCRIPTOR.cs | 5 +- .../Native Other/STORAGE_BUS_TYPE.cs | 5 +- .../Native Other/STORAGE_MEDIA_TYPE.cs | 5 +- .../Native Other/STORAGE_PROPERTY_ID.cs | 5 +- .../Native Other/STORAGE_QUERY_TYPE.cs | 5 +- .../Native Other/SymbolicLinkReparseBuffer.cs | 23 +- .../DiskPartitionType.cs | 74 +++++-- .../PartitionType..cs | 201 ++++++++++++++++++ .../Network/Host Class/Host.DFS.GetDfsInfo.cs | 2 +- .../Host Class/Host.SMB.GetNetStatistics.cs | 2 +- .../Host Class/Host.SMB.GetShareInfo.cs | 8 +- AlphaFS/Network/Host Class/Host.cs | 2 +- .../SafeNativeMemoryBufferHandle.cs | 57 ++--- 32 files changed, 352 insertions(+), 149 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateSymbolicLink_And_GetLinkTargetInfo.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateSymbolicLink_And_GetLinkTargetInfo.cs index 27e44d392..0e0088314 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateSymbolicLink_And_GetLinkTargetInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateSymbolicLink_And_GetLinkTargetInfo.cs @@ -84,7 +84,7 @@ private void File_CreateSymbolicLink_And_GetLinkTargetInfo(bool isNetwork) UnitTestConstants.Dump(new System.IO.FileInfo(fileLink), -17); var alphaFSFileInfo = new Alphaleonis.Win32.Filesystem.FileInfo(fileLink); - UnitTestConstants.Dump(alphaFSFileInfo.EntryInfo, -17); + UnitTestConstants.Dump(alphaFSFileInfo.EntryInfo, -19); Assert.AreEqual(System.IO.File.Exists(alphaFSFileInfo.FullName), alphaFSFileInfo.Exists); Assert.IsFalse(alphaFSFileInfo.EntryInfo.IsDirectory); diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index db3f0b0c4..5039c9bef 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -42,14 +42,9 @@ public static partial class Device var lastError = Marshal.GetLastWin32Error(); - - // https://stackoverflow.com/questions/19825910/get-size-of-volume-on-windows - // https://stackoverflow.com/questions/327718/how-to-list-physical-disks - // https://github.com/Invoke-IR/PowerForensics/blob/master/src/PowerForensicsCore/src/PowerForensics.BootSectors/GuidPartitionTable.cs - if (success) { - numberOfExtents = safeBuffer.PtrToStructure(0).NumberOfExtents; + numberOfExtents = safeBuffer.ReadInt32(); var diskExtent = new NativeMethods.DISK_EXTENT[numberOfExtents]; diff --git a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs index 9073da111..a2493073b 100644 --- a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs +++ b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs @@ -38,7 +38,7 @@ internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, stri { using (var safeBuffer = GetLinkTargetData(safeHandle, reparsePath)) { - var header = safeBuffer.PtrToStructure(0); + var header = safeBuffer.PtrToStructure(); var marshalReparseBuffer = (int)Marshal.OffsetOf(typeof(NativeMethods.ReparseDataBufferHeader), "data"); diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs index 52de8f197..1a1d37b2e 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs @@ -129,7 +129,7 @@ private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle saf if (isRetry && !safeHandleRetry.IsClosed) safeHandleRetry.Close(); - return new StorageAdapterInfo(safeBuffer.PtrToStructure(0)); + return new StorageAdapterInfo(safeBuffer.PtrToStructure()); } } } diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs index decaf0920..0b1a86fac 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs @@ -105,7 +105,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri else using (safeBuffer) - storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure(0)); + storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure()); } @@ -168,7 +168,7 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH } - var deviceDescriptor = safeBuffer.PtrToStructure(0); + var deviceDescriptor = safeBuffer.PtrToStructure(); storageDeviceInfo = new StorageDeviceInfo diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs index 0eb4bfdbc..eaf9ed3bf 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs @@ -53,8 +53,9 @@ internal static StoragePartitionInfo GetStoragePartitionInfoCore(string devicePa return GetStoragePartitionInfoNative(safeHandle, devicePath); } - + + /// Retrieves information about the number of partitions on a disk and the features of each partition. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandle, string pathToDevice) { @@ -102,7 +103,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 - var drive = safeBuffer.PtrToStructure(0); + var drive = safeBuffer.PtrToStructure(); var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; @@ -138,7 +139,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative0(SafeFileHandl if (success) { - var drive = safeBuffer.PtrToStructure(0); + var drive = safeBuffer.PtrToStructure(); var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; @@ -170,7 +171,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative0(SafeFileHandl } - /// Gets the disk geometry extended information + /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeHandle, string pathForException) { var bufferSize = 128; diff --git a/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs b/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs index 527db2781..b04d02ad2 100644 --- a/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs +++ b/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs @@ -106,7 +106,7 @@ internal static IEnumerable EnumerateAlternateDataStrea while (true) { - yield return new AlternateDataStreamInfo(pathLp, buffer.PtrToStructure(0)); + yield return new AlternateDataStreamInfo(pathLp, buffer.PtrToStructure()); var success = NativeMethods.FindNextStreamW(safeHandle, buffer); diff --git a/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs b/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs index 0216a59f3..e76a92c28 100644 --- a/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs +++ b/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs @@ -200,7 +200,7 @@ internal static DateTime GetChangeTimeCore(KernelTransaction transaction, SafeFi safeBuffer.StructureToPtr(fbi, true); - var changeTime = safeBuffer.PtrToStructure(0).ChangeTime; + var changeTime = safeBuffer.PtrToStructure().ChangeTime; return getUtc ? DateTime.FromFileTimeUtc(changeTime) : DateTime.FromFileTime(changeTime); diff --git a/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs b/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs index 27dc94b03..1bde6a15c 100644 --- a/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs +++ b/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs @@ -116,7 +116,7 @@ internal static FileIdInfo GetFileIdInfoCore(KernelTransaction transaction, stri if (!success) NativeError.ThrowException(lastError, path); - return new FileIdInfo(safeBuffer.PtrToStructure(0)); + return new FileIdInfo(safeBuffer.PtrToStructure()); } } diff --git a/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs b/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs index 05af68afb..6e361014e 100644 --- a/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs +++ b/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs @@ -590,7 +590,7 @@ public BackupStreamInfo ReadStreamInfo() throw new IOException(Resources.Read_Incomplete_Header); - var streamID = hBuf.PtrToStructure(0); + var streamID = hBuf.PtrToStructure(); var nameLength = (uint) Math.Min(streamID.dwStreamNameSize, hBuf.Capacity); diff --git a/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs b/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs index cf1282d49..27c5b11de 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs @@ -25,26 +25,22 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Represents a disk extent. + /// Represents a disk extent. + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct DISK_EXTENT { /// The number of the disk that contains this extent. This is the same number that is used to construct the name of the disk, /// for example, the X in "\\.\PhysicalDriveX" or "\\?\HarddiskX". - [MarshalAs(UnmanagedType.U4)] public readonly int DiskNumber; + [MarshalAs(UnmanagedType.U4)] public readonly uint DiskNumber; /// The offset from the beginning of the disk to the extent, in bytes. - [MarshalAs(UnmanagedType.U8)] public readonly long StartingOffset; + [MarshalAs(UnmanagedType.I8)] public readonly long StartingOffset; /// The number of bytes in this extent. - [MarshalAs(UnmanagedType.U8)] public readonly long ExtentLength; - } - - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct DiskExtentsBeforeArray - { - [MarshalAs(UnmanagedType.U4)] public readonly int NumberOfExtents; + [MarshalAs(UnmanagedType.I8)] public readonly long ExtentLength; } } } diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs index da3a391ab..ee7ab1f27 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs @@ -25,11 +25,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Contains extended information about a drive's partitions. - /// + /// Contains extended information about a drive's partitions. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] internal struct DRIVE_LAYOUT_INFORMATION_EX { diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs index 72be49f56..289568371 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs @@ -26,11 +26,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Contains information about a drive's GUID partition table (GPT) partitions. - /// + /// Contains information about a drive's GUID partition table (GPT) partitions. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct DRIVE_LAYOUT_INFORMATION_GPT { diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs index 8ece0fcaf..a90523188 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs @@ -25,11 +25,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Provides information about a drive's master boot record (MBR) partitions. - /// + /// Provides information about a drive's master boot record (MBR) partitions. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct DRIVE_LAYOUT_INFORMATION_MBR { diff --git a/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs b/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs index ee1e8aee9..3f8294d0f 100644 --- a/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs +++ b/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs @@ -29,25 +29,25 @@ internal static partial class NativeMethods /// internal enum DiskPartitionType : byte { - /// An unused entry partition. + /// Unused partition entry. PARTITION_ENTRY_UNUSED = 0, - /// A FAT12 file system partition. + /// DOS FAT12 primary partition or logical drive (fewer than 32,680 sectors in the volume). PARTITION_FAT_12 = 1, - /// A FAT16 file system partition. + /// DOS 3.0+ FAT16 partition or logical drive (32,680�65,535 sectors or 16 MB�33 MB). PARTITION_FAT_16 = 4, - /// An extended partition. + /// DOS 3.3+ Extended partition. PARTITION_EXTENDED = 5, - /// An IFS (Installable File System) partition. + /// Installable File System (IFS). NTFS partition or logical drive. PARTITION_IFS = 7, - /// A FAT32 file system partition. + /// FAT32 partition or logical drive. PARTITION_FAT32 = 11, - /// An LDM (Logical Disk Manager) partition. + /// LDM (Logical Disk Manager) partition. PARTITION_LDM = 66, /// An NTFT partition. diff --git a/AlphaFS/Filesystem/Native Other/MountPointReparseBuffer.cs b/AlphaFS/Filesystem/Native Other/MountPointReparseBuffer.cs index c9c5837a9..c0db9a9db 100644 --- a/AlphaFS/Filesystem/Native Other/MountPointReparseBuffer.cs +++ b/AlphaFS/Filesystem/Native Other/MountPointReparseBuffer.cs @@ -29,19 +29,20 @@ internal static partial class NativeMethods internal struct MountPointReparseBuffer { /// Offset, in bytes, of the substitute name string in the PathBuffer array. - public ushort SubstituteNameOffset; + [MarshalAs(UnmanagedType.U2)] public ushort SubstituteNameOffset; /// Length, in bytes, of the substitute name string. If this string is null-terminated, SubstituteNameLength does not include space for the null character. - public ushort SubstituteNameLength; + [MarshalAs(UnmanagedType.U2)] public ushort SubstituteNameLength; /// Offset, in bytes, of the print name string in the PathBuffer array. - public ushort PrintNameOffset; + [MarshalAs(UnmanagedType.U2)] public ushort PrintNameOffset; /// Length, in bytes, of the print name string. If this string is null-terminated, PrintNameLength does not include space for the null character. - public ushort PrintNameLength; + [MarshalAs(UnmanagedType.U2)] public ushort PrintNameLength; /// A buffer containing the unicode-encoded path string. The path string contains the substitute name string and print name string. - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] public byte[] data; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] + public readonly byte[] data; } } } diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs index 509ef156d..623aa4afc 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs @@ -25,11 +25,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Contains partition information for standard AT-style master boot record (MBR) and Extensible Firmware Interface (EFI) disks. - /// + /// Contains partition information for standard AT-style master boot record (MBR) and Extensible Firmware Interface (EFI) disks. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] internal struct PARTITION_INFORMATION_EX { diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs index 3ae6be3f4..fbdbcee58 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs @@ -25,11 +25,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Contains partition information specific to master boot record (MBR) disks. - /// + /// Contains partition information specific to master boot record (MBR) disks. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct PARTITION_INFORMATION_MBR { diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs b/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs index be61fad9a..357034f4a 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs @@ -23,11 +23,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Represents the format of a partition. - /// + /// Represents the format of a partition. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// internal enum PARTITION_STYLE { /// Master boot record (MBR) format. This corresponds to standard AT-style MBR partitions. diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs b/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs index c15ee2072..c51363cc1 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs @@ -26,11 +26,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Used with the control code to retrieve the storage adapter descriptor data for a device. - /// + /// Used with the control code to retrieve the storage adapter descriptor data for a device. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct STORAGE_ADAPTER_DESCRIPTOR { diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs index c98d67a69..9f5772ca1 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs @@ -23,11 +23,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Provides a symbolic means of representing storage bus types. - /// + /// Provides a symbolic means of representing storage bus types. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// internal enum STORAGE_BUS_TYPE { /// Indicates an unknown bus type. diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs index dd785f75d..fe0defe47 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs @@ -23,11 +23,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Specifies various types of storage media. Parameters and members of type STORAGE_MEDIA_TYPE also accept values from the MEDIA_TYPE enumeration type. - /// + /// Specifies various types of storage media. Parameters and members of type STORAGE_MEDIA_TYPE also accept values from the MEDIA_TYPE enumeration type. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// public enum STORAGE_MEDIA_TYPE { /// Format is unknown. diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs index 4f3bee286..5eef2b0dd 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs @@ -23,11 +23,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Enumerates the possible values of the PropertyId member of the structure passed as input to the IOCTL_STORAGE_QUERY_PROPERTY request to retrieve the properties of a storage device or adapter. - /// + /// Enumerates the possible values of the PropertyId member of the structure passed as input to the IOCTL_STORAGE_QUERY_PROPERTY request to retrieve the properties of a storage device or adapter. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// public enum STORAGE_PROPERTY_ID { /// Indicates that the caller is querying for the device descriptor, . diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs index d027feed6..dd5c3c6b9 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs @@ -23,11 +23,10 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// Used by the structure passed to the IOCTL_STORAGE_QUERY_PROPERTY control code to indicate what information is returned about a property of a storage device or adapter. - /// + /// Used by the structure passed to the IOCTL_STORAGE_QUERY_PROPERTY control code to indicate what information is returned about a property of a storage device or adapter. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// public enum STORAGE_QUERY_TYPE { /// Instructs the driver to return an appropriate descriptor. diff --git a/AlphaFS/Filesystem/Native Other/SymbolicLinkReparseBuffer.cs b/AlphaFS/Filesystem/Native Other/SymbolicLinkReparseBuffer.cs index 299a03f70..11f470a9b 100644 --- a/AlphaFS/Filesystem/Native Other/SymbolicLinkReparseBuffer.cs +++ b/AlphaFS/Filesystem/Native Other/SymbolicLinkReparseBuffer.cs @@ -28,12 +28,23 @@ internal static partial class NativeMethods [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SymbolicLinkReparseBuffer { - public ushort SubstituteNameOffset; - public ushort SubstituteNameLength; - public ushort PrintNameOffset; - public ushort PrintNameLength; - public SymbolicLinkType Flags; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] public byte[] data; + /// Offset, in bytes, of the substitute name string in the PathBuffer array. + [MarshalAs(UnmanagedType.U2)] public readonly ushort SubstituteNameOffset; + + /// Length, in bytes, of the substitute name string. If this string is null-terminated, SubstituteNameLength does not include space for the null character. + [MarshalAs(UnmanagedType.U2)] public readonly ushort SubstituteNameLength; + + /// Offset, in bytes, of the print name string in the PathBuffer array. + [MarshalAs(UnmanagedType.U2)] public readonly ushort PrintNameOffset; + + /// Length, in bytes, of the print name string. If this string is null-terminated, PrintNameLength does not include space for the null character. + [MarshalAs(UnmanagedType.U2)] public readonly ushort PrintNameLength; + + [MarshalAs(UnmanagedType.U4)] public readonly SymbolicLinkType Flags; + + /// A buffer containing the unicode-encoded path string. The path string contains the substitute name string and print name string. + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] + public readonly byte[] data; } } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs index 244746f5c..b4294e594 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs @@ -24,13 +24,13 @@ namespace Alphaleonis.Win32.Filesystem { /// The following table identifies the valid partition types that are used by disk drivers. - /// http://www.win.tue.nl/~aeb/partitions/partition_types-1.html + /// https://technet.microsoft.com/en-us/library/cc739412.aspx public enum DiskPartitionType { - /// An unused entry partition. + /// Unused partition entry. UnusedEntry = NativeMethods.DiskPartitionType.PARTITION_ENTRY_UNUSED, - /// DOS 12-bit FAT partition. + /// DOS FAT12 primary partition or logical drive (fewer than 32,680 sectors in the volume). Fat12 = NativeMethods.DiskPartitionType.PARTITION_FAT_12, /// A XENIX root partition. @@ -41,46 +41,84 @@ public enum DiskPartitionType [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Xenix")] XenixUser = 3, - /// DOS 3.0+ 16-bit FAT partition (up to 32M). + /// DOS 3.0+ FAT16 partition or logical drive (32,680�65,535 sectors or 16 MB�33 MB). Fat16 = NativeMethods.DiskPartitionType.PARTITION_FAT_16, /// DOS 3.3+ Extended partition. Extended = NativeMethods.DiskPartitionType.PARTITION_EXTENDED, - /// DOS 3.31+ 16-bit FAT partition (over 32M). - Fat16Big = 6, + /// DOS 3.31+ BIGDOS FAT16 partition or logical drive (33 MB�4 GB). + Fat16B = 6, - /// OS/2 IFS (Installable File System) (e.g., HPFS) partition. + /// Installable File System (IFS). NTFS partition or logical drive. Ifs = NativeMethods.DiskPartitionType.PARTITION_IFS, - /// A FAT32 file system partition. + /// FAT32 partition or logical drive. Fat32 = NativeMethods.DiskPartitionType.PARTITION_FAT32, - /// A FAT32 XINT13 partition. - Fat32XInt13 = 12, + /// FAT32 partition or logical drive using BIOS INT 13h extensions. + Fat32Int13 = 12, - /// An XINT13 partition. - XInt13 = 14, + /// BIGDOS FAT16 partition or logical drive using BIOS INT 13h extensions + Fat16BInt13 = 14, - /// An XINT13 Extended partition. - XInt13Extended = 15, + /// Extended partition using BIOS INT 13h extensions + ExtendedInt13 = 15, - /// A PREP (Power PC Reference Platform) partition. + /// EISA partition or OEM partition + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Eisa")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Oem")] + EisaOem = 18, + + /// A PC PReP (Power PC Reference Platform) Boot partition. Prep = 65, - /// An LDM (Logical Disk Manager) partition. + /// LDM (Logical Disk Manager) Dynamic volume. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ldm")] Ldm = NativeMethods.DiskPartitionType.PARTITION_LDM, - /// A UNIX partition. + /// SCO Unix, ISC, UnixWare, AT+T System V/386, ix, MtXinu BSD 4.3 on Mach, GNU HURD. Unix = 99, /// An NTFT partition. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ntft")] Ntft = NativeMethods.DiskPartitionType.PARTITION_NTFT, + /// Power management hibernation partition. + PowerManagementHibernation = 132, + + /// Multidisk FAT16 volume created by using Windows NT 4.0 + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi")] + Fat16MultiDisk = 134, + + /// Multidisk NTFS volume created by using Windows NT 4.0 + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi")] + NtfsMultiDisk = 135, + + /// Laptop hibernation partition + LaptopHibernation = 160, + /// A valid NTFT partition. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ntft")] - ValidNtft = NativeMethods.DiskPartitionType.VALID_NTFT + ValidNtft = NativeMethods.DiskPartitionType.VALID_NTFT, + + /// Dell OEM partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Oem")] + DellOem = 222, + + /// IBM OEM partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Oem")] + IbmOem = 254, + + /// GPT partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] + Gpt = 238, + + /// EFI System partition on an MBR disk. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Efi")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr")] + EfiSystemOnMbr = 239 + } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs index 21176ab79..766b1d784 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs @@ -38,12 +38,14 @@ public enum PartitionType UnusedEntry, /// Legacy MBR partition. A partition that is sub-partitioned by a Master Boot Record; "partitions-inside-a-slice configuration". + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr")] [Description("024DEE41-33E7-11D3-9D69-0008C781F39F")] LegacyMbr, /// The partition is an EFI system partition. /// This value can be set for basic and dynamic disks. /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Efi")] [Description("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")] EfiSystem, @@ -52,6 +54,7 @@ public enum PartitionType BiosBoot, /// Intel Fast Flash (iFFS, Intel Rapid Start technology) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Iffs")] [Description("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593")] Iffs, @@ -122,10 +125,18 @@ public enum PartitionType #region HP-UX /// HP-UX Data partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ux")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hp")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ux")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Hp")] [Description("75894C1E-3AEB-11D3-B7C1-7B03A0000000")] HpUxData, /// HP-UX Service partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ux")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ux")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hp")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Hp")] [Description("E2A1E728-32E3-11D6-A682-7B03A0000000")] HpUxService, @@ -151,10 +162,12 @@ public enum PartitionType LinuxRootX8664, /// Linux Root (32bit ARM) partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "bit")] [Description("69DAD710-2CE4-4E3C-B16C-21A1D49ABED3")] LinuxRoot32bitArm, /// Linux Root (64bit ARM/AArch64) partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "bit")] [Description("B921B045-1DF0-41C3-AF44-4C6F280D3FAE")] LinuxRoot64bitArm, @@ -163,6 +176,7 @@ public enum PartitionType LinuxSwap, /// Linux Logical Volume Manager(LVM) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lvm")] [Description("E6D6D379-F507-44C2-A23C-238F2A3DF928")] LinuxLvm, @@ -171,10 +185,13 @@ public enum PartitionType LinuxHome, /// Linux /srv (server data) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Srv")] [Description("3B8F8425-20E0-4F3B-907F-1A25A76F98E8")] LinuxSrv, /// Linux Plain dm-crypt partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] [Description("7FFEC5C9-2D00-49B7-8941-3EA10A5586B7")] LinuxPlainDmCrypt, @@ -183,6 +200,7 @@ public enum PartitionType LinuxLuks, /// Linux Reserved partition. + [SuppressMessage("Microsoft.Naming", "CA1700:DoNotNameEnumValuesReserved")] [Description("8DA63339-0007-60C0-C436-083AC8230908")] LinuxReserved, @@ -192,26 +210,35 @@ public enum PartitionType #region FreeBSD /// FreeBSD Boot partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("83BD6B9D-7F41-11DC-BE0B-001560B84F0F")] FreeBsdBoot, /// FreeBSD Data partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("516E7CB4-6ECF-11D6-8FF8-00022D09712B")] FreeBsdData, /// FreeBSD Swap partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("516E7CB5-6ECF-11D6-8FF8-00022D09712B")] FreeBsdSwap, /// FreeBSD Unix File System (UFS) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ufs")] [Description("516E7CB6-6ECF-11D6-8FF8-00022D09712B")] FreeBsdUfs, /// FreeBSD Vinum Volume Manager partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vvm")] [Description("516E7CB8-6ECF-11D6-8FF8-00022D09712B")] FreeBsdVvm, /// FreeBSD ZFS partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Zfs")] [Description("516E7CBA-6ECF-11D6-8FF8-00022D09712B")] FreeBsdZfs, @@ -221,58 +248,92 @@ public enum PartitionType #region MacOS Darwin /// OSX Hierarchical File System Plus (HFS+) partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hfs")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] [Description("48465300-0000-11AA-AA11-00306543ECAC")] OsXHfs, /// OSX Apple APFS partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Apfs")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("7C3457EF-0000-11AA-AA11-00306543ECAC")] OsXAppleApfs, /// OSX Apple UFS partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ufs")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] [Description("55465300-0000-11AA-AA11-00306543ECAC")] OsXAppleUfs, /// OSX ZFS partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Zfs")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("6A898CC3-1DD2-11B2-99A6-080020736631")] OsXZfs, /// OSX Apple RAID partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] [Description("52414944-0000-11AA-AA11-00306543ECAC")] OsXAppleRaid, /// OSX Apple RAID offline partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("52414944-5F4F-11AA-AA11-00306543ECAC")] OsXAppleRaidOffline, /// OSX Apple Boot (Recovery HD) partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] [Description("426F6F74-0000-11AA-AA11-00306543ECAC")] OsXBootRecovery, /// OSX Apple Label partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("C616265-6C00-11AA-AA11-00306543ECAC")] OsXLabel, /// OSX Apple TV Recovery partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Tv")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Tv")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("5265636F-7665-11AA-AA11-00306543ECAC")] OsXTvRecovery, /// OSX Apple Core Storage (i.e. Lion FileVault) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("53746F72-6167-11AA-AA11-00306543ECAC")] OsXCoreStorage, /// OSX SoftRAID_Status partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("B6FA30DA-92D2-4A9A-96F1-871EC6486200")] OsXSoftRaidStatus, /// OSX SoftRAID_Scratch partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("2E313465-19B9-463F-8126-8A7993773801")] OsXSoftRaidScratch, /// OSX SoftRAID_Volume partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("FA709C7E-65B1-4593-BFD5-E71D61DE9B02")] OsXSoftRaidVolume, /// OSX SoftRAID_Cache partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] [Description("BBBA6DF5-F46F-4A89-8F59-8765B2727503")] OsXSoftRaidCache, @@ -298,6 +359,7 @@ public enum PartitionType SolarisBackup, /// Solaris /usr partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usr")] [Description("6A898CC3-1DD2-11B2-99A6-080020736631")] SolarisUsr, @@ -314,22 +376,27 @@ public enum PartitionType SolarisAlternateSector, /// Solaris Reserved partition. + [SuppressMessage("Microsoft.Naming", "CA1700:DoNotNameEnumValuesReserved")] [Description("6A945A3B-1DD2-11B2-99A6-080020736631")] SolarisReserved1, /// Solaris Reserved partition. + [SuppressMessage("Microsoft.Naming", "CA1700:DoNotNameEnumValuesReserved")] [Description("6A9630D1-1DD2-11B2-99A6-080020736631")] SolarisReserved2, /// Solaris Reserved partition. + [SuppressMessage("Microsoft.Naming", "CA1700:DoNotNameEnumValuesReserved")] [Description("6A980767-1DD2-11B2-99A6-080020736631")] SolarisReserved3, /// Solaris Reserved partition. + [SuppressMessage("Microsoft.Naming", "CA1700:DoNotNameEnumValuesReserved")] [Description("6A96237F-1DD2-11B2-99A6-080020736631")] SolarisReserved4, /// Solaris Reserved partition. + [SuppressMessage("Microsoft.Naming", "CA1700:DoNotNameEnumValuesReserved")] [Description("6A8D2AC7-1DD2-11B2-99A6-080020736631")] SolarisReserved5, @@ -339,26 +406,34 @@ public enum PartitionType #region NetBSD /// NetBSD Swap partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("6A82CB45-1DD2-11B2-99A6-080020736631")] NetBsdSwap, /// NetBSD Fast File System (FFS) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ffs")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("49F48D5A-B10E-11DC-B99B-0019D1879648")] NetBsdFfs, /// NetBSD Log-Structured File System (LFS) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lfs")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("49F48D82-B10E-11DC-B99B-0019D1879648")] NetBsdLfs, /// NetBSD RAID partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("49F48DAA-B10E-11DC-B99B-0019D1879648")] NetBsdRaid, /// NetBSD Concatenated partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("2DB519C4-B10F-11DC-B99B-0019D1879648")] NetBsdConcatenated, /// NetBSD Encrypted partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("2DB519EC-B10F-11DC-B99B-0019D1879648")] NetBsdEncrypted, @@ -368,14 +443,25 @@ public enum PartitionType #region Chrome OS /// Chrome OS Kernel partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Chromse")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("FE3A2A5D-4F32-41A7-B725-ACCC3285A309")] ChromseOsKernel, /// Chrome OS RootFS partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fs")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Chromse")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Fs")] [Description("3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC")] ChromseOsRootFs, /// Chrome OS (future use) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Chromse")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("2E0A753D-9E48-43B0-8337-B15192CB1B5E")] ChromseOsFutureUse, @@ -385,6 +471,7 @@ public enum PartitionType #region Haiku /// Haiku Be File System (BFS) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bfs")] [Description("42465331-3BA3-10F1-802A-4861696B7521")] HaikuBfs, @@ -394,26 +481,35 @@ public enum PartitionType #region MidnightBSD /// MidnightBSD Boot partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("85D5E45E-237C-11E1-B4B3-E89A8F7FC3A7")] MidnightBsdBoot, /// MidnightBSD Data partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("85D5E45A-237C-11E1-B4B3-E89A8F7FC3A7")] MidnightBsdData, /// MidnightBSD Swap partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("85D5E45B-237C-11E1-B4B3-E89A8F7FC3A7")] MidnightBsdSwap, /// MidnightBSD Unix File System (UFS) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ufs")] [Description("0394EF8B-237E-11E1-B4B3-E89A8F7FC3A7")] MidnightBsdUfs, /// MidnightBSD Vinum Volume Manager partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vvm")] [Description("85D5E45C-237C-11E1-B4B3-E89A8F7FC3A7")] MidnightBsdVvm, /// MidnightBSD ZFS partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Zfs")] [Description("85D5E45D-237C-11E1-B4B3-E89A8F7FC3A7")] MidnightBsdZfs, @@ -423,98 +519,150 @@ public enum PartitionType #region Ceph /// Ceph journal partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("45B0969E-9B03-4F30-B4C6-B4B80CEFF106")] CephJournal, /// Ceph dm-crypt journal partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] [Description("45B0969E-9B03-4F30-B4C6-5EC00CEFF106")] CephDmCryptJournal, /// Ceph OSD partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Osd")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("4FBD7E29-9D25-41B8-AFD0-062C0CEFF05D")] CephOsd, /// Ceph dm-crypt OSD partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Osd")] [Description("4FBD7E29-9D25-41B8-AFD0-5EC00CEFF05D")] CephDmCryptOsd, /// Ceph disk in creation partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("89C57F98-2FE5-4DC0-89C1-F3AD0CEFF2BE")] CephDiskInCreation, /// Ceph dm-crypt disk in creation partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] [Description("89C57F98-2FE5-4DC0-89C1-5EC00CEFF2BE")] CephDmCryptDiskInCreation, /// Ceph block partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("CAFECAFE-9B03-4F30-B4C6-B4B80CEFF106")] CephBlock, /// Ceph block DB partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("30CD0809-C2B2-499C-8879-2D6B78529876")] CephBlockDb, /// Ceph block write-ahead log partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("5CE17FCE-4087-4169-B7FF-056CC58473F9")] CephBlockWriteAheadLog, /// Ceph lockbox for dm-crypt keys partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] [Description("FB3AABF9-D25F-47CC-BF5E-721D1816496B")] CephDmCryptKeysLockbox, /// Ceph multipath OSD partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Osd")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("4FBD7E29-8AE0-4982-BF9D-5A8D867AF560")] CephMultipathOsd, /// Ceph multipath journal partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("45B0969E-8AE0-4982-BF9D-5A8D867AF560")] CephMultipathJournal, /// Ceph multipath block partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("CAFECAFE-8AE0-4982-BF9D-5A8D867AF560")] CephMultipathBlock1, /// Ceph multipath block partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("7F4A666A-16F3-47A2-8445-152EF4D03F6C")] CephMultipathBlock2, /// Ceph multipath block DB partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("EC6D6385-E346-45DC-BE91-DA2A7C8B3261")] CephMultipathBlockDb, /// Ceph multipath block write-ahead log partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] [Description("01B41E1B-002A-453C-9F17-88793989FF8F")] CephMultipathBlockWriteAheadLog, /// Ceph dm-crypt block partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] [Description("CAFECAFE-9B03-4F30-B4C6-5EC00CEFF106")] CephDmCryptBlock, /// Ceph dm-crypt block DB partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] [Description("93B0052D-02D9-4D8A-A43B-33A3EE4DFBC3")] CephDmCryptBlockDb, /// Ceph dm-crypt block write-ahead log partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] [Description("306E8683-4FE2-4330-B7C0-00A917C16966")] CephDmCryptBlockWriteAheadLog, /// Ceph dm-crypt LUKS journal partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] [Description("45B0969E-9B03-4F30-B4C6-35865CEFF106")] CephDmCryptLuksJournal, /// Ceph dm-crypt LUKS block partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] [Description("CAFECAFE-9B03-4F30-B4C6-35865CEFF106")] CephDmCryptLuksBlock, /// Ceph dm-crypt LUKS block DB partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] [Description("166418DA-C469-4022-ADF4-B30AFD37F176")] CephDmCryptLuksBlockDb, /// Ceph dm-crypt LUKS block write-ahead log partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] [Description("166418DA-C469-4022-ADF4-B30AFD37F176")] CephDmCryptLuksBlockWriteAheadLog, /// Ceph dm-crypt LUKS OSD partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ceph")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Osd")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dm")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dm")] [Description("166418DA-C469-4022-ADF4-B30AFD37F176")] CephDmCryptLuksOsd, @@ -524,6 +672,7 @@ public enum PartitionType #region OpenBSD /// OpenBSD Data partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bsd")] [Description("824CC7A0-36A8-11E3-890A-952519AD3F61")] OpenBsdData, @@ -533,6 +682,7 @@ public enum PartitionType #region QNX /// QNX Power-safe (QNX6) file system partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Qnx")] [Description("CEF5A9AD-73BC-4601-89F3-CDEEEEE321A1")] Qnx6, @@ -551,14 +701,25 @@ public enum PartitionType #region VMware ESX /// VMware ESX vmkcore (coredump) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Esx")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vm")] [Description("9D275380-40AD-11DB-BF97-000C2911D1B8")] VmWareEsxCore, /// VMware ESX Virtual Machine File System (VMFS) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vm")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vmfs")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Esx")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vm")] [Description("AA31E02A-400F-11DB-9590-000C2911D1B8")] VmWareEsxVmfs, /// VMware ESX Reserved partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Esx")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vm")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vm")] + [SuppressMessage("Microsoft.Naming", "CA1700:DoNotNameEnumValuesReserved")] [Description("9198EFFC-31C0-11DB-8F78-000C2911D1B8")] VmWareEsxReserved, @@ -568,66 +729,101 @@ public enum PartitionType #region Android-IA /// Android-IA Bootloader partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bootloader")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("2568845D-2332-4675-BC39-8FA5A4748D15")] AndroidIaBootloader, /// Android-IA Bootloader2 partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bootloader")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("114EAFFE-1552-4022-B26E-9B053604CF84")] AndroidIaBootloader2, /// Android-IA Boot partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("49A4D17F-93A3-45C1-A0DE-F50B2EBE2599")] AndroidIaBoot, /// Android-IA Recovery partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("4177C722-9E92-4AAB-8644-43502BFD5506")] AndroidIaRecovery, /// Android-IA Misc partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("EF32A33B-A409-486C-9141-9FFB711F6266")] AndroidIaMisc, /// Android-IA Metadata partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("20AC26BE-20B7-11E3-84C5-6CFDB94711E9")] AndroidIaMetadata, /// Android-IA System partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("38F428E6-D326-425D-9140-6E0EA133647C")] AndroidIaSystem, /// Android-IA Cache partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("A893EF21-E428-470A-9E55-0668FD91A2D9")] AndroidIaCache, /// Android-IA Data partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("DC76DDA9-5AC1-491C-AF42-A82591580C0D")] AndroidIaData, /// Android-IA Persistent partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("EBC597D0-2053-4B15-8B64-E0AAC75F4DB1")] AndroidIaPersistent, /// Android-IA Vendor partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("C5A0AEEC-13EA-11E5-A1B1-001E67CA0C3C")] AndroidIaVendor, /// Android-IA Config partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("BD59408B-4514-490D-BF12-9878D963F378")] AndroidIaConfig, /// Android-IA Factory partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("8F68CC74-C5E5-48DA-BE91-A0C8C15E9C80")] AndroidIaFactory, /// Android-IA Factory (Alternate) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("9FDAA6EF-4B3F-40D2-BA8D-BFF16BFB887B")] AndroidIaFactoryAlternate, /// Android-IA Tertiary partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("767941D0-2085-11E3-AD3B-6CFDB94711E9")] AndroidIaTertiary, /// Android-IA OEM partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Oem")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] [Description("AC6D7924-EB71-4DF8-B48D-E267B27148FF")] AndroidIaOem, @@ -637,10 +833,12 @@ public enum PartitionType #region ONIE /// Open Network Install Environment (ONIE) Boot partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Onie")] [Description("7412F7D5-A156-4B13-81DC-867174929325")] OnieBoot, /// Open Network Install Environment (ONIE) Config partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Onie")] [Description("D4E6E2CD-4469-46F3-B5CB-1BFF57AFC149")] OnieConfig, @@ -650,6 +848,7 @@ public enum PartitionType #region PowerPC /// PowerPC PReP Boot partition. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pc")] [Description("9E1A2D38-C612-4316-AA26-8B49521E5A8B")] PowerPcPrepBoot, @@ -659,6 +858,7 @@ public enum PartitionType #region freedesktop.org OSes (Linux, etc.) /// Shared boot loader configuration partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bootloader")] [Description("BC13C2FF-59E6-4262-A352-B275FD6F7172")] SharedBootloaderConfiguration, @@ -668,6 +868,7 @@ public enum PartitionType #region Atari TOS /// Atari TOS Basic data (GEM, BGM, F32) partition. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Tos")] [Description("734E5AFE-F61A-11E6-BC64-92361F002671")] AtariTosBasicData diff --git a/AlphaFS/Network/Host Class/Host.DFS.GetDfsInfo.cs b/AlphaFS/Network/Host Class/Host.DFS.GetDfsInfo.cs index 4cb9c5df9..a08f59db2 100644 --- a/AlphaFS/Network/Host Class/Host.DFS.GetDfsInfo.cs +++ b/AlphaFS/Network/Host Class/Host.DFS.GetDfsInfo.cs @@ -86,7 +86,7 @@ internal static DfsInfo GetDfsInfoCore(bool getFromClient, string dfsName, strin 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(0)); + return new DfsInfo(safeBuffer.PtrToStructure()); throw new NetworkInformationException((int)lastError); } diff --git a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs index 9325a025f..40f48180f 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs @@ -109,7 +109,7 @@ internal static T GetNetStatisticsNative(bool isServer, string hostName) throw new NetworkInformationException((int) lastError); - return safeBuffer.PtrToStructure(0); + return safeBuffer.PtrToStructure(); } } } diff --git a/AlphaFS/Network/Host Class/Host.SMB.GetShareInfo.cs b/AlphaFS/Network/Host Class/Host.SMB.GetShareInfo.cs index 484092644..b8272cc1d 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.GetShareInfo.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.GetShareInfo.cs @@ -119,22 +119,22 @@ internal static ShareInfo GetShareInfoCore(ShareInfoLevel shareLevel, string hos switch (shareLevel) { case ShareInfoLevel.Info1005: - return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure(0)) + return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure()) { NetFullPath = Path.CombineCore(false, Path.UncPrefix + stripUnc, share) }; case ShareInfoLevel.Info503: - return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure(0)); + return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure()); case ShareInfoLevel.Info2: - return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure(0)); + return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure()); case ShareInfoLevel.Info1: - return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure(0)); + return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure()); } break; diff --git a/AlphaFS/Network/Host Class/Host.cs b/AlphaFS/Network/Host Class/Host.cs index 5f308af22..f08277983 100644 --- a/AlphaFS/Network/Host Class/Host.cs +++ b/AlphaFS/Network/Host Class/Host.cs @@ -308,7 +308,7 @@ internal static NativeMethods.REMOTE_NAME_INFO GetRemoteNameInfoCore(string path lastError = NativeMethods.WNetGetUniversalName(path, 2, buffer, out bufferSize); if (lastError == Win32Errors.NO_ERROR) - return buffer.PtrToStructure(0); + return buffer.PtrToStructure(); } } while (lastError == Win32Errors.ERROR_MORE_DATA); diff --git a/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs b/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs index 590f3d012..b5f5404be 100644 --- a/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs +++ b/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs @@ -197,7 +197,7 @@ public void WriteInt32(int offset, short value) Marshal.WriteInt32(handle, offset, value); } - public void WriteInt32(int value) + public void WriteInt32(int value = 0) { Marshal.WriteInt32(handle, value); } @@ -207,7 +207,7 @@ public void WriteInt64(int offset, long value) Marshal.WriteInt64(handle, offset, value); } - public void WriteInt64(long value) + public void WriteInt64(long value = 0) { Marshal.WriteInt64(handle, value); } @@ -217,7 +217,7 @@ public void WriteByte(int offset, byte value) Marshal.WriteByte(handle, offset, value); } - public void WriteByte(byte value) + public void WriteByte(byte value = 0) { Marshal.WriteByte(handle, value); } @@ -237,52 +237,31 @@ public void WriteIntPtr(IntPtr value) #region Read - public byte ReadByte() - { - return Marshal.ReadByte(handle); - } - - public byte ReadByte(int offset) + public byte ReadByte(int offset = 0) { return Marshal.ReadByte(handle, offset); } - public short ReadInt16() - { - return Marshal.ReadInt16(handle); - } - - public short ReadInt16(int offset) + + public short ReadInt16(int offset = 0) { return Marshal.ReadInt16(handle, offset); } - public int ReadInt32() - { - return Marshal.ReadInt32(handle); - } - - public int ReadInt32(int offset) + + public int ReadInt32(int offset = 0) { return Marshal.ReadInt32(handle, offset); } - public long ReadInt64() - { - return Marshal.ReadInt64(handle); - } - - public long ReadInt64(int offset) + + public long ReadInt64(int offset = 0) { return Marshal.ReadInt64(handle, offset); } - public IntPtr ReadIntPtr() - { - return Marshal.ReadIntPtr(handle); - } - - public IntPtr ReadIntPtr(int offset) + + public IntPtr ReadIntPtr(int offset = 0) { return Marshal.ReadIntPtr(handle, offset); } @@ -300,15 +279,7 @@ public void StructureToPtr(object structure, bool deleteOld) /// Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type. /// A managed object containing the data pointed to by the ptr parameter. - public T PtrToStructure() - { - return PtrToStructure(0); - } - - - /// Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type. - /// A managed object containing the data pointed to by the ptr parameter. - public T PtrToStructure(int offset) + public T PtrToStructure(int offset = 0) { return (T) Marshal.PtrToStructure(new IntPtr(handle.ToInt64() + offset), typeof(T)); } @@ -316,7 +287,7 @@ public T PtrToStructure(int offset) /// Allocates a managed System.String and copies a specified number of characters from an unmanaged ANSI string into it. /// A managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null. - public string PtrToStringAnsi(int offset) + public string PtrToStringAnsi(int offset = 0) { return Marshal.PtrToStringAnsi(new IntPtr(handle.ToInt64() + offset)); } From f21ea9fdeace7e77ea360cca26c164a6b789e2bd Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 2 Mar 2018 15:28:35 +0100 Subject: [PATCH 063/133] Code improvement, work in progress. --- .../Device.GetStorageAdapterInfo.cs | 7 +- .../Device.GetStorageDeviceInfo.cs | 10 +- .../Device.GetStoragePartitionInfo.cs | 18 ++-- AlphaFS/Device/StorageDeviceInfo.cs | 4 +- .../Native Other/DiskPartitionType.cs | 4 +- .../Native Other/STORAGE_DEVICE_NUMBER.cs | 8 +- AlphaFS/Filesystem/Shell32.cs | 4 - .../DiskPartitionType.cs | 4 +- .../StorageDeviceType.cs | 97 +++++++++---------- 9 files changed, 77 insertions(+), 79 deletions(-) diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs index 1a1d37b2e..c417ca20b 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs @@ -60,9 +60,10 @@ public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) /// /// /// - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string (when is set to ). + /// A disk path such as: "\\.\PhysicalDrive0"s + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath) { diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs index 0b1a86fac..6b1efef7e 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs @@ -61,9 +61,10 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) /// /// indicates the current process is in an elevated state, allowing to retrieve more data. /// - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string (when is set to ). + /// A disk path such as: "\\.\PhysicalDrive0"s + /// A drive path such as: "C", "C:" or "C:\". + /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, string devicePath) { @@ -212,12 +213,9 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; - - if (isRetry && !safeHandleRetry.IsClosed) safeHandleRetry.Close(); - return storageDeviceInfo; } } diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs index eaf9ed3bf..5273830e7 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs @@ -108,9 +108,9 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; - for (var partitionCount = 0; partitionCount <= drive.PartitionCount - 1; partitionCount++) + for (var i = 0; i <= drive.PartitionCount - 1; i++) - partitions[partitionCount] = safeBuffer.PtrToStructure(driveStructureSize + partitionCount * partitionStructureSize); + partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); var disk = GetDiskGeometryExNative(safeHandle, pathToDevice); @@ -132,7 +132,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative0(SafeFileHandl while (true) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) { - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); @@ -179,7 +179,7 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHa while (true) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) { - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); @@ -197,15 +197,17 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHa }; - var offset = sizeOf + sizeof(long); // 32 + var offset = (uint) sizeOf + sizeof(long); // 32 - diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure(offset); + diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure((int) offset); - offset += (int)diskGeometryEx.PartitionInformation.SizeOfPartitionInfo; + //// Intermittently throws: System.AccessViolationException: Attempted to read or write protected memory. + //// Observed when mounting an .iso file. - diskGeometryEx.DiskDetectionInfo = safeBuffer.PtrToStructure(offset); + //offset += diskGeometryEx.PartitionInformation.SizeOfPartitionInfo; + //diskGeometryEx.DiskDetectionInfo = safeBuffer.PtrToStructure((int) offset); return diskGeometryEx; } diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs index 6be9cdb62..c8b3cd714 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -48,9 +48,9 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() { DeviceType = device.DeviceType; - DeviceNumber = device.DeviceNumber; + DeviceNumber = (int) device.DeviceNumber; - PartitionNumber = device.PartitionNumber; + PartitionNumber = (int) device.PartitionNumber; } #endregion // Constructors diff --git a/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs b/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs index 3f8294d0f..23d085ea2 100644 --- a/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs +++ b/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs @@ -23,7 +23,7 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// The following table identifies the valid partition types that are used by disk drivers. + /// Valid partition types that are used by disk drivers. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] /// @@ -47,7 +47,7 @@ internal enum DiskPartitionType : byte /// FAT32 partition or logical drive. PARTITION_FAT32 = 11, - /// LDM (Logical Disk Manager) partition. + /// LDM (Logical Disk Manager) Data partition on a dynamic disk. PARTITION_LDM = 66, /// An NTFT partition. diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs index 5929b4789..a9f577098 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs @@ -28,6 +28,8 @@ internal static partial class NativeMethods /// /// The STORAGE_DEVICE_NUMBER structure is used in conjunction with the IOCTL_STORAGE_GET_DEVICE_NUMBER request to retrieve the FILE_DEVICE_XXX device type, /// the device number, and, for a device that can be partitioned, the partition number assigned to a device by the driver when the device is started. + /// The values in the STORAGE_DEVICE_NUMBER structure are guaranteed to remain unchanged until the device is removed or the system is restarted. + /// It is not guaranteed to be persistent across device restarts or system restarts. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct STORAGE_DEVICE_NUMBER @@ -36,10 +38,12 @@ internal struct STORAGE_DEVICE_NUMBER [MarshalAs(UnmanagedType.U4)] internal readonly StorageDeviceType DeviceType; /// Indicates the number of this device. This value is set to 0xFFFFFFFF (-1) for the disks that represent the physical paths of an MPIO disk. - [MarshalAs(UnmanagedType.U4)] internal readonly int DeviceNumber; + [MarshalAs(UnmanagedType.U4)] + internal readonly int DeviceNumber; // 2018-02-28: On MSDN this is defined as ULONG. /// Indicates the partition number of the device is returned in this member, if the device can be partitioned. Otherwise, -1 is returned. - [MarshalAs(UnmanagedType.U4)] internal readonly int PartitionNumber; + [MarshalAs(UnmanagedType.U4)] + internal readonly int PartitionNumber; // 2018-02-28: On MSDN this is defined as ULONG. } } } diff --git a/AlphaFS/Filesystem/Shell32.cs b/AlphaFS/Filesystem/Shell32.cs index baca3a40d..d6cea8b9b 100644 --- a/AlphaFS/Filesystem/Shell32.cs +++ b/AlphaFS/Filesystem/Shell32.cs @@ -302,10 +302,6 @@ public enum FileAttributes /// SHFILEINFO structure, contains information about a file system object. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Sh")] - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sh")] - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct FileInfo { diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs index b4294e594..1cce7bd5f 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs @@ -23,7 +23,7 @@ namespace Alphaleonis.Win32.Filesystem { - /// The following table identifies the valid partition types that are used by disk drivers. + /// Valid partition types that are used by disk drivers. /// https://technet.microsoft.com/en-us/library/cc739412.aspx public enum DiskPartitionType { @@ -73,7 +73,7 @@ public enum DiskPartitionType /// A PC PReP (Power PC Reference Platform) Boot partition. Prep = 65, - /// LDM (Logical Disk Manager) Dynamic volume. + /// LDM (Logical Disk Manager) Data partition on a dynamic disk. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ldm")] Ldm = NativeMethods.DiskPartitionType.PARTITION_LDM, diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs index f36342681..fbd98793a 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs @@ -35,7 +35,7 @@ public enum StorageDeviceType Beep = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BEEP, /// FILE_DEVICE_CD_ROM parameter. - CDRom = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM, + CDRom = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM, // .NET DriveInfo.DriveType property also uses "CDRom" instead of "CdRom". /// FILE_DEVICE_CD_ROM_FILE_SYSTEM parameter. CDRomFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM_FILE_SYSTEM, @@ -47,8 +47,8 @@ public enum StorageDeviceType DataLink = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DATALINK, /// FILE_DEVICE_DFS parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "DFS")] - DFS = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] + Dfs = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS, /// FILE_DEVICE_DISK parameter. Disk = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK, @@ -163,15 +163,15 @@ public enum StorageDeviceType Modem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MODEM, /// FILE_DEVICE_VDM parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "VDM")] - VDM = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VDM, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vdm")] + Vdm = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VDM, /// FILE_DEVICE_MASS_STORAGE parameter. MassStorage = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE, /// FILE_DEVICE_SMB parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SMB")] - SMB = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SMB, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smb")] + Smb = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SMB, /// FILE_DEVICE_KS parameter. KS = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_KS, @@ -180,67 +180,65 @@ public enum StorageDeviceType Changer = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER, /// FILE_DEVICE_SMARTCARD parameter. - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SmartCard")] - SmartCard = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SMARTCARD, + Smartcard = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SMARTCARD, /// FILE_DEVICE_ACPI parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ACPI")] - ACPI = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_ACPI, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Acpi")] + Acpi = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_ACPI, /// FILE_DEVICE_DVD parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "DVD")] - DVD = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DVD, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dvd")] + Dvd = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DVD, /// FILE_DEVICE_FULLSCREEN_VIDEO parameter. - FullScreenVideo = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_FULLSCREEN_VIDEO, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fullscreen")] + FullscreenVideo = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_FULLSCREEN_VIDEO, /// FILE_DEVICE_DFS_FILE_SYSTEM parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "DEVICE")] - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "DFS")] - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "FILE")] - [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores")] - DFSFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS_FILE_SYSTEM, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] + DfsFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS_FILE_SYSTEM, /// FILE_DEVICE_DFS_VOLUME parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "DFS")] - DFSVolume = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS_VOLUME, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] + DfsVolume = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS_VOLUME, /// FILE_DEVICE_SERENUM parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Serenum")] Serenum = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SERENUM, /// FILE_DEVICE_TERMSRV parameter. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Srv")] - TermSrv = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_TERMSRV, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Termsrv")] + Termsrv = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_TERMSRV, /// FILE_DEVICE_KSEC parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "KSEC")] - KSEC = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_KSEC, + KSec = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_KSEC, /// FILE_DEVICE_FIPS parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "FIPS")] - FIPS = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_FIPS, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fips")] + Fips = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_FIPS, /// FILE_DEVICE_INFINIBAND parameter. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infini")] - InfiniBand = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_INFINIBAND, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infiniband")] + Infiniband = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_INFINIBAND, /// FILE_DEVICE_VMBUS parameter. - VMBus = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VMBUS, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vm")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vm")] + VmBus = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VMBUS, /// FILE_DEVICE_CRYPT_PROVIDER parameter. CryptProvider = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CRYPT_PROVIDER, /// FILE_DEVICE_WPD parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "WPD")] - WPD = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_WPD, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wpd")] + Wpd = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_WPD, /// FILE_DEVICE_BLUETOOTH parameter. - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "BlueTooth")] - BlueTooth = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BLUETOOTH, + Bluetooth = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BLUETOOTH, /// FILE_DEVICE_MT_COMPOSITE parameter. - MTComposite = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MT_COMPOSITE, + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mt")] + MtComposite = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MT_COMPOSITE, /// FILE_DEVICE_MT_TRANSPORT parameter. MTTransport = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MT_TRANSPORT, @@ -249,35 +247,34 @@ public enum StorageDeviceType Biometric = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BIOMETRIC, /// FILE_DEVICE_PMI parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "PMI")] - PMI = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_PMI, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pmi")] + Pmi = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_PMI, /// FILE_DEVICE_EHSTOR parameter. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Stor")] - EHStor = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_EHSTOR, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ehstor")] + Ehstor = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_EHSTOR, /// FILE_DEVICE_DEVAPI parameter. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Api")] - DevApi = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DEVAPI, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Devapi")] + Devapi = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DEVAPI, /// FILE_DEVICE_GPIO parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "GPIO")] - GPIO = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_GPIO, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpio")] + Gpio = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_GPIO, /// FILE_DEVICE_USBEX parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "USB")] - [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] - USBEx = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_USBEX, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usbex")] + Usbex = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_USBEX, /// FILE_DEVICE_CONSOLE parameter. Console = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CONSOLE, /// FILE_DEVICE_NFP parameter. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NFP")] - NFP = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NFP, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nfp")] + Nfp = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NFP, /// FILE_DEVICE_SYSENV parameter. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Env")] - SysEnv = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SYSENV + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sysenv")] + Sysenv = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SYSENV } } From fa45301b434a8f089e7ce93718e165bfb37f07f8 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 9 May 2018 18:51:39 +0200 Subject: [PATCH 064/133] Renamed members to their original Win32 name. --- AlphaFS/AlphaFS.csproj | 4 +- AlphaFS/Device/Device.EnumerateDevices.cs | 4 +- .../NativeMethods.DeviceManagement.cs | 2 +- ...ssFlags.cs => DEVICE_INFORMATION_FLAGS.cs} | 37 ++++++------------- 4 files changed, 17 insertions(+), 30 deletions(-) rename AlphaFS/Filesystem/Structures, Enumerations/{DiGetClassFlags.cs => DEVICE_INFORMATION_FLAGS.cs} (54%) diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 94aa76d66..05b6ecb12 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -396,7 +396,7 @@ - + @@ -708,7 +708,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Device.EnumerateDevices.cs index c1dad9bb4..83feb21ab 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -80,7 +80,7 @@ internal static IEnumerable EnumerateDevicesCore(string hostName, De // 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)) + using (var safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref classGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_PRESENT | NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_DEVICEINTERFACE, IntPtr.Zero, hostName, IntPtr.Zero)) { NativeMethods.IsValidHandle(safeHandle, Marshal.GetLastWin32Error()); @@ -193,7 +193,7 @@ private static string GetDeviceBusReportedDeviceDescription(SafeHandle safeHandl var success = NativeMethods.SetupDiGetDeviceProperty(safeHandle, ref infoData, ref NativeMethods.DEVPROPKEYS.DeviceBusReportedDeviceDesc, ref propertyType, descriptionBuffer, descriptionBuffer.Length, ref requiredSize, 0); - Marshal.GetLastWin32Error(); + var lastError = Marshal.GetLastWin32Error(); if (success) { diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs index d36c34210..0da76ef1d 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs @@ -206,7 +206,7 @@ internal static partial class NativeMethods /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern SafeSetupDiClassDevsExHandle SetupDiGetClassDevsEx(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, [MarshalAs(UnmanagedType.U4)] SetupDiGetClassDevsExFlags devsExFlags, IntPtr deviceInfoSet, [MarshalAs(UnmanagedType.LPWStr)] string machineName, IntPtr reserved); + internal static extern SafeSetupDiClassDevsExHandle SetupDiGetClassDevsEx(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, [MarshalAs(UnmanagedType.U4)] DEVICE_INFORMATION_FLAGS devsExFlags, IntPtr deviceInfoSet, [MarshalAs(UnmanagedType.LPWStr)] string machineName, IntPtr reserved); /// The SetupDiGetDeviceInterfaceDetail function returns details about a device interface. diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DiGetClassFlags.cs b/AlphaFS/Filesystem/Structures, Enumerations/DEVICE_INFORMATION_FLAGS.cs similarity index 54% rename from AlphaFS/Filesystem/Structures, Enumerations/DiGetClassFlags.cs rename to AlphaFS/Filesystem/Structures, Enumerations/DEVICE_INFORMATION_FLAGS.cs index d60b07e76..463954b2e 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DiGetClassFlags.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DEVICE_INFORMATION_FLAGS.cs @@ -27,35 +27,22 @@ internal static partial class NativeMethods { /// Specifies control options that filter the device information elements that are added to the device information set. [Flags] - internal enum SetupDiGetClassDevsExFlags + internal enum DEVICE_INFORMATION_FLAGS { - /// DIGCF_DEFAULT - /// Return only the device that is associated with the system default device interface, if one is set, for the specified device interface classes. - /// - Default = 1, // only valid with DIGCF_DEVICEINTERFACE + /// Return only the device that is associated with the system default device interface, if one is set, for the specified device interface classes. + DIGCF_DEFAULT = 1, // Only valid with DIGCF_DEVICEINTERFACE - /// DIGCF_PRESENT - /// Return only devices that are currently present. - /// - Present = 2, + /// Return only devices that are currently present. + DIGCF_PRESENT = 2, - /// DIGCF_ALLCLASSES - /// Return a list of installed devices for the specified device setup classes or device interface classes. - /// - AllClasses = 4, + /// Return a list of installed devices for the specified device setup classes or device interface classes. + DIGCF_ALLCLASSES = 4, - /// DIGCF_PROFILE - /// Return only devices that are a part of the current hardware profile. - /// - Profile = 8, + /// Return only devices that are a part of the current hardware profile. + DIGCF_PROFILE = 8, - /// DIGCF_DEVICEINTERFACE - /// - /// 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. - /// - /// - DeviceInterface = 16 + /// 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. + DIGCF_DEVICEINTERFACE = 16 } } -} \ No newline at end of file +} From b5745fc9221499ef14cae49da9414819931f42e1 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 10 May 2018 12:40:31 +0200 Subject: [PATCH 065/133] Restored missing file. --- AlphaFS/AlphaFS.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 05b6ecb12..08f6ea922 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -331,6 +331,7 @@ + @@ -396,7 +397,6 @@ - @@ -708,7 +708,7 @@ --> - + \ No newline at end of file From 5a0c15a2399375fff252193f0327400c9b5634d7 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 10 May 2018 12:46:21 +0200 Subject: [PATCH 066/133] Corrected unit test files. --- ...phaFS.Volume.GetUniqueVolumeNameForPath.cs | 77 ------------------- ....Volume.GetUniqueVolumeNameForPath.cs~HEAD | 77 ------------------- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 - 3 files changed, 155 deletions(-) delete mode 100644 AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs delete mode 100644 AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs~HEAD diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs deleted file mode 100644 index 703c8c537..000000000 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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_VolumeTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Volume_GetUniqueVolumeNameForPath_Local_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - - var logicalDriveCount = 0; - - foreach (var driveName in System.IO.Directory.GetLogicalDrives()) - { - var deviceGuid = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(driveName); - - Console.WriteLine("\n#{0:000}\tInput Path: [{1}]", ++logicalDriveCount, driveName); - - - var volumeNameResult = Alphaleonis.Win32.Filesystem.Volume.GetUniqueVolumeNameForPath(driveName); - - Console.WriteLine("\n\tGetUniqueVolumeNameForPath: [{0}]", volumeNameResult ?? "null"); - - - // Typically, only one mount point exists so the Volume GUIDs will match. - - Assert.AreEqual(deviceGuid, volumeNameResult); - - - var pathNames = Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumePathNames(volumeNameResult).ToArray(); - - foreach (var displayName in pathNames) - { - Console.WriteLine("\n\t(Input Volume GUID Path) EnumerateVolumePathNames: Volume points to logcal drive: [{0}]\n", displayName); - - - // Volumes don't always have drive letters. - - if (!string.IsNullOrWhiteSpace(displayName)) - Assert.AreEqual(driveName, displayName); - } - } - - - if (logicalDriveCount == 0) - Assert.Inconclusive("No logical drives enumerated, but it is expected."); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs~HEAD b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs~HEAD deleted file mode 100644 index ec7d8c57a..000000000 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs~HEAD +++ /dev/null @@ -1,77 +0,0 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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_VolumeTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Volume_GetUniqueVolumeNameForPath_Local_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - - var logicalDriveCount = 0; - - foreach (var driveName in System.IO.Directory.GetLogicalDrives()) - { - var deviceGuid = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(driveName); - - Console.WriteLine("\n#{0:000}\tInput Path: [{1}]", ++logicalDriveCount, driveName); - - - var volumeNameResult = Alphaleonis.Win32.Filesystem.Volume.GetUniqueVolumeNameForPath(driveName); - - Console.WriteLine("\n\tGetUniqueVolumeNameForPath: [{0}]", volumeNameResult ?? "null"); - - - // Typically, only one mount point exists so the Volume GUIDs will match. - - Assert.AreEqual(deviceGuid, volumeNameResult); - - - var pathNames = Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumePathNames(volumeNameResult).ToArray(); - - foreach (var displayName in pathNames) - { - Console.WriteLine("\n\t(Input Volume GUID Path) EnumerateVolumePathNames: Volume points to logcal drive: [{0}]\n", displayName); - - - // Volumes don't always have drive letters. - - if (!string.IsNullOrWhiteSpace(displayName)) - Assert.AreEqual(driveName, displayName); - } - } - - - if (logicalDriveCount == 0) - Assert.Inconclusive("No logical drices enumerated, but it is expected."); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index c29beafe2..ce5a5e33a 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -184,7 +184,6 @@ - From 08e8bf03dbaae3118106507365fdc8a6cc9aceb9 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 10 May 2018 12:47:51 +0200 Subject: [PATCH 067/133] Corrected unit test files. --- ...phaFS.Volume.GetUniqueVolumeNameForPath.cs | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs new file mode 100644 index 000000000..703c8c537 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs @@ -0,0 +1,77 @@ +/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_VolumeTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Volume_GetUniqueVolumeNameForPath_Local_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + + var logicalDriveCount = 0; + + foreach (var driveName in System.IO.Directory.GetLogicalDrives()) + { + var deviceGuid = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(driveName); + + Console.WriteLine("\n#{0:000}\tInput Path: [{1}]", ++logicalDriveCount, driveName); + + + var volumeNameResult = Alphaleonis.Win32.Filesystem.Volume.GetUniqueVolumeNameForPath(driveName); + + Console.WriteLine("\n\tGetUniqueVolumeNameForPath: [{0}]", volumeNameResult ?? "null"); + + + // Typically, only one mount point exists so the Volume GUIDs will match. + + Assert.AreEqual(deviceGuid, volumeNameResult); + + + var pathNames = Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumePathNames(volumeNameResult).ToArray(); + + foreach (var displayName in pathNames) + { + Console.WriteLine("\n\t(Input Volume GUID Path) EnumerateVolumePathNames: Volume points to logcal drive: [{0}]\n", displayName); + + + // Volumes don't always have drive letters. + + if (!string.IsNullOrWhiteSpace(displayName)) + Assert.AreEqual(driveName, displayName); + } + } + + + if (logicalDriveCount == 0) + Assert.Inconclusive("No logical drives enumerated, but it is expected."); + } + } +} From f9d461a530ddf2ff183ca13e9f879b3ad1f346da Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 17 May 2018 19:19:37 +0200 Subject: [PATCH 068/133] Updated year in headers. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 2 +- .../AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs | 2 +- .../AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs | 2 +- .../AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs | 2 +- .../AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs | 2 +- .../AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs | 2 +- .../AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs | 2 +- .../AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs | 2 +- AlphaFS.UnitTest/AlphaFS Timestamps/AlphaFS_TimestampsTest.cs | 2 +- .../AlphaFS.Volume.GetUniqueVolumeNameForPath.cs | 2 +- AlphaFS.UnitTest/Path Class/Path.GetRelativePath.cs | 2 +- AlphaFS.UnitTest/UnitTest Utility/FolderDenyPermission.cs | 2 +- AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs | 2 +- AlphaFS/Device/Device.Compression.cs | 2 +- AlphaFS/Device/Device.EnumerateDevices.cs | 2 +- AlphaFS/Device/Device.GetDeviceIoData.cs | 2 +- AlphaFS/Device/Device.GetDevicePath.cs | 2 +- AlphaFS/Device/Device.GetVolumeDiskExtents.cs | 2 +- AlphaFS/Device/Device.InvokeDeviceIoData.cs | 2 +- AlphaFS/Device/Device.OpenPhysicalDrive.cs | 2 +- AlphaFS/Device/Device.ValidateDevicePath.cs | 2 +- AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs | 2 +- AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs | 2 +- AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs | 2 +- .../Device/Junctions, Links/Device.CreateDirectoryJunction.cs | 2 +- .../Device/Junctions, Links/Device.DeleteDirectoryJunction.cs | 2 +- AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs | 2 +- .../Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs | 2 +- AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs | 2 +- AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs | 2 +- AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs | 2 +- .../Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs | 2 +- AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs | 2 +- AlphaFS/Device/StorageAdapterInfo.cs | 2 +- AlphaFS/Device/StorageDeviceInfo.cs | 2 +- AlphaFS/Device/StorageGptPartitionInfo.cs | 2 +- AlphaFS/Device/StorageMbrPartitionInfo.cs | 2 +- AlphaFS/Device/StoragePartitionInfo.cs | 2 +- AlphaFS/Device/Test.cs | 2 +- AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs | 2 +- AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs | 2 +- AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs | 2 +- AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs | 2 +- AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs | 2 +- AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs | 2 +- AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs | 2 +- AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs | 2 +- AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs | 2 +- AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs | 2 +- AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs | 2 +- AlphaFS/Filesystem/Native Other/DiskInt13Union.cs | 2 +- AlphaFS/Filesystem/Native Other/DiskPartitionType.cs | 2 +- AlphaFS/Filesystem/Native Other/EfiPartitionAttributes.cs | 2 +- AlphaFS/Filesystem/Native Other/IoControlCode.cs | 2 +- AlphaFS/Filesystem/Native Other/IoMethod.cs | 2 +- AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs | 2 +- AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs | 2 +- AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs | 2 +- AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs | 2 +- AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs | 2 +- AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs | 2 +- AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs | 2 +- AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs | 2 +- AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs | 2 +- AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs | 2 +- AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs | 2 +- AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs | 2 +- AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs | 2 +- AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs | 2 +- AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs | 2 +- .../Filesystem/Structures, Enumerations/DiskPartitionType.cs | 2 +- .../Structures, Enumerations/EfiPartitionAttributes.cs | 2 +- AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs | 2 +- AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs | 2 +- AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs | 2 +- .../Filesystem/Structures, Enumerations/StorageDeviceType.cs | 2 +- AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs | 2 +- 77 files changed, 77 insertions(+), 77 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index 6c921db77..9639d9bc0 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs index c975853c1..a6b5596b2 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs index 2430ee750..52fd20dbc 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs index 4a3226def..79adf8377 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs index 5ffeda9e4..a5a1a5005 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index e4d15569a..3bdf2a9ff 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs index ad6d1d730..75d6f005c 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs index 5889f48e2..8edca9ed0 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/AlphaFS Timestamps/AlphaFS_TimestampsTest.cs b/AlphaFS.UnitTest/AlphaFS Timestamps/AlphaFS_TimestampsTest.cs index 3ffe7007f..b3096cbd7 100644 --- a/AlphaFS.UnitTest/AlphaFS Timestamps/AlphaFS_TimestampsTest.cs +++ b/AlphaFS.UnitTest/AlphaFS Timestamps/AlphaFS_TimestampsTest.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs index 703c8c537..1e6c989a3 100644 --- a/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs +++ b/AlphaFS.UnitTest/AlphaFS Volume Class/AlphaFS.Volume.GetUniqueVolumeNameForPath.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/Path Class/Path.GetRelativePath.cs b/AlphaFS.UnitTest/Path Class/Path.GetRelativePath.cs index 37ea155cd..3f1857316 100644 --- a/AlphaFS.UnitTest/Path Class/Path.GetRelativePath.cs +++ b/AlphaFS.UnitTest/Path Class/Path.GetRelativePath.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/UnitTest Utility/FolderDenyPermission.cs b/AlphaFS.UnitTest/UnitTest Utility/FolderDenyPermission.cs index 4e19c2e24..be9a4c2ff 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/FolderDenyPermission.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/FolderDenyPermission.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs b/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs index 1f650b3ba..08e39f66e 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Device.Compression.cs b/AlphaFS/Device/Device.Compression.cs index b7e23c907..ccf98d4db 100644 --- a/AlphaFS/Device/Device.Compression.cs +++ b/AlphaFS/Device/Device.Compression.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Device.EnumerateDevices.cs index 83feb21ab..1eeacc002 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Device.GetDeviceIoData.cs b/AlphaFS/Device/Device.GetDeviceIoData.cs index 112e6b8aa..b4175ada3 100644 --- a/AlphaFS/Device/Device.GetDeviceIoData.cs +++ b/AlphaFS/Device/Device.GetDeviceIoData.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Device.GetDevicePath.cs b/AlphaFS/Device/Device.GetDevicePath.cs index 1b395b9d3..f9b87ece0 100644 --- a/AlphaFS/Device/Device.GetDevicePath.cs +++ b/AlphaFS/Device/Device.GetDevicePath.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs index 5039c9bef..41e09a79b 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Device.GetVolumeDiskExtents.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Device.InvokeDeviceIoData.cs b/AlphaFS/Device/Device.InvokeDeviceIoData.cs index df810f8d4..ad1d36677 100644 --- a/AlphaFS/Device/Device.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Device.InvokeDeviceIoData.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Device.OpenPhysicalDrive.cs b/AlphaFS/Device/Device.OpenPhysicalDrive.cs index 1ad1d5f1e..3468e687c 100644 --- a/AlphaFS/Device/Device.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/Device.OpenPhysicalDrive.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Device.ValidateDevicePath.cs b/AlphaFS/Device/Device.ValidateDevicePath.cs index 3f3af9952..780e0f59d 100644 --- a/AlphaFS/Device/Device.ValidateDevicePath.cs +++ b/AlphaFS/Device/Device.ValidateDevicePath.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs index 182e883cf..b6780b0ef 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs index c21e8484a..a2eaa9ed2 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs index e3c2298ce..23315ca1f 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs b/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs index 8c5852de9..3ca4b556b 100644 --- a/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs +++ b/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs b/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs index 3a979e18b..c0ba5274f 100644 --- a/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs +++ b/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs index a2493073b..55a68e2ed 100644 --- a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs +++ b/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs index 3ef7d0ec2..b3ff745b6 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs index ddd9085cc..bb99aa686 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs index c417ca20b..daa285940 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs index 6b1efef7e..3d4ab23e6 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs index 5273830e7..ffccc129c 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs index 522cde204..93ac8131d 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/StorageAdapterInfo.cs b/AlphaFS/Device/StorageAdapterInfo.cs index 7d0335c88..3de70d13b 100644 --- a/AlphaFS/Device/StorageAdapterInfo.cs +++ b/AlphaFS/Device/StorageAdapterInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs index c8b3cd714..1c2092adf 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/StorageGptPartitionInfo.cs b/AlphaFS/Device/StorageGptPartitionInfo.cs index 98034e5aa..8caa7a141 100644 --- a/AlphaFS/Device/StorageGptPartitionInfo.cs +++ b/AlphaFS/Device/StorageGptPartitionInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/StorageMbrPartitionInfo.cs b/AlphaFS/Device/StorageMbrPartitionInfo.cs index a891d5194..6c814892b 100644 --- a/AlphaFS/Device/StorageMbrPartitionInfo.cs +++ b/AlphaFS/Device/StorageMbrPartitionInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/StoragePartitionInfo.cs b/AlphaFS/Device/StoragePartitionInfo.cs index 0ee788b24..09075fbc0 100644 --- a/AlphaFS/Device/StoragePartitionInfo.cs +++ b/AlphaFS/Device/StoragePartitionInfo.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Device/Test.cs b/AlphaFS/Device/Test.cs index 9cb219398..e61d0df26 100644 --- a/AlphaFS/Device/Test.cs +++ b/AlphaFS/Device/Test.cs @@ -1,4 +1,4 @@ -//* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +//* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov // * // * Permission is hereby granted, free of charge, to any person obtaining a copy // * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs b/AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs index 370f595ba..6bc7b3004 100644 --- a/AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs +++ b/AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs b/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs index 6bbc9fe55..dcf75320c 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs b/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs index 27c5b11de..6b75e4f8f 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs b/AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs index 2bd45bad3..e22fed401 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs index 90356052a..040ebc003 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs index e101ec026..4f288d475 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs b/AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs index cdeb37c30..8b7f98a79 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs b/AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs index bdf4926ab..c53f0426c 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs +++ b/AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs index ee7ab1f27..5b3cc4c1a 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs index 289568371..92d55b7b5 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs index a90523188..bcc7cd56b 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs +++ b/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DiskInt13Union.cs b/AlphaFS/Filesystem/Native Other/DiskInt13Union.cs index 0a6b16ae9..4457bad31 100644 --- a/AlphaFS/Filesystem/Native Other/DiskInt13Union.cs +++ b/AlphaFS/Filesystem/Native Other/DiskInt13Union.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs b/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs index 23d085ea2..4cda85454 100644 --- a/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs +++ b/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/EfiPartitionAttributes.cs b/AlphaFS/Filesystem/Native Other/EfiPartitionAttributes.cs index edba7dd76..b53b9f45a 100644 --- a/AlphaFS/Filesystem/Native Other/EfiPartitionAttributes.cs +++ b/AlphaFS/Filesystem/Native Other/EfiPartitionAttributes.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/IoControlCode.cs b/AlphaFS/Filesystem/Native Other/IoControlCode.cs index bae3b2aeb..4c740bdf0 100644 --- a/AlphaFS/Filesystem/Native Other/IoControlCode.cs +++ b/AlphaFS/Filesystem/Native Other/IoControlCode.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/IoMethod.cs b/AlphaFS/Filesystem/Native Other/IoMethod.cs index 95f28fe91..c164cfd5e 100644 --- a/AlphaFS/Filesystem/Native Other/IoMethod.cs +++ b/AlphaFS/Filesystem/Native Other/IoMethod.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs index 623aa4afc..5f54d8390 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs index 771fe75fd..7c56e26dd 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs index fbdbcee58..01bbda84b 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs b/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs index 357034f4a..f0da68308 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs +++ b/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs b/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs index c51363cc1..25ab2476a 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs index 9f5772ca1..c70b42909 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs index 1be023720..fb2bb6468 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs index a9f577098..701fbfdcd 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs index 2299105da..6ea4502e9 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs index fe0defe47..09817a841 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs index 5eef2b0dd..66c6d730a 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs index 27aa7692d..2be357e55 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs b/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs index dd5c3c6b9..739153f30 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs +++ b/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs b/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs index 653abba26..344cbb765 100644 --- a/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs +++ b/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs b/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs index bd0ea38aa..4ab90a488 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs index 1cce7bd5f..354d03660 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs b/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs index 0b496c14f..4625f22b8 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs index 9d82dc8bb..7d88c918b 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs index 766b1d784..3fccc43b0 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs index 1cc081192..6f7fdbce0 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs index fbd98793a..5b3f683d2 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs b/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs index 58925a49a..7a3965d2d 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2017 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal From 500719fea4a4793e57b9e75e51a06390f0d25f08 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 25 May 2018 14:10:27 +0200 Subject: [PATCH 069/133] Fixed project file. --- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 3487ae1a9..006535291 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -189,7 +189,6 @@ - @@ -364,11 +363,6 @@ - - - - - @@ -382,14 +376,9 @@ - - + - - - - From fdbacedc387188c1b78da79fee290f8ac128d11f Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 25 May 2018 14:14:07 +0200 Subject: [PATCH 070/133] Fixed project file, added missing files. --- .../AlphaFS_Shell32Test.UrlIs.cs | 2 -- .../AlphaFS_Shell32Test.cs | 32 +++++++++++++++++++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 3 -- 3 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.cs diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.UrlIs.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.UrlIs.cs index 23803bc44..5d7bb452c 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.UrlIs.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.UrlIs.cs @@ -24,8 +24,6 @@ namespace AlphaFS.UnitTest { - /// This is a test class for Shell32 and is intended to contain all Shell32 and Shell32Info Unit Tests. - [TestClass] public partial class AlphaFS_Shell32Test { [TestMethod] diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.cs new file mode 100644 index 000000000..a0df291a1 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.cs @@ -0,0 +1,32 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// This is a test class for Shell32 and is intended to contain all Shell32 and Shell32Info Unit Tests. + [TestClass] + public partial class AlphaFS_Shell32Test + { + } +} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 006535291..9d701fd87 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -360,9 +360,6 @@ - - - From 3162ef0138b42af7b2f574ab451ffec84cb89697 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 26 May 2018 02:07:33 +0200 Subject: [PATCH 071/133] Fixed duplicate/missing unit test files. --- ...cs => AlphaFS.Host.GetServerStatistics.cs} | 0 ... AlphaFS.Host.GetWorkstationStatistics.cs} | 0 .../AlphaFS_Host.GetWorkstationStatistics.cs | 42 ---------------- .../AlphaFS_Shell32Test..cs | 31 ------------ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 50 +++++++------------ AlphaFS.UnitTest/File Class/FileTest.cs | 7 ++- 6 files changed, 21 insertions(+), 109 deletions(-) rename AlphaFS.UnitTest/AlphaFS Host Class/{AlphaFS.Host_GetServerStatistics.cs => AlphaFS.Host.GetServerStatistics.cs} (100%) rename AlphaFS.UnitTest/AlphaFS Host Class/{AlphaFS.Host_GetWorkstationStatistics.cs => AlphaFS.Host.GetWorkstationStatistics.cs} (100%) delete mode 100644 AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetWorkstationStatistics.cs delete mode 100644 AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test..cs diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetServerStatistics.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host.GetServerStatistics.cs similarity index 100% rename from AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetServerStatistics.cs rename to AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host.GetServerStatistics.cs diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetWorkstationStatistics.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host.GetWorkstationStatistics.cs similarity index 100% rename from AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host_GetWorkstationStatistics.cs rename to AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS.Host.GetWorkstationStatistics.cs diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetWorkstationStatistics.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetWorkstationStatistics.cs deleted file mode 100644 index e87258a31..000000000 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetWorkstationStatistics.cs +++ /dev/null @@ -1,42 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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; - -namespace AlphaFS.UnitTest -{ - public partial class AlphaFS_HostTest - { - [TestMethod] - public void AlphaFS_Host_GetWorkstationStatistics_Local_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - if (!UnitTestConstants.IsAdmin()) - Assert.Inconclusive(); - - - var workstationStat = Alphaleonis.Win32.Network.Host.GetWorkstationStatistics(); - - UnitTestConstants.Dump(workstationStat, -36); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test..cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test..cs deleted file mode 100644 index 744bb74a6..000000000 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test..cs +++ /dev/null @@ -1,31 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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; - -namespace AlphaFS.UnitTest -{ - /// This is a test class for Shell32 and is intended to contain all Shell32 and Shell32Info Unit Tests. - [TestClass] - public partial class AlphaFS_Shell32Test - { - } -} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 9afd08517..4936fd736 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -151,8 +151,13 @@ + + + + + @@ -186,13 +191,16 @@ - - + + + + + + + + + - - - - @@ -201,11 +209,6 @@ - - - - - @@ -287,21 +290,12 @@ - - - - - - - - - @@ -350,11 +344,12 @@ - - - + + + + @@ -377,9 +372,6 @@ - - - @@ -390,7 +382,6 @@ - @@ -430,16 +421,11 @@ - - - - - diff --git a/AlphaFS.UnitTest/File Class/FileTest.cs b/AlphaFS.UnitTest/File Class/FileTest.cs index 01d20f63d..8f0dc1a77 100644 --- a/AlphaFS.UnitTest/File Class/FileTest.cs +++ b/AlphaFS.UnitTest/File Class/FileTest.cs @@ -66,7 +66,7 @@ private void DumpGetSetAttributes(bool isLocal) var allOk = true; var cnt = 0; - UnitTestConstants.StopWatcher(true); + foreach (var file in Directory.EnumerateFiles(tempPath)) { try @@ -90,7 +90,7 @@ private void DumpGetSetAttributes(bool isLocal) } } Console.WriteLine(); - Console.WriteLine(UnitTestConstants.Reporter()); + Assert.IsTrue(allOk); @@ -99,7 +99,7 @@ private void DumpGetSetAttributes(bool isLocal) allOk = true; cnt = 0; - UnitTestConstants.StopWatcher(true); + foreach (var file in Directory.EnumerateFiles(tempPath)) { try @@ -123,7 +123,6 @@ private void DumpGetSetAttributes(bool isLocal) } } Console.WriteLine(); - Console.WriteLine(UnitTestConstants.Reporter()); Directory.Delete(tempPath, true, true); From 35caa898b9ea0521bc128b55987d6f7791dec8c6 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 26 May 2018 09:47:29 +0200 Subject: [PATCH 072/133] -Modified EnumeratePhysicalDisksCore to exclude mapped network drives; --- ...lphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs | 3 +++ ...AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs | 3 +++ ...haFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs | 3 +++ .../PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs | 7 ++++++- 4 files changed, 15 insertions(+), 1 deletion(-) diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs index a5a1a5005..708cf31bd 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs @@ -44,6 +44,9 @@ public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrive_Success() foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { + if (drive.DriveType == System.IO.DriveType.Network) + continue; + var storageAdapterInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageAdapterInfo(drive.Name); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index 3bdf2a9ff..839bbfc72 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -40,6 +40,9 @@ public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { + if (drive.DriveType == System.IO.DriveType.Network) + continue; + var storageDeviceInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageDeviceInfo(drive.Name); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs index 75d6f005c..3e5af13b2 100644 --- a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs @@ -40,6 +40,9 @@ public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrive_Success() foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { + if (drive.DriveType == System.IO.DriveType.Network) + continue; + var storagePartitionInfo = Alphaleonis.Win32.Filesystem.Device.GetStoragePartitionInfo(drive.Name); Console.WriteLine(); diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs index b3ff745b6..606ba6f7e 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs @@ -21,6 +21,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; +using System.IO; using System.Linq; using System.Security; @@ -48,7 +49,11 @@ internal static IEnumerable EnumeratePhysicalDisksCore(bool is var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDiskInfoCore(false, volumeGuid, null, null)).Where(physicalDisk => null != physicalDisk).ToArray(); - var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false).Select(driveName => GetPhysicalDiskInfoCore(false, driveName, null, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false) + + .Select(driveName => new DriveInfo(driveName)).Where(driveInfo => driveInfo.DriveType == DriveType.CDRom || driveInfo.DriveType == DriveType.Fixed || driveInfo.DriveType == DriveType.Removable) + + .Select(driveInfo => GetPhysicalDiskInfoCore(false, driveInfo.Name, null, null)).Where(physicalDisk => null != physicalDisk).ToArray(); foreach (var pDisk in physicalDisks) From d6bfbc1ddab7e63b1098d427914300e629df82a9 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 30 May 2018 00:34:29 +0200 Subject: [PATCH 073/133] Moved unit tests. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 0 .../AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs | 0 .../AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs | 0 .../AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs | 0 .../AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs | 0 .../AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs | 0 .../AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs | 0 .../AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs | 0 8 files changed, 0 insertions(+), 0 deletions(-) rename AlphaFS.UnitTest/{ => AlphaFS Device Class}/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs (100%) rename AlphaFS.UnitTest/{ => AlphaFS Device Class}/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs (100%) rename AlphaFS.UnitTest/{ => AlphaFS Device Class}/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs (100%) rename AlphaFS.UnitTest/{ => AlphaFS Device Class}/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs (100%) rename AlphaFS.UnitTest/{ => AlphaFS Device Class}/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs (100%) rename AlphaFS.UnitTest/{ => AlphaFS Device Class}/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs (100%) rename AlphaFS.UnitTest/{ => AlphaFS Device Class}/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs (100%) rename AlphaFS.UnitTest/{ => AlphaFS Device Class}/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs (100%) diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs similarity index 100% rename from AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs similarity index 100% rename from AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs similarity index 100% rename from AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs similarity index 100% rename from AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs similarity index 100% rename from AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs similarity index 100% rename from AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs similarity index 100% rename from AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs diff --git a/AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs similarity index 100% rename from AlphaFS.UnitTest/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfoTest.cs From 500f7c4fc46be6d5fa7d39c07cd5502307e4dc7d Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 30 May 2018 00:37:51 +0200 Subject: [PATCH 074/133] Moved unit tests. --- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 5e808eb05..911246adb 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -143,14 +143,14 @@ AssemblyVersionInfo.cs - - - - - - - - + + + + + + + + From 524f2bb4e8fa9bff243b0753b464bb228f4510c9 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 30 May 2018 14:44:37 +0200 Subject: [PATCH 075/133] Improved unit test code. --- ...aFS_BackupFileStream_InitializeInstance.cs | 2 +- ...am_ThrowIOException_FilePortionIsLocked.cs | 2 +- ...ThrowIOException_SegmentAlreadyUnlocked.cs | 2 +- .../AlphaFS_Directory.GetFileInfo.cs | 2 +- .../AlphaFS_File.GetFileInfoByHandle.cs | 2 +- .../AlphaFS_File.Compress_And_Decompress.cs | 2 +- .../AlphaFS_Volume.DefineDosDevice.cs | 163 ------------ ...ume.DefineDosDevice_RegularDriveMapping.cs | 83 ++++++ ...efineDosDevice_SymbolicLinkDriveMapping.cs | 74 ++++++ .../AlphaFS_Volume.GetDriveFormat.cs | 5 +- ...haFS_Volume.GetDriveNameForNtDeviceName.cs | 4 +- ...phaFS_Volume.GetUniqueVolumeNameForPath.cs | 4 +- .../AlphaFS_Volume.GetVolumeInfo.cs | 5 +- .../AlphaFS_Volume.GetXxx.cs | 18 +- .../AlphaFS_Volume.SetVolumeMountPoint.cs | 2 +- ..._EnableEncryption_And_DisableEncryption.cs | 2 +- .../AlphaFS_Directory_Encrypt_And_Decrypt.cs | 2 +- ...Directory_Encrypt_And_Decrypt_Recursive.cs | 2 +- ...File_EncryptDecrypt_GetEncryptionStatus.cs | 2 +- .../AlphaFS_Directory.GetFileIdInfo.cs | 2 +- .../AlphaFS_File.GetFileIdInfo.cs | 2 +- ...eSystemEntryInfos_FolderWithSpaceAsName.cs | 2 +- ...tion_ThrowArgumentException_MappedDrive.cs | 21 +- ...e.CreateHardlink_And_EnumerateHardlinks.cs | 8 +- .../AlphaFS_Shell32.GetVerbCommand.cs | 2 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 16 +- ...phaFS_Directory.Copy_ExistingDirectory.cs} | 8 +- ...ry.Copy_ExistingDirectory_WithProgress.cs} | 10 +- ..._Overwrite_DestinationFileAlreadyExists.cs | 2 +- ...sException_DestinationFileAlreadyExists.cs | 2 +- ...ion_UserExplicitDenyOnDestinationFolder.cs | 4 +- ...ileSystemObjects_FilesOnly_NonRecursive.cs | 2 +- ...ntFileSystemObjects_FilesOnly_Recursive.cs | 2 +- ...SystemObjects_FoldersAndFiles_Recursive.cs | 2 +- ...eSystemObjects_FoldersOnly_NonRecursive.cs | 2 +- ...FileSystemObjects_FoldersOnly_Recursive.cs | 2 +- ...aFS_Directory.DeleteEmptySubdirectories.cs | 2 +- ...ption_FileExistsWithSameNameAsDirectory.cs | 2 +- ...toryNotEmptyException_NonEmptyDirectory.cs | 5 +- ...ption_FileExistsWithSameNameAsDirectory.cs | 2 +- ...essException_DirectoryHasDenyPermission.cs | 8 +- .../Directory.Exists_ExistingDirectory.cs | 2 +- .../Directory.Exists_UseCases.cs | 2 +- .../Directory.GetDirectories_AbsolutePath.cs | 2 +- .../Directory.GetDirectories_RelativePath.cs | 2 +- ...ectory.GetDirectories_WithSearchPattern.cs | 18 +- .../Directory.GetFiles_AbsolutePath.cs | 2 +- .../Directory.GetFiles_RelativePath.cs | 2 +- .../Directory.GetFiles_WithSearchPattern.cs | 19 +- .../Directory.GetProperties.cs | 2 +- ...write_DestinationDirectoryAlreadyExists.cs | 2 +- ...ption_DestinationDirectoryAlreadyExists.cs | 4 +- ...ferentVolume_EmulateMoveUsingCopyDelete.cs | 8 +- .../Directory.Move_SameVolume.cs | 2 +- ...ion_UserExplicitDenyOnDestinationFolder.cs | 4 +- ...phaFS_Directory.HasInheritedPermissions.cs | 2 +- .../Directory.GetAccessControl.cs | 2 +- .../Directory.SetAccessControl.cs | 2 +- ...Directory.EnumerateAlternateDataStreams.cs | 21 +- ...ectory.EnumerateFileIdBothDirectoryInfo.cs | 2 +- .../Directory.EnumerateDirectories.cs | 2 +- .../Directory.EnumerateFileSystemEntries.cs | 2 +- .../Directory.EnumerateFiles.cs | 2 +- .../AlphaFS_Directory.CopyTimestamps.cs | 4 +- .../AlphaFS_Directory.SetTimestamps.cs | 6 +- ..._CompareTimestamps_NonExistingDirectory.cs | 49 ++-- ...fo.InitializeInstance_ExistingDirectory.cs | 2 +- ...irectoryInfo.MoveTo_FolderToEmptyFolder.cs | 14 +- .../DirectoryInfo.MoveTo_Rename.cs | 25 +- ...haFS_File.EnumerateAlternateDataStreams.cs | 23 +- .../File Class/AlphaFS_File.GetSize.cs | 2 +- .../AlphaFS_File.GetProcessForFileLock.cs | 2 +- ...GetProcessForFileLock_NoLockReturnsNull.cs | 2 +- .../AlphaFS_File.IsLocked.cs | 2 +- ...FS_File.Copy_ExistingFile_WithProgress.cs} | 12 +- ..._Overwrite_DestinationFileAlreadyExists.cs | 4 +- ...sException_DestinationFileAlreadyExists.cs | 4 +- ...File.Copy.cs => File.Copy_ExistingFile.cs} | 10 +- ...cessException_DestinationFileIsReadOnly.cs | 2 +- ...ThrowFileReadOnlyException_ReadOnlyFile.cs | 2 +- .../File.Delete/File.Delete_ExistingFile.cs | 2 +- ...ccessException_PathIsADirectoryNotAFile.cs | 2 +- .../File.Exists/File.Exists_ExistingFile.cs | 2 +- ..._Overwrite_DestinationFileAlreadyExists.cs | 4 +- ...sException_DestinationFileAlreadyExists.cs | 2 +- ...File.Move.cs => File.Move_ExistingFile.cs} | 10 +- ...ile.OpenRead_OpenReadTwiceShouldNotLock.cs | 2 +- ...e_Open_Append_NoObjectDisposedException.cs | 2 +- .../File.GetAccessControl.cs | 2 +- .../File.SetAccessControl.cs | 2 +- .../File_Attributes/File.GetAttributes.cs | 2 +- .../File_Attributes/File.SetAttributes.cs | 2 +- .../AlphaFS_File.CopyTimestamps.cs | 4 +- .../AlphaFS_File.GetChangeTime.cs | 2 +- .../AlphaFS_File.SetTimestamps.cs | 7 +- ...tamps_CompareTimestamps_NonExistingFile.cs | 43 ++-- ...ileInfo.InitializeInstance_ExistingFile.cs | 2 +- ...nalPathNameByHandle_ToGetFileStreamName.cs | 2 +- .../UnitTest Utility/DirectoryAssert.cs | 31 ++- .../UnitTest Utility/FileAssert.cs | 6 + .../UnitTest Utility/FolderDenyPermission.cs | 70 ------ ...etRandomFileNameWithDiacriticCharacters.cs | 50 ---- .../UnitTest Utility/InputPaths.cs | 134 ---------- .../UnitTest Utility/TemporaryDirectory.cs | 238 +++++++++++++----- .../UnitTest Utility/UnitTestConstants.cs | 107 +++++++- 105 files changed, 719 insertions(+), 768 deletions(-) delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice.cs create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs rename AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/{AlphaFS_Directory.Copy.cs => AlphaFS_Directory.Copy_ExistingDirectory.cs} (93%) rename AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/{AlphaFS_Directory.Copy_WithProgress.cs => AlphaFS_Directory.Copy_ExistingDirectory_WithProgress.cs} (92%) rename AlphaFS.UnitTest/File Class/File.Copy/{AlphaFS_File.Copy_WithProgress.cs => AlphaFS_File.Copy_ExistingFile_WithProgress.cs} (91%) rename AlphaFS.UnitTest/File Class/File.Copy/{File.Copy.cs => File.Copy_ExistingFile.cs} (89%) rename AlphaFS.UnitTest/File Class/File.Move/{File.Move.cs => File.Move_ExistingFile.cs} (92%) delete mode 100644 AlphaFS.UnitTest/UnitTest Utility/FolderDenyPermission.cs delete mode 100644 AlphaFS.UnitTest/UnitTest Utility/GetRandomFileNameWithDiacriticCharacters.cs delete mode 100644 AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs diff --git a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs index 5e37bec34..20e17e339 100644 --- a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs +++ b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs @@ -42,7 +42,7 @@ private void AlphaFS_BackupFileStream_InitializeInstance(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_FilePortionIsLocked.cs b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_FilePortionIsLocked.cs index aec50fb6e..62de8fafc 100644 --- a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_FilePortionIsLocked.cs +++ b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_FilePortionIsLocked.cs @@ -42,7 +42,7 @@ private void AlphaFS_BackupFileStream_ThrowIOException_FilePortionIsLocked(bool { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_SegmentAlreadyUnlocked.cs b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_SegmentAlreadyUnlocked.cs index 5e0e8091b..475e4c391 100644 --- a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_SegmentAlreadyUnlocked.cs +++ b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_SegmentAlreadyUnlocked.cs @@ -42,7 +42,7 @@ private void AlphaFS_BackupFileStream_ThrowIOException_SegmentAlreadyUnlocked(bo { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_Directory.GetFileInfo.cs b/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_Directory.GetFileInfo.cs index d4d9145fa..785143f54 100644 --- a/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_Directory.GetFileInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_Directory.GetFileInfo.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_GetFileInfoByHandle(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectory(); + var folder = tempRoot.CreateDirectory(); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_File.GetFileInfoByHandle.cs b/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_File.GetFileInfoByHandle.cs index 5acd2e759..258a4c18b 100644 --- a/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_File.GetFileInfoByHandle.cs +++ b/AlphaFS.UnitTest/AlphaFS ByHandleFileInfo Class/AlphaFS_File.GetFileInfoByHandle.cs @@ -42,7 +42,7 @@ private void AlphaFS_File_GetFileInfoByHandle(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File.Compress_And_Decompress.cs b/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File.Compress_And_Decompress.cs index 98d7d0149..577390e29 100644 --- a/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File.Compress_And_Decompress.cs +++ b/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File.Compress_And_Decompress.cs @@ -41,7 +41,7 @@ private void AlphaFS_File_Compress_And_Decompress(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice.cs deleted file mode 100644 index cd9cec065..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice.cs +++ /dev/null @@ -1,163 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_VolumeTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Volume_DefineDosDevice_Local_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var tempFolder = UnitTestConstants.TempPath; - - - #region Regular Drive Mapping - - var drive = string.Format(CultureInfo.InvariantCulture, @"{0}:\", Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter()); - - // Create Regular drive mapping. - var actionIsTrue = false; - try - { - Alphaleonis.Win32.Filesystem.Volume.DefineDosDevice(drive, tempFolder); - actionIsTrue = true; - } - catch - { - } - - Console.WriteLine("Created Regular drive mapping (Should be True): [{0}]\nDrive letter: [{1}] now points to: [{2}]", actionIsTrue, drive, tempFolder); - - Assert.IsTrue(actionIsTrue, "Regular drive mapping should have been created."); - - - var di = new Alphaleonis.Win32.Filesystem.DriveInfo(drive); - var diSysIo = new System.IO.DriveInfo(drive); - - try - { - Assert.IsTrue(UnitTestConstants.Dump(di, -21)); - - Assert.AreEqual(diSysIo.IsReady, di.IsReady); - - } - finally - { - // Remove Regular drive mapping. - actionIsTrue = false; - try - { - Alphaleonis.Win32.Filesystem.Volume.DeleteDosDevice(drive); - actionIsTrue = true; - } - catch - { - } - - - Console.WriteLine(); - Console.WriteLine("Removed Regular drive mapping (Should be True): [{0}]\nDrive letter: [{1}] has been set free.", actionIsTrue, drive); - Console.WriteLine(); - - Assert.IsTrue(actionIsTrue, "Regular drive mapping should have been removed."); - - Assert.IsFalse(System.IO.Directory.Exists(drive), "Drive letter should not be visible."); - } - - #endregion // Regular Drive Mapping - - - #region Symbolic Link Drive Mapping - - try - { - drive = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter(true), Alphaleonis.Win32.Filesystem.Path.VolumeSeparatorChar, Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar); - - // Create Symbolic Link. - var createSymbolicLink = false; - try - { - Alphaleonis.Win32.Filesystem.Volume.DefineDosDevice(drive, tempFolder, Alphaleonis.Win32.Filesystem.DosDeviceAttributes.RawTargetPath); - createSymbolicLink = true; - } - catch - { - } - - Console.WriteLine("\n\nCreated Symbolic link mapping (Should be True): [{0}]\nDrive letter: [{1}] now points to: [{2}]", createSymbolicLink, drive, tempFolder); - - Assert.IsTrue(createSymbolicLink); - - - di = new Alphaleonis.Win32.Filesystem.DriveInfo(drive); - Assert.IsTrue(UnitTestConstants.Dump(di, -21)); - - // The link is created in the NT Device Name namespace and thus not visibile in Explorer. - - // Remove Symbolic Link, no exact match: fail. - - var removeSymbolicLink = false; - try - { - Alphaleonis.Win32.Filesystem.Volume.DeleteDosDevice(drive, "NonExistingFolder", true); - removeSymbolicLink = true; - } - catch - { - } - - Console.WriteLine("\n\nRemoved Symbolic link mapping (Should be False): [{0}]\nDrive letter: [{1}] has NOT been set free.\tNo exactMatch MS-DOS device name found.", removeSymbolicLink, drive); - - Assert.IsFalse(removeSymbolicLink); - } - finally - { - // Remove Symbolic Link, exact match: success. - var removeSymbolicLink = false; - try - { - Alphaleonis.Win32.Filesystem.Volume.DeleteDosDevice(drive, tempFolder, true); - removeSymbolicLink = true; - } - catch - { - } - - Console.WriteLine("\n\nRemoved Symbolic link mapping (Should be True): [{0}]\nDrive letter: [{1}] has been set free.\tFound exactMatch MS-DOS device name.", removeSymbolicLink, drive); - - Assert.IsTrue(removeSymbolicLink); - - Assert.IsFalse(System.IO.Directory.Exists(drive)); - } - - #endregion // Symbolic Link Drive Mapping - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs new file mode 100644 index 000000000..e3d851e9d --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs @@ -0,0 +1,83 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_VolumeTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Volume_DefineDosDevice_RegularDriveMapping_Local_Success() + { + AlphaFS_Volume_DefineDosDevice_RegularDriveMapping(false); + AlphaFS_Volume_DefineDosDevice_RegularDriveMapping(true); + } + + + private void AlphaFS_Volume_DefineDosDevice_RegularDriveMapping(bool isNetwork) + { + using (var tempRoot = new TemporaryDirectory(isNetwork)) + { + var folder = tempRoot.CreateDirectory(); + var drive = string.Format(CultureInfo.InvariantCulture, @"{0}:\", Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter()); + + Assert.IsFalse(System.IO.Directory.Exists(drive), "The drive exists, but it is expected not to."); + + + try + { + Alphaleonis.Win32.Filesystem.Volume.DefineDosDevice(drive, folder.FullName); + + Assert.IsTrue(System.IO.Directory.Exists(drive), "The drive does not exists, but it is expected to."); + + + var dirInfoSysIO = new System.IO.DriveInfo(drive); + + var dirInfoAlphaFS = new Alphaleonis.Win32.Filesystem.DriveInfo(drive); + + UnitTestConstants.Dump(dirInfoSysIO, -21); + UnitTestConstants.Dump(dirInfoAlphaFS, -21); + + + Assert.AreEqual(dirInfoSysIO.Name, dirInfoAlphaFS.Name); + + Assert.AreEqual(dirInfoSysIO.DriveType, dirInfoAlphaFS.DriveType); + + Assert.AreEqual(dirInfoSysIO.TotalSize, dirInfoAlphaFS.TotalSize); + } + finally + { + Alphaleonis.Win32.Filesystem.Volume.DeleteDosDevice(drive); + + Assert.IsFalse(System.IO.Directory.Exists(drive), "The drive exists, but it is expected not to."); + } + } + + Console.WriteLine(); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs new file mode 100644 index 000000000..a92c928c1 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs @@ -0,0 +1,74 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_VolumeTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Volume_DefineDosDevice_SymbolicLinkDriveMapping_Local_Success() + { + AlphaFS_Volume_DefineDosDevice_SymbolicLinkDriveMapping(false); + AlphaFS_Volume_DefineDosDevice_SymbolicLinkDriveMapping(true); + } + + + [TestMethod] + public void AlphaFS_Volume_DefineDosDevice_SymbolicLinkDriveMapping(bool isNetwork) + { + using (var tempRoot = new TemporaryDirectory(isNetwork)) + { + var folder = tempRoot.CreateDirectory(); + var drive = string.Format(CultureInfo.InvariantCulture, @"{0}:\", Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter(true)); + + Assert.IsFalse(System.IO.Directory.Exists(drive), "The drive exists, but it is expected not to."); + + + try + { + Alphaleonis.Win32.Filesystem.Volume.DefineDosDevice(drive, folder.FullName, Alphaleonis.Win32.Filesystem.DosDeviceAttributes.RawTargetPath); + + + // Remove Symbolic Link, no exact match: fail. + + ExceptionAssert.FileNotFoundException(() => Alphaleonis.Win32.Filesystem.Volume.DeleteDosDevice(drive, folder.FullName)); + } + finally + { + // Remove Symbolic Link, exact match: success. + + Alphaleonis.Win32.Filesystem.Volume.DeleteDosDevice(drive, folder.FullName, true); + + Assert.IsFalse(System.IO.Directory.Exists(drive), "The drive exists, but it is expected not to."); + } + } + + Console.WriteLine(); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs index 3b6b8062f..be8788828 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs @@ -50,7 +50,10 @@ private void AlphaFS_Volume_GetDriveFormat(bool isNetwork) Console.Write("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveName); - if (logicalDrive.DriveType == System.IO.DriveType.CDRom) + + // Skip mapped drives and CDRom drives. + + if (logicalDrive.DriveType == System.IO.DriveType.NoRootDirectory || logicalDrive.DriveType == System.IO.DriveType.CDRom) { Console.WriteLine(); continue; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs index 6c78e1bcf..b47d25d70 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs @@ -39,7 +39,9 @@ public void AlphaFS_Volume_GetDriveNameForNtDeviceName_And_GetVolumeGuidForNtDev foreach (var drive in System.IO.DriveInfo.GetDrives()) { - if (drive.DriveType == System.IO.DriveType.Network) + // Skip mapped drives and network drives. + + if (drive.DriveType == System.IO.DriveType.NoRootDirectory || drive.DriveType == System.IO.DriveType.Network) continue; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs index 4d72e2ea0..23af4945c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs @@ -40,7 +40,9 @@ public void AlphaFS_Volume_GetUniqueVolumeNameForPath_Local_Success() foreach (var drive in System.IO.DriveInfo.GetDrives()) { - if (drive.DriveType == System.IO.DriveType.Network) + // Skip mapped drives and network drives. + + if (drive.DriveType == System.IO.DriveType.NoRootDirectory || drive.DriveType == System.IO.DriveType.Network) continue; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo.cs index 882f3d311..b001ec9d6 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo.cs @@ -50,7 +50,10 @@ private void AlphaFS_Volume_GetVolumeInfo_FromLogicalDrive(bool isNetwork) Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveName); - if (logicalDrive.DriveType == System.IO.DriveType.CDRom) + + // Skip mapped drives and CDRom drives. + + if (logicalDrive.DriveType == System.IO.DriveType.NoRootDirectory || logicalDrive.DriveType == System.IO.DriveType.CDRom) { Console.WriteLine(); continue; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs index 6bc84d0a3..b8161234f 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs @@ -44,7 +44,7 @@ public void AlphaFS_Volume_GetXxx_Local_Success() foreach (var logicalDrive in System.IO.DriveInfo.GetDrives()) { - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, logicalDrive.Name); + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\n", ++logicalDriveCount, logicalDrive.Name); if (logicalDrive.DriveType == System.IO.DriveType.CDRom) { @@ -59,13 +59,15 @@ public void AlphaFS_Volume_GetXxx_Local_Success() var deviceNameFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumeDeviceName(logicalDrive.Name); - Console.WriteLine("\n\tGetVolumeDeviceName\t\t\t: [{0}]", deviceNameFromLogicalDrive); + Console.WriteLine("\tGetVolumeDeviceName\t\t\t: [{0}]", deviceNameFromLogicalDrive); Assert.IsNotNull(deviceNameFromLogicalDrive); - if (logicalDrive.DriveType != System.IO.DriveType.Network) + // Skip mapped drives and network drives. + + if (logicalDrive.DriveType != System.IO.DriveType.NoRootDirectory && logicalDrive.DriveType != System.IO.DriveType.Network) { Assert.IsTrue(deviceNameFromLogicalDrive.StartsWith(deviceNamePrefix)); @@ -74,7 +76,7 @@ public void AlphaFS_Volume_GetXxx_Local_Success() var volumeGuidFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(logicalDrive.Name); - Console.WriteLine("\n\tGetVolumeGuid\t\t\t\t: [{0}]", volumeGuidFromLogicalDrive); + Console.WriteLine("\tGetVolumeGuid\t\t\t\t: [{0}]", volumeGuidFromLogicalDrive); Assert.IsNotNull(volumeGuidFromLogicalDrive); @@ -87,7 +89,7 @@ public void AlphaFS_Volume_GetXxx_Local_Success() var uniqueVolumeNameFromlDriveInputPath = Alphaleonis.Win32.Filesystem.Volume.GetUniqueVolumeNameForPath(logicalDrive.Name); - Console.WriteLine("\n\tGetUniqueVolumeNameForPath\t: [{0}]", uniqueVolumeNameFromlDriveInputPath); + Console.WriteLine("\tGetUniqueVolumeNameForPath\t: [{0}]", uniqueVolumeNameFromlDriveInputPath); Assert.IsNotNull(uniqueVolumeNameFromlDriveInputPath); @@ -99,17 +101,13 @@ public void AlphaFS_Volume_GetXxx_Local_Success() var volumePathNameFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumePathName(logicalDrive.Name); - Console.WriteLine("\n\tGetVolumePathName\t\t\t: [{0}]", volumePathNameFromLogicalDrive); + Console.WriteLine("\tGetVolumePathName\t\t\t: [{0}]\n", volumePathNameFromLogicalDrive); Assert.IsNotNull(volumePathNameFromLogicalDrive); Assert.AreEqual(logicalDrive.Name, volumePathNameFromLogicalDrive); - - - Console.WriteLine(); } - if (logicalDriveCount == 0) UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.SetVolumeMountPoint.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.SetVolumeMountPoint.cs index ec9d737b1..6c022f931 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.SetVolumeMountPoint.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.SetVolumeMountPoint.cs @@ -37,7 +37,7 @@ public void AlphaFS_Volume_SetVolumeMountPoint_And_DeleteVolumeMountPoint_Local_ using (var tempRoot = new TemporaryDirectory()) { - var folder = tempRoot.CreateRandomDirectory(); + var folder = tempRoot.CreateDirectory(); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_EnableEncryption_And_DisableEncryption.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_EnableEncryption_And_DisableEncryption.cs index 9928c9aca..6bf7998c0 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_EnableEncryption_And_DisableEncryption.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_EnableEncryption_And_DisableEncryption.cs @@ -42,7 +42,7 @@ private void AlphaFS_Directory_EnableEncryption_And_DisableEncryption(bool isNet { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectory(); + var folder = tempRoot.CreateDirectory(); Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs index 4fd40f0ea..2104e1ce2 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_EncryptDecrypt(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(); + var folder = tempRoot.CreateTree(); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt_Recursive.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt_Recursive.cs index cc06dde38..f7b0314cf 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt_Recursive.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt_Recursive.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_EncryptDecrypt_Recursive(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(); + var folder = tempRoot.CreateTree(); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_EncryptDecrypt_GetEncryptionStatus.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_EncryptDecrypt_GetEncryptionStatus.cs index dc144fc35..8a31a363a 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_EncryptDecrypt_GetEncryptionStatus.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File_EncryptDecrypt_GetEncryptionStatus.cs @@ -39,7 +39,7 @@ private void AlphaFS_File_EncryptDecrypt_GetEncryptionStatus(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_Directory.GetFileIdInfo.cs b/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_Directory.GetFileIdInfo.cs index a576294b6..04d8cef19 100644 --- a/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_Directory.GetFileIdInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_Directory.GetFileIdInfo.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_GetFileIdInfo(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectory(); + var folder = tempRoot.CreateDirectory(); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_File.GetFileIdInfo.cs b/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_File.GetFileIdInfo.cs index ba63bb038..9d5ce4209 100644 --- a/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_File.GetFileIdInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS FileIdInfo Class/AlphaFS_File.GetFileIdInfo.cs @@ -41,7 +41,7 @@ private void AlphaFS_File_GetFileIdInfo(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_FolderWithSpaceAsName.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_FolderWithSpaceAsName.cs index fff505ba3..603534cfc 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_FolderWithSpaceAsName.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_FolderWithSpaceAsName.cs @@ -44,7 +44,7 @@ private void AlphaFS_Directory_EnumerateFileSystemEntryInfos_FolderWithSpaceAsNa const int maxFso = 5; const int expectedFso = 12; - var folder = tempRoot.CreateRandomDirectoryStructure(maxFso, false, true, true); + var folder = tempRoot.CreateRandomizedAttributesTree(maxFso); Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_MappedDrive.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_MappedDrive.cs index 26dce29e0..6e30ffdc7 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_MappedDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_MappedDrive.cs @@ -33,24 +33,19 @@ public partial class AlphaFS_JunctionsLinksTest public void AlphaFS_Directory_CreateJunction_ThrowArgumentException_MappedDrive_Netwerk_Success() { using (var tempRoot = new TemporaryDirectory()) + using (var connection = new Alphaleonis.Win32.Network.DriveConnection(Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempRoot.CreateDirectory().FullName))) { - var folder = tempRoot.CreateRandomDirectory(); + var mappedPath = connection.LocalName + @"\" + tempRoot.RandomDirectoryName; - using (var connection = new Alphaleonis.Win32.Network.DriveConnection(Alphaleonis.Win32.Filesystem.Path.LocalToUnc(folder.FullName))) - { - var mappedPath = connection.LocalName + @"\" + tempRoot.RandomFileName; + Console.WriteLine("Mapped drive [{0}] to [{1}]", connection.LocalName, connection.Share); - Console.WriteLine("Mapped drive [{0}] to [{1}]", connection.LocalName, connection.Share); + var target = System.IO.Directory.CreateDirectory(mappedPath); - var target = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(mappedPath); + var toDelete = tempRoot.Directory.CreateSubdirectory("ToDelete"); - var toDelete = tempRoot.Directory.CreateSubdirectory("ToDelete"); - - var junction = System.IO.Path.Combine(toDelete.FullName, "JunctionPoint"); - - - ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Directory.CreateJunction(junction, target.FullName)); - } + var junction = System.IO.Path.Combine(toDelete.FullName, "JunctionPoint"); + + ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Directory.CreateJunction(junction, target.FullName)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateHardlink_And_EnumerateHardlinks.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateHardlink_And_EnumerateHardlinks.cs index 051cc69d6..f213cb12e 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateHardlink_And_EnumerateHardlinks.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateHardlink_And_EnumerateHardlinks.cs @@ -38,13 +38,13 @@ public void AlphaFS_File_CreateHardlink_And_EnumerateHardlinks_Local_Success() private void AlphaFS_File_CreateHardlink_And_EnumerateHardlinks() { - using (var tempPath = new TemporaryDirectory()) + using (var tempRoot = new TemporaryDirectory()) { - var hardlinkFolder = System.IO.Path.Combine(tempPath.Directory.FullName, "Hardlinks"); + var hardlinkFolder = System.IO.Path.Combine(tempRoot.Directory.FullName, "Hardlinks"); System.IO.Directory.CreateDirectory(hardlinkFolder); - var file = System.IO.Path.Combine(tempPath.Directory.FullName, "OriginalFile.txt"); + 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. @@ -59,7 +59,7 @@ private void AlphaFS_File_CreateHardlink_And_EnumerateHardlinks() for (var i = 0; i < numCreate; i++) { - var newfile = System.IO.Path.Combine(hardlinkFolder, i + "-Hardlink-" + UnitTestConstants.GetRandomFileName() + ".txt"); + var newfile = System.IO.Path.Combine(hardlinkFolder, i + "-Hardlink-" + tempRoot.RandomTxtFileName); Alphaleonis.Win32.Filesystem.File.CreateHardlink(newfile, file); diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetVerbCommand.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetVerbCommand.cs index 46533eed7..20e2eaf83 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetVerbCommand.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetVerbCommand.cs @@ -44,7 +44,7 @@ private void AlphaFS_Shell32Info_GetVerbCommand(bool isNetwork) using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]\n", file.FullName); diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 08b8cfc6f..fcb76365c 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -143,6 +143,7 @@ AssemblyVersionInfo.cs + @@ -151,9 +152,6 @@ - - - @@ -228,15 +226,15 @@ - + - + - + @@ -383,8 +381,8 @@ - - + + @@ -399,7 +397,7 @@ - + diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ExistingDirectory.cs similarity index 93% rename from AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy.cs rename to AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ExistingDirectory.cs index 7c37f6e29..1bdfec9fb 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ExistingDirectory.cs @@ -32,16 +32,16 @@ public partial class CopyTest [TestMethod] public void AlphaFS_Directory_Copy_LocalAndNetwork_Success() { - AlphaFS_Directory_Copy(false); - AlphaFS_Directory_Copy(true); + AlphaFS_Directory_Copy_ExistingDirectory(false); + AlphaFS_Directory_Copy_ExistingDirectory(true); } - private void AlphaFS_Directory_Copy(bool isNetwork) + private void AlphaFS_Directory_Copy_ExistingDirectory(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folderSrc = tempRoot.CreateRandomDirectoryStructure(5, true); + var folderSrc = tempRoot.CreateRecursiveRandomizedAttributesTree(5); var folderDst = tempRoot.RandomDirectoryFullPath; Console.WriteLine("Src Directory Path: [{0}]", folderSrc.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_WithProgress.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ExistingDirectory_WithProgress.cs similarity index 92% rename from AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_WithProgress.cs rename to AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ExistingDirectory_WithProgress.cs index 43b0c130d..66f530b73 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_WithProgress.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ExistingDirectory_WithProgress.cs @@ -31,18 +31,18 @@ public partial class CopyTest [TestMethod] - public void AlphaFS_Directory_Copy_WithProgress_LocalAndNetwork_Success() + public void AlphaFS_Directory_Copy_ExistingDirectory_WithProgress_LocalAndNetwork_Success() { - AlphaFS_Directory_Copy_WithProgress(false); - AlphaFS_Directory_Copy_WithProgress(true); + AlphaFS_Directory_Copy_ExistingDirectory_WithProgress(false); + AlphaFS_Directory_Copy_ExistingDirectory_WithProgress(true); } - private void AlphaFS_Directory_Copy_WithProgress(bool isNetwork) + private void AlphaFS_Directory_Copy_ExistingDirectory_WithProgress(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folderSrc = tempRoot.CreateRandomDirectoryStructure(5, true); + var folderSrc = tempRoot.CreateRecursiveTree(5); var folderDst = tempRoot.RandomDirectoryFullPath; Console.WriteLine("Src Directory Path: [{0}]", folderSrc.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_Overwrite_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_Overwrite_DestinationFileAlreadyExists.cs index 6ce489067..93f690b23 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_Overwrite_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_Overwrite_DestinationFileAlreadyExists.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_Copy_Overwrite_DestinationFileAlreadyExists(bool { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folderSrc = tempRoot.CreateRandomDirectoryStructure(); + var folderSrc = tempRoot.CreateTree(); var folderDst = tempRoot.RandomDirectoryFullPath; Console.WriteLine("Src Directory Path: [{0}]", folderSrc.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs index 12d8afdd2..0d2fa58c4 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_Copy_ThrowAlreadyExistsException_DestinationFileA { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var srcFolder = tempRoot.CreateRandomDirectoryStructure(); + var srcFolder = tempRoot.CreateTree(); var dstFolder = tempRoot.RandomDirectoryFullPath; Console.WriteLine("Src Directory Path: [{0}]", srcFolder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs index 439916b46..dfd980bd0 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs @@ -41,8 +41,8 @@ private void AlphaFS_Directory_Copy_ThrowUnauthorizedAccessException_UserExplici { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var srcFolder = tempRoot.CreateRandomDirectoryStructure(); - var dstFolder = tempRoot.CreateRandomDirectory(); + var srcFolder = tempRoot.CreateTree(); + var dstFolder = tempRoot.CreateDirectory(); Console.WriteLine("Src Directory Path: [{0}]", srcFolder.FullName); Console.WriteLine("Dst Directory Path: [{0}]", dstFolder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FilesOnly_NonRecursive.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FilesOnly_NonRecursive.cs index 1171b1f35..bc1ce00c9 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FilesOnly_NonRecursive.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FilesOnly_NonRecursive.cs @@ -45,7 +45,7 @@ private void AlphaFS_Directory_CountFileSystemObjects_FilesOnly_NonRecursive(boo const int maxFso = 10; const int expectedFso = maxFso / 2; - var folder = tempRoot.CreateRandomDirectoryStructure(maxFso); + var folder = tempRoot.CreateTree(maxFso); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FilesOnly_Recursive.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FilesOnly_Recursive.cs index d05a5a3ff..433086f03 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FilesOnly_Recursive.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FilesOnly_Recursive.cs @@ -43,7 +43,7 @@ private void AlphaFS_Directory_CountFileSystemObjects_FilesOnly_Recursive(bool i using (var tempRoot = new TemporaryDirectory(isNetwork)) { const int expectedFso = 10; - var folder = tempRoot.CreateRandomDirectoryStructure(expectedFso); + var folder = tempRoot.CreateTree(expectedFso); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersAndFiles_Recursive.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersAndFiles_Recursive.cs index 4fbd37abf..012a7cf4b 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersAndFiles_Recursive.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersAndFiles_Recursive.cs @@ -45,7 +45,7 @@ private void AlphaFS_Directory_CountFileSystemObjects_FoldersAndFiles_Recursive( const int maxFso = 100; const int expectedFso = 2 * maxFso; - var folder = tempRoot.CreateRandomDirectoryStructure(maxFso); + var folder = tempRoot.CreateTree(maxFso); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersOnly_NonRecursive.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersOnly_NonRecursive.cs index 6baa3392d..f1c8b70ba 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersOnly_NonRecursive.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersOnly_NonRecursive.cs @@ -43,7 +43,7 @@ private void AlphaFS_Directory_CountFileSystemObjects_FoldersOnly_NonRecursive(b using (var tempRoot = new TemporaryDirectory(isNetwork)) { const int expectedFso = 10; - var folder = tempRoot.CreateRandomDirectoryStructure(expectedFso); + var folder = tempRoot.CreateTree(expectedFso); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersOnly_Recursive.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersOnly_Recursive.cs index 95ed02401..48bf456cc 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersOnly_Recursive.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.CountFileSystemObjects/AlphaFS_Directory.CountFileSystemObjects_FoldersOnly_Recursive.cs @@ -46,7 +46,7 @@ private void AlphaFS_Directory_CountFileSystemObjects_FoldersOnly_Recursive(bool const int maxFso = 10; const int expectedSubfolders = expectedFso * expectedFso + expectedFso; - var folder = tempRoot.CreateRandomDirectoryStructure(maxFso, true); + var folder = tempRoot.CreateRecursiveTree(maxFso); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.DeleteEmptySubdirectories/AlphaFS_Directory.DeleteEmptySubdirectories.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.DeleteEmptySubdirectories/AlphaFS_Directory.DeleteEmptySubdirectories.cs index a5f971d2c..1c0d4ada2 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.DeleteEmptySubdirectories/AlphaFS_Directory.DeleteEmptySubdirectories.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.DeleteEmptySubdirectories/AlphaFS_Directory.DeleteEmptySubdirectories.cs @@ -46,7 +46,7 @@ private void AlphaFS_Directory_DeleteEmptySubdirectories(bool isNetwork) const int emptyDirectories = maxDepth * maxDepth / 2; // 50 empty directories. const int remainingDirectories = totalDirectories - emptyDirectories; // 60 remaining directories. - var folder = tempRoot.CreateRandomDirectoryStructure(maxDepth, true); + var folder = tempRoot.CreateRecursiveTree(maxDepth); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowAlreadyExistsException_FileExistsWithSameNameAsDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowAlreadyExistsException_FileExistsWithSameNameAsDirectory.cs index 4c82ba508..79f2aea43 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowAlreadyExistsException_FileExistsWithSameNameAsDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowAlreadyExistsException_FileExistsWithSameNameAsDirectory.cs @@ -41,7 +41,7 @@ private void Directory_CreateDirectory_ThrowAlreadyExistsException_FileExistsWit { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryNotEmptyException_NonEmptyDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryNotEmptyException_NonEmptyDirectory.cs index 2e87b2f62..a97d73dbb 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryNotEmptyException_NonEmptyDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryNotEmptyException_NonEmptyDirectory.cs @@ -41,8 +41,9 @@ private void AlphaFS_Directory_Delete_ThrowDirectoryNotEmptyException_NonEmptyDi { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectory(); - var file = System.IO.Path.Combine(folder.FullName, tempRoot.RandomFileName); + var folder = tempRoot.CreateDirectory(); + + var file = System.IO.Path.Combine(folder.FullName, tempRoot.RandomTxtFileName); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); Console.WriteLine("Input File Path : [{0}]", file); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs index d89d5026d..1781d74aa 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs @@ -41,7 +41,7 @@ private void Directory_Delete_ThrowDirectoryNotFoundException_FileExistsWithSame { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete_ThrowUnauthorizedAccessException_DirectoryHasDenyPermission.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete_ThrowUnauthorizedAccessException_DirectoryHasDenyPermission.cs index 18b5f0d7c..718df778d 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete_ThrowUnauthorizedAccessException_DirectoryHasDenyPermission.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete_ThrowUnauthorizedAccessException_DirectoryHasDenyPermission.cs @@ -44,12 +44,10 @@ private void Directory_Delete_ThrowUnauthorizedAccessException_DirectoryHasDenyP var folder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(tempRoot.Directory.FullName, "Existing Source Folder")); Console.WriteLine("Input Directory Path: [{0}]", folder); - - + // Set DENY permission for current user. - UnitTestConstants.FolderDenyPermission(true, folder.FullName); + tempRoot.SetDirectoryDenyPermission(true, folder.FullName); - try { ExceptionAssert.IOException(() => System.IO.Directory.Delete(folder.FullName)); @@ -61,7 +59,7 @@ private void Directory_Delete_ThrowUnauthorizedAccessException_DirectoryHasDenyP finally { // Remove DENY permission for current user. - UnitTestConstants.FolderDenyPermission(false, folder.FullName); + tempRoot.SetDirectoryDenyPermission(false, folder.FullName); } } diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Exists/Directory.Exists_ExistingDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.Exists/Directory.Exists_ExistingDirectory.cs index 7292fe55a..b3f33e49f 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Exists/Directory.Exists_ExistingDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Exists/Directory.Exists_ExistingDirectory.cs @@ -41,7 +41,7 @@ private void Directory_Exists_ExistingDirectory(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectory(); + var folder = tempRoot.CreateDirectory(); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Exists/Directory.Exists_UseCases.cs b/AlphaFS.UnitTest/Directory Class/Directory.Exists/Directory.Exists_UseCases.cs index f83552853..1fae4876c 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Exists/Directory.Exists_UseCases.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Exists/Directory.Exists_UseCases.cs @@ -53,7 +53,7 @@ private void Directory_Exists_UseCases(bool isNetwork) sysDrive = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(sysDrive); - var randomName = tempRoot.RandomFileName; + var randomName = tempRoot.RandomDirectoryName; // C:\randomName var NonExistingFolder1 = UnitTestConstants.SysDrive + @"\" + randomName; diff --git a/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_AbsolutePath.cs b/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_AbsolutePath.cs index 380f7dc79..66cb093a2 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_AbsolutePath.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_AbsolutePath.cs @@ -41,7 +41,7 @@ private void Directory_GetDirectories_AbsolutePath(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, true, true, true); + var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5); Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_RelativePath.cs b/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_RelativePath.cs index e2e7f3b4c..b0ecc5ec1 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_RelativePath.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_RelativePath.cs @@ -41,7 +41,7 @@ private void Directory_GetDirectories_RelativePath(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, true, true, true); + var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5); var currentDirectory = tempRoot.Directory.Parent.FullName; Environment.CurrentDirectory = currentDirectory; diff --git a/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_WithSearchPattern.cs b/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_WithSearchPattern.cs index 81579e001..86dee2edc 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_WithSearchPattern.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.GetDirectories/Directory.GetDirectories_WithSearchPattern.cs @@ -41,26 +41,18 @@ private void Directory_GetDirectories_WithSearchPattern(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = new System.IO.DirectoryInfo(tempRoot.RandomDirectoryFullPath).FullName; + var folder = tempRoot.RandomDirectoryFullPath; Console.WriteLine("Input Directory Path: [{0}]\n", folder); - var count = 0; var folders = new[] { - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), + tempRoot.RandomDirectoryName, tempRoot.RandomDirectoryName, tempRoot.RandomDirectoryName, tempRoot.RandomDirectoryName, tempRoot.RandomDirectoryName, + tempRoot.RandomDirectoryName, tempRoot.RandomDirectoryName, tempRoot.RandomDirectoryName, tempRoot.RandomDirectoryName, tempRoot.RandomDirectoryName }; + foreach (var folderName in folders) { var newFolder = System.IO.Path.Combine(folder, folderName); @@ -78,7 +70,7 @@ private void Directory_GetDirectories_WithSearchPattern(bool isNetwork) var alphaFSCollection = Alphaleonis.Win32.Filesystem.Directory.GetDirectories(folder, folderResult, System.IO.SearchOption.AllDirectories); Console.WriteLine("\t#{0:000}\t{1}", ++folderCount, folderResult); - + CollectionAssert.AreEquivalent(systemIOCollection, alphaFSCollection); } } diff --git a/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_AbsolutePath.cs b/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_AbsolutePath.cs index 28ceb0c69..e3c5c3f8a 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_AbsolutePath.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_AbsolutePath.cs @@ -41,7 +41,7 @@ private void Directory_GetFiles_AbsolutePath(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, true, true, true); + var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5); Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_RelativePath.cs b/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_RelativePath.cs index e99814156..60ae5e27d 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_RelativePath.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_RelativePath.cs @@ -42,7 +42,7 @@ private void Directory_GetFiles_RelativePath(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, true, true, true); + var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5); var currentDirectory = tempRoot.Directory.Parent.FullName; Environment.CurrentDirectory = currentDirectory; diff --git a/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_WithSearchPattern.cs b/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_WithSearchPattern.cs index 41fc9dddc..e39f4d7c5 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_WithSearchPattern.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.GetFiles/Directory.GetFiles_WithSearchPattern.cs @@ -42,24 +42,15 @@ private void Directory_GetFiles_WithSearchPattern(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectory(); + var folder = tempRoot.CreateDirectory(); Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName); - - + var count = 0; var folders = new[] { - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), - UnitTestConstants.GetRandomFileName(), + tempRoot.RandomString, tempRoot.RandomDirectoryName, tempRoot.RandomTxtFileName, tempRoot.RandomString, tempRoot.RandomDirectoryName, + tempRoot.RandomTxtFileName, tempRoot.RandomString, tempRoot.RandomDirectoryName, tempRoot.RandomTxtFileName, tempRoot.RandomString }; @@ -80,7 +71,7 @@ private void Directory_GetFiles_WithSearchPattern(bool isNetwork) var alphaFSCollection = Alphaleonis.Win32.Filesystem.Directory.GetFiles(folder.FullName, folderResult, System.IO.SearchOption.AllDirectories); Console.WriteLine("\t#{0:000}\t{1}", ++folderCount, folderResult); - + CollectionAssert.AreEquivalent(systemIOCollection, alphaFSCollection); } } diff --git a/AlphaFS.UnitTest/Directory Class/Directory.GetProperties.cs b/AlphaFS.UnitTest/Directory Class/Directory.GetProperties.cs index 5a071ef97..ddd21b8d1 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.GetProperties.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.GetProperties.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_GetProperties(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, true, true, true); + var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5); Console.WriteLine("Aggregated properties of file system objects from Directory: [{0}]\n", folder); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_Overwrite_DestinationDirectoryAlreadyExists.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_Overwrite_DestinationDirectoryAlreadyExists.cs index 55556b34a..d04744241 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_Overwrite_DestinationDirectoryAlreadyExists.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_Overwrite_DestinationDirectoryAlreadyExists.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_Move_Overwrite_DestinationDirectoryAlreadyExists( { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folderSrc = tempRoot.CreateRandomDirectoryStructure(); + var folderSrc = tempRoot.CreateTree(); var folderDst = tempRoot.RandomDirectoryFullPath; Console.WriteLine("Src Directory Path: [{0}]", folderSrc.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowAlreadyExistsException_DestinationDirectoryAlreadyExists.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowAlreadyExistsException_DestinationDirectoryAlreadyExists.cs index ee4a63139..47374d95f 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowAlreadyExistsException_DestinationDirectoryAlreadyExists.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowAlreadyExistsException_DestinationDirectoryAlreadyExists.cs @@ -41,8 +41,8 @@ private void AlphaFS_Directory_Move_ThrowAlreadyExistsException_DestinationDirec { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var srcFolder = tempRoot.CreateRandomDirectoryStructure(); - var dstFfolder = tempRoot.CreateRandomDirectory(); + var srcFolder = tempRoot.CreateTree(); + var dstFfolder = tempRoot.CreateDirectory(); Console.WriteLine("Src Directory Path: [{0}]", srcFolder.FullName); Console.WriteLine("Dst Directory Path: [{0}]", dstFfolder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ToDifferentVolume_EmulateMoveUsingCopyDelete.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ToDifferentVolume_EmulateMoveUsingCopyDelete.cs index 3dc8bf366..4be5f5005 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ToDifferentVolume_EmulateMoveUsingCopyDelete.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ToDifferentVolume_EmulateMoveUsingCopyDelete.cs @@ -43,13 +43,9 @@ private void AlphaFS_Directory_Move_ToDifferentVolume_EmulateMoveUsingCopyDelete using (var tempRoot = new TemporaryDirectory()) { - var folderSrc = isNetwork - ? tempRoot.CreateRandomDirectoryStructure(Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempRoot.RandomDirectoryFullPath), new Random().Next(5, 15), true) - : tempRoot.CreateRandomDirectoryStructure(new Random().Next(5, 15), true); + var folderSrc = isNetwork ? tempRoot.CreateRecursiveTree(5, Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempRoot.RandomDirectoryFullPath)) : tempRoot.CreateRecursiveTree(5); - var folderDst = !isNetwork - ? new System.IO.DirectoryInfo(Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempRoot.RandomDirectoryFullPath)).FullName - : tempRoot.RandomDirectoryFullPath; + var folderDst = !isNetwork ? new System.IO.DirectoryInfo(Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempRoot.RandomDirectoryFullPath)).FullName : tempRoot.RandomDirectoryFullPath; Console.WriteLine("Src Directory Path: [{0}]", folderSrc.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_SameVolume.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_SameVolume.cs index 3eab73a1d..43bbca3df 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_SameVolume.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_SameVolume.cs @@ -41,7 +41,7 @@ private void Directory_Move_SameVolume(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var srcFolder = tempRoot.CreateRandomDirectoryStructure(new Random().Next(5, 15), true); + var srcFolder = tempRoot.CreateRecursiveTree(5); var dstFolder = tempRoot.RandomDirectoryFullPath; Console.WriteLine("Src Directory Path: [{0}]", srcFolder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs index 2ca791bb3..23a89dfb2 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs @@ -41,8 +41,8 @@ private void Directory_Move_ThrowUnauthorizedAccessException_UserExplicitDenyOnD { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var srcFolder = tempRoot.CreateRandomDirectoryStructure(); - var dstFolder = tempRoot.CreateRandomDirectory(); + var srcFolder = tempRoot.CreateTree(); + var dstFolder = tempRoot.CreateDirectory(); Console.WriteLine("Src Directory Path: [{0}]", srcFolder.FullName); Console.WriteLine("Dst Directory Path: [{0}]", dstFolder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/AlphaFS_Directory.HasInheritedPermissions.cs b/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/AlphaFS_Directory.HasInheritedPermissions.cs index 90e968246..38b469b52 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/AlphaFS_Directory.HasInheritedPermissions.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/AlphaFS_Directory.HasInheritedPermissions.cs @@ -42,7 +42,7 @@ private void AlphaFS_Directory_HasInheritedPermissions(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, true, true, true); + var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5); Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/Directory.GetAccessControl.cs b/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/Directory.GetAccessControl.cs index 5d4baefaa..125e9247b 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/Directory.GetAccessControl.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/Directory.GetAccessControl.cs @@ -41,7 +41,7 @@ private void Directory_GetAccessControl(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectory(); + var folder = tempRoot.CreateDirectory(); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/Directory.SetAccessControl.cs b/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/Directory.SetAccessControl.cs index 3ec6549b7..c42ab16d4 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/Directory.SetAccessControl.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_AccessControl/Directory.SetAccessControl.cs @@ -45,7 +45,7 @@ private void Directory_SetAccessControl(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectory(); + var folder = tempRoot.CreateDirectory(); var sysIO = System.IO.Directory.GetAccessControl(folder.FullName); var sysIOaccessRules = sysIO.GetAccessRules(true, true, typeof(NTAccount)); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateAlternateDataStreams.cs b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateAlternateDataStreams.cs index 96c208e28..7f296b592 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateAlternateDataStreams.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateAlternateDataStreams.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -46,7 +46,12 @@ private void AlphaFS_Directory_EnumerateAlternateDataStreams(bool isNetwork) Console.WriteLine("Input Directory Path: [{0}]", folder); - Console.WriteLine("\nA directory is created and {0} streams are added.", UnitTestConstants.AllStreams.Length.ToString(CultureInfo.CurrentCulture)); + 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("\nA directory is created and {0} streams are added.", allStreams.Length.ToString(CultureInfo.CurrentCulture)); var di = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder); di.Create(); @@ -63,11 +68,11 @@ private void AlphaFS_Directory_EnumerateAlternateDataStreams(bool isNetwork) // 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. - var stream1Name = folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + UnitTestConstants.MyStream; - var stream2Name = folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + UnitTestConstants.MyStream2; + var stream1Name = folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream; + var stream2Name = folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream2; Alphaleonis.Win32.Filesystem.File.WriteAllLines(stream1Name, UnitTestConstants.StreamArrayContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath); - Alphaleonis.Win32.Filesystem.File.WriteAllText(stream2Name, UnitTestConstants.StreamStringContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath); + Alphaleonis.Win32.Filesystem.File.WriteAllText(stream2Name, streamStringContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath); @@ -83,7 +88,7 @@ private void AlphaFS_Directory_EnumerateAlternateDataStreams(bool isNetwork) // Show the contents of our streams. Console.WriteLine(); - foreach (var streamName in UnitTestConstants.AllStreams) + foreach (var streamName in allStreams) { Console.WriteLine("\n\tStream name: [{0}]", streamName); @@ -117,8 +122,8 @@ private void AlphaFS_Directory_EnumerateAlternateDataStreams(bool isNetwork) UnitTestConstants.Dump(fileInfo2, -17); - Assert.AreEqual(UnitTestConstants.MyStream, fileInfo1.Name); - Assert.AreEqual(UnitTestConstants.MyStream2, fileInfo2.Name); + Assert.AreEqual(myStream, fileInfo1.Name); + Assert.AreEqual(myStream2, fileInfo2.Name); Assert.IsNull(fileInfo1.EntryInfo); Assert.IsNull(fileInfo2.EntryInfo); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateFileIdBothDirectoryInfo.cs b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateFileIdBothDirectoryInfo.cs index e8773b183..469a6e4d6 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateFileIdBothDirectoryInfo.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateFileIdBothDirectoryInfo.cs @@ -42,7 +42,7 @@ private void AlphaFS_Directory_EnumerateFileIdBothDirectoryInfo(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, false, true, true); + var folder = tempRoot.CreateRandomizedAttributesTree(5); Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateDirectories.cs b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateDirectories.cs index d61f2b68a..3e2432f66 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateDirectories.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateDirectories.cs @@ -42,7 +42,7 @@ private void Directory_EnumerateDirectories(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, true, true, true); + var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5); Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateFileSystemEntries.cs b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateFileSystemEntries.cs index bf98335bb..3b7069e4d 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateFileSystemEntries.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateFileSystemEntries.cs @@ -42,7 +42,7 @@ private void Directory_EnumerateFileSystemEntries(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, true, true, true); + var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5); Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateFiles.cs b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateFiles.cs index 538879daf..93c417fee 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateFiles.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/Directory.EnumerateFiles.cs @@ -42,7 +42,7 @@ private void Directory_EnumerateFiles(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, true, true, true); + var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5); Console.WriteLine("Input Directory Path: [{0}]\n", folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.CopyTimestamps.cs b/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.CopyTimestamps.cs index 9b3a0d9f7..cb8c08e92 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.CopyTimestamps.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.CopyTimestamps.cs @@ -42,11 +42,11 @@ private void AlphaFS_Directory_CopyTimestamps(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder1 = tempRoot.CreateRandomDirectory(); + var folder1 = tempRoot.CreateDirectory(); Thread.Sleep(1500); - var folder2 = tempRoot.CreateRandomDirectory(); + var folder2 = tempRoot.CreateDirectory(); Console.WriteLine("Input Directory1 Path: [{0}]", folder1.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.SetTimestamps.cs b/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.SetTimestamps.cs index 753607b46..a4da4ed8a 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.SetTimestamps.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.SetTimestamps.cs @@ -43,10 +43,12 @@ private void AlphaFS_Directory_SetTimestamps(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectory(); - var symlinkPath = System.IO.Path.Combine(tempRoot.Directory.FullName, UnitTestConstants.GetRandomFileName()) + "-symlink"; + var folder = tempRoot.CreateDirectory(); + + var symlinkPath = System.IO.Path.Combine(tempRoot.Directory.FullName, tempRoot.RandomString) + "_symlink"; Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); + Console.WriteLine("Input SymLink Path : [{0}]", symlinkPath); Alphaleonis.Win32.Filesystem.Directory.CreateSymbolicLink(symlinkPath, folder.FullName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/Directory_Timestamps_CompareTimestamps_NonExistingDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/Directory_Timestamps_CompareTimestamps_NonExistingDirectory.cs index 9caf186e6..7d1cd1bea 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/Directory_Timestamps_CompareTimestamps_NonExistingDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/Directory_Timestamps_CompareTimestamps_NonExistingDirectory.cs @@ -38,40 +38,39 @@ public void CompareTimestamps_NonExistingDirectory_Local_Success() private void CompareTimestamps_NonExistingDirectory() { - UnitTestConstants.PrintUnitTestHeader(false); + using (var tempRoot = new TemporaryDirectory()) + { + var folder = tempRoot.RandomDirectoryFullPath; - var tempPath = UnitTestConstants.SysDrive + @"\NonExistingFolder-" + UnitTestConstants.GetRandomFileName(); + Console.WriteLine("Input Directory Path: [{0}]", folder); - Console.WriteLine("Input Directory Path: [{0}]", tempPath); + var newDateTime = new DateTime(1601, 1, 1); + var newDateTimeLocaltime = new DateTime(1601, 1, 1).ToLocalTime(); - Assert.IsFalse(System.IO.Directory.Exists(tempPath)); + UnitTestConstants.Dump(newDateTime, -11); + UnitTestConstants.Dump(newDateTimeLocaltime, -11); + + Assert.AreEqual(newDateTime, System.IO.Directory.GetCreationTimeUtc(folder)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetCreationTimeUtc(folder)); + + Assert.AreEqual(newDateTime, System.IO.Directory.GetLastAccessTimeUtc(folder)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTimeUtc(folder)); + + Assert.AreEqual(newDateTime, System.IO.Directory.GetLastWriteTimeUtc(folder)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTimeUtc(folder)); - var newDateTime = new DateTime(1601, 1, 1); - var newDateTimeLocaltime = new DateTime(1601, 1, 1).ToLocalTime(); + Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetCreationTime(folder)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetCreationTime(folder)); - Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetCreationTime(tempPath)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetCreationTime(tempPath)); - - Assert.AreEqual(newDateTime, System.IO.Directory.GetCreationTimeUtc(tempPath)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetCreationTimeUtc(tempPath)); - - - Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetLastAccessTime(tempPath)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTime(tempPath)); - - Assert.AreEqual(newDateTime, System.IO.Directory.GetLastAccessTimeUtc(tempPath)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTimeUtc(tempPath)); - - - Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetLastWriteTime(tempPath)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTime(tempPath)); - - Assert.AreEqual(newDateTime, System.IO.Directory.GetLastWriteTimeUtc(tempPath)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTimeUtc(tempPath)); + Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetLastAccessTime(folder)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTime(folder)); + Assert.AreEqual(newDateTimeLocaltime, System.IO.Directory.GetLastWriteTime(folder)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTime(folder)); + } Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingDirectory.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingDirectory.cs index 999ac491d..9adf4a966 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingDirectory.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingDirectory.cs @@ -41,7 +41,7 @@ private void DirectoryInfo_InitializeInstance_ExistingDirectory(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectory(); + var folder = tempRoot.CreateDirectory(); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/DirectoryInfo.MoveTo_FolderToEmptyFolder.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/DirectoryInfo.MoveTo_FolderToEmptyFolder.cs index 01ef70d86..d53ab2c58 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/DirectoryInfo.MoveTo_FolderToEmptyFolder.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/DirectoryInfo.MoveTo_FolderToEmptyFolder.cs @@ -41,30 +41,26 @@ private void DirectoryInfo_MoveTo_FolderToEmptyFolder(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var testfolder = UnitTestConstants.GetRandomFileName(); + var testfolder = tempRoot.RandomDirectoryName; var folderSrc = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(System.IO.Path.Combine(tempRoot.Directory.FullName, testfolder)); - var folderDst = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(tempRoot.Directory.FullName, "Existing Destination Folder")); + var folderDst = tempRoot.CreateDirectory(); Console.WriteLine("Input Directory Path: [{0}]", folderSrc.FullName); Console.WriteLine("\n\tMove folder to: [{0}]", folderDst.FullName); - // Move folder. - var newLocation = System.IO.Path.Combine(folderDst.FullName, testfolder); - - folderSrc.MoveTo(newLocation); - + folderSrc.MoveTo(System.IO.Path.Combine(folderDst.FullName, testfolder)); folderSrc.Refresh(); folderDst.Refresh(); Assert.IsTrue(folderSrc.Exists, "It is expected that the source exists, but is does not."); + Assert.AreEqual(folderSrc.Parent.FullName, folderDst.FullName); } - - + Console.WriteLine(); } } diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/DirectoryInfo.MoveTo_Rename.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/DirectoryInfo.MoveTo_Rename.cs index 8df648e60..5164c9d69 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/DirectoryInfo.MoveTo_Rename.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/DirectoryInfo.MoveTo_Rename.cs @@ -41,31 +41,32 @@ private void DirectoryInfo_MoveTo_Rename(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var newFolderName = UnitTestConstants.GetRandomFileName(); + var newFolderName = "Rename_to_" + tempRoot.RandomDirectoryName; - var folderSrc = new Alphaleonis.Win32.Filesystem.DirectoryInfo(System.IO.Path.Combine(tempRoot.Directory.FullName, "Source Folder")); - var folderDst = new System.IO.DirectoryInfo(System.IO.Path.Combine(tempRoot.Directory.FullName, newFolderName)); + var dirInfoAlphaFS = new Alphaleonis.Win32.Filesystem.DirectoryInfo(tempRoot.RandomDirectoryFullPath); - Console.WriteLine("Input Directory Path: [{0}]", folderSrc.FullName); - Console.WriteLine("\n\tRename folder to: [{0}]", folderDst.Name); + 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. - folderSrc.Create(); + dirInfoAlphaFS.Create(); // Rename folder. - folderSrc.MoveTo(folderDst.FullName); + dirInfoAlphaFS.MoveTo(dirInfoSystemIO.FullName); - folderSrc.Refresh(); - folderDst.Refresh(); + dirInfoAlphaFS.Refresh(); + dirInfoSystemIO.Refresh(); - Assert.IsTrue(folderSrc.Exists, "It is expected that the source exists, but is does not."); - Assert.AreEqual(folderSrc.Parent.FullName, folderDst.Parent.FullName); - } + 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(); } diff --git a/AlphaFS.UnitTest/File Class/AlphaFS_File.EnumerateAlternateDataStreams.cs b/AlphaFS.UnitTest/File Class/AlphaFS_File.EnumerateAlternateDataStreams.cs index 3595461ec..3857e254d 100644 --- a/AlphaFS.UnitTest/File Class/AlphaFS_File.EnumerateAlternateDataStreams.cs +++ b/AlphaFS.UnitTest/File Class/AlphaFS_File.EnumerateAlternateDataStreams.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -42,12 +42,17 @@ private void AlphaFS_EnumerateAlternateDataStreams(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.RandomFileNoExtensionFullPath; + var file = tempRoot.RandomTxtFileFullPath; Console.WriteLine("Input File Path: [{0}]", file); - Console.WriteLine("\nA file is created and {0} streams are added.", UnitTestConstants.AllStreams.Length.ToString(CultureInfo.CurrentCulture)); + 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("\nA file is created and {0} streams are added.", allStreams.Length.ToString(CultureInfo.CurrentCulture)); // Create file and add 10 characters to it, file is created in ANSI format. System.IO.File.WriteAllText(file, UnitTestConstants.TenNumbers); @@ -71,11 +76,11 @@ private void AlphaFS_EnumerateAlternateDataStreams(bool isNetwork) // 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. - var stream1Name = file + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + UnitTestConstants.MyStream; - var stream2Name = file + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + UnitTestConstants.MyStream2; + var stream1Name = file + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream; + var stream2Name = file + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream2; Alphaleonis.Win32.Filesystem.File.WriteAllLines(stream1Name, UnitTestConstants.StreamArrayContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath); - Alphaleonis.Win32.Filesystem.File.WriteAllText(stream2Name, UnitTestConstants.StreamStringContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath); + Alphaleonis.Win32.Filesystem.File.WriteAllText(stream2Name, streamStringContent, Alphaleonis.Win32.Filesystem.PathFormat.FullPath); @@ -97,7 +102,7 @@ private void AlphaFS_EnumerateAlternateDataStreams(bool isNetwork) // Show the contents of our streams. Console.WriteLine(); - foreach (var streamName in UnitTestConstants.AllStreams) + foreach (var streamName in allStreams) { Console.WriteLine("\n\tStream name: [{0}]", streamName); @@ -122,8 +127,8 @@ private void AlphaFS_EnumerateAlternateDataStreams(bool isNetwork) UnitTestConstants.Dump(fileInfo2, -17); - Assert.AreEqual(UnitTestConstants.MyStream, fileInfo1.Name); - Assert.AreEqual(UnitTestConstants.MyStream2, fileInfo2.Name); + Assert.AreEqual(myStream, fileInfo1.Name); + Assert.AreEqual(myStream2, fileInfo2.Name); Assert.IsNull(fileInfo1.EntryInfo); Assert.IsNull(fileInfo2.EntryInfo); diff --git a/AlphaFS.UnitTest/File Class/AlphaFS_File.GetSize.cs b/AlphaFS.UnitTest/File Class/AlphaFS_File.GetSize.cs index 2287cca5d..1f84fe677 100644 --- a/AlphaFS.UnitTest/File Class/AlphaFS_File.GetSize.cs +++ b/AlphaFS.UnitTest/File Class/AlphaFS_File.GetSize.cs @@ -41,7 +41,7 @@ private void AlphaFS_File_GetSize(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.GetProcessForFileLock.cs b/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.GetProcessForFileLock.cs index f460007ed..716ecbd63 100644 --- a/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.GetProcessForFileLock.cs +++ b/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.GetProcessForFileLock.cs @@ -44,7 +44,7 @@ private void AlphaFS_File_GetProcessForFileLock(bool isNetwork) using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.GetProcessForFileLock_NoLockReturnsNull.cs b/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.GetProcessForFileLock_NoLockReturnsNull.cs index 7f0cc0b40..771f7ff98 100644 --- a/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.GetProcessForFileLock_NoLockReturnsNull.cs +++ b/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.GetProcessForFileLock_NoLockReturnsNull.cs @@ -41,7 +41,7 @@ private void AlphaFS_File_GetProcessForFileLock_NoLockReturnsNull(bool isNetwork { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]\n", file.FullName); diff --git a/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.IsLocked.cs b/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.IsLocked.cs index 4bafc3f9c..e35e9c01d 100644 --- a/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.IsLocked.cs +++ b/AlphaFS.UnitTest/File Class/AlphaFS_File_Lock/AlphaFS_File.IsLocked.cs @@ -41,7 +41,7 @@ private void AlphaFS_File_IsLocked(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_WithProgress.cs b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ExistingFile_WithProgress.cs similarity index 91% rename from AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_WithProgress.cs rename to AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ExistingFile_WithProgress.cs index 858fffb7d..de5868c6b 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_WithProgress.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ExistingFile_WithProgress.cs @@ -31,19 +31,19 @@ public partial class CopyTest [TestMethod] - public void AlphaFS_File_Copy_WithProgress_LocalAndNetwork_Success() + public void AlphaFS_File_Copy_ExistingFile_WithProgress_LocalAndNetwork_Success() { - AlphaFS_File_Copy_WithProgress(false); - AlphaFS_File_Copy_WithProgress(true); + AlphaFS_File_Copy_ExistingFile_WithProgress(false); + AlphaFS_File_Copy_ExistingFile_WithProgress(true); } - private void AlphaFS_File_Copy_WithProgress(bool isNetwork) + private void AlphaFS_File_Copy_ExistingFile_WithProgress(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var fileSource = tempRoot.CreateRandomFile(); - var fileCopy = tempRoot.CreateRandomFile(); + 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); diff --git a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_Overwrite_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_Overwrite_DestinationFileAlreadyExists.cs index f3a6701cc..103dce73e 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_Overwrite_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_Overwrite_DestinationFileAlreadyExists.cs @@ -20,8 +20,8 @@ private void AlphaFS_File_Copy_Overwrite_DestinationFileAlreadyExists(bool isNet { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var srcFile = tempRoot.CreateRandomFile(); - var dstFile = tempRoot.CreateRandomFile(); + var srcFile = tempRoot.CreateFile(); + var dstFile = tempRoot.CreateFile(); Console.WriteLine("Src File Path: [{0}]", srcFile.FullName); Console.WriteLine("Dst File Path: [{0}]", dstFile.FullName); diff --git a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs index f33bbdc89..09ddbb3e7 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs @@ -41,8 +41,8 @@ private void AlphaFS_File_Copy_ThrowAlreadyExistsException_DestinationFileAlread { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var srcFile = tempRoot.CreateRandomFile(); - var dstFile = tempRoot.CreateRandomFile(); + var srcFile = tempRoot.CreateFile(); + var dstFile = tempRoot.CreateFile(); Console.WriteLine("Src File Path: [{0}]", srcFile); Console.WriteLine("Dst File Path: [{0}]", dstFile); diff --git a/AlphaFS.UnitTest/File Class/File.Copy/File.Copy.cs b/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ExistingFile.cs similarity index 89% rename from AlphaFS.UnitTest/File Class/File.Copy/File.Copy.cs rename to AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ExistingFile.cs index 48f066f1c..26f51aa0c 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/File.Copy.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ExistingFile.cs @@ -30,18 +30,18 @@ public partial class CopyTest [TestMethod] - public void File_Copy_LocalAndNetwork_Success() + public void File_Copy_ExistingFile_LocalAndNetwork_Success() { - File_Copy(false); - File_Copy(true); + File_Copy_ExistingFile(false); + File_Copy_ExistingFile(true); } - private void File_Copy(bool isNetwork) + private void File_Copy_ExistingFile(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var fileSource = tempRoot.CreateRandomFile(); + var fileSource = tempRoot.CreateFileRandomizedAttributes(); var fileCopy = tempRoot.RandomTxtFileFullPath; Console.WriteLine("Src File Path: [{0}] [{1}]", Alphaleonis.Utils.UnitSizeToText(fileSource.Length), fileSource.FullName); diff --git a/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowUnauthorizedAccessException_DestinationFileIsReadOnly.cs b/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowUnauthorizedAccessException_DestinationFileIsReadOnly.cs index 1d65dce64..789c68a5d 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowUnauthorizedAccessException_DestinationFileIsReadOnly.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowUnauthorizedAccessException_DestinationFileIsReadOnly.cs @@ -41,7 +41,7 @@ private void File_Copy_ThrowUnauthorizedAccessException_DestinationFileIsReadOnl { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var srcFile = tempRoot.CreateRandomFile(); + var srcFile = tempRoot.CreateFile(); var dstFile = tempRoot.RandomTxtFileFullPath; Console.WriteLine("Src File Path: [{0}]", srcFile.FullName); diff --git a/AlphaFS.UnitTest/File Class/File.Delete/AlphaFS_File.Delete_ThrowFileReadOnlyException_ReadOnlyFile.cs b/AlphaFS.UnitTest/File Class/File.Delete/AlphaFS_File.Delete_ThrowFileReadOnlyException_ReadOnlyFile.cs index 1ee8bfc18..cdb817693 100644 --- a/AlphaFS.UnitTest/File Class/File.Delete/AlphaFS_File.Delete_ThrowFileReadOnlyException_ReadOnlyFile.cs +++ b/AlphaFS.UnitTest/File Class/File.Delete/AlphaFS_File.Delete_ThrowFileReadOnlyException_ReadOnlyFile.cs @@ -41,7 +41,7 @@ private void AlphaFS_File_Delete_ThrowFileReadOnlyException_ReadOnlyFile(bool is { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file); diff --git a/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ExistingFile.cs b/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ExistingFile.cs index b97d66801..4b5384b93 100644 --- a/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ExistingFile.cs +++ b/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ExistingFile.cs @@ -41,7 +41,7 @@ private void File_Delete_ExistingFile(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file); diff --git a/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowUnauthorizedAccessException_PathIsADirectoryNotAFile.cs b/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowUnauthorizedAccessException_PathIsADirectoryNotAFile.cs index 78e8bf802..8da63d37d 100644 --- a/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowUnauthorizedAccessException_PathIsADirectoryNotAFile.cs +++ b/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowUnauthorizedAccessException_PathIsADirectoryNotAFile.cs @@ -41,7 +41,7 @@ private void File_Delete_ThrowUnauthorizedAccessException_PathIsADirectoryNotAFi { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectory(); + var folder = tempRoot.CreateDirectory(); Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); diff --git a/AlphaFS.UnitTest/File Class/File.Exists/File.Exists_ExistingFile.cs b/AlphaFS.UnitTest/File Class/File.Exists/File.Exists_ExistingFile.cs index fd634815b..c164a9a9b 100644 --- a/AlphaFS.UnitTest/File Class/File.Exists/File.Exists_ExistingFile.cs +++ b/AlphaFS.UnitTest/File Class/File.Exists/File.Exists_ExistingFile.cs @@ -41,7 +41,7 @@ private void File_Exists_ExistingFile(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_Overwrite_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_Overwrite_DestinationFileAlreadyExists.cs index 9b110ecf1..4bf3e4a14 100644 --- a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_Overwrite_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_Overwrite_DestinationFileAlreadyExists.cs @@ -41,8 +41,8 @@ private void AlphaFS_File_Move_Overwrite_DestinationFileAlreadyExists(bool isNet { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var fileSource = tempRoot.CreateRandomFile(); - var fileCopy = tempRoot.CreateRandomFile(); + var fileSource = tempRoot.CreateFile(); + var fileCopy = tempRoot.CreateFile(); Console.WriteLine("Source File Path: [{0}]", fileSource.FullName); diff --git a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs index d7f308749..e6aeb44f6 100644 --- a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs @@ -41,7 +41,7 @@ private void AlphaFS_File_Move_ThrowAlreadyExistsException_DestinationFileAlread { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var srcFile = tempRoot.CreateRandomFile(); + var srcFile = tempRoot.CreateFile(); var dstFile = srcFile + "-Existing File"; diff --git a/AlphaFS.UnitTest/File Class/File.Move/File.Move.cs b/AlphaFS.UnitTest/File Class/File.Move/File.Move_ExistingFile.cs similarity index 92% rename from AlphaFS.UnitTest/File Class/File.Move/File.Move.cs rename to AlphaFS.UnitTest/File Class/File.Move/File.Move_ExistingFile.cs index 02e796790..d4c5dc81a 100644 --- a/AlphaFS.UnitTest/File Class/File.Move/File.Move.cs +++ b/AlphaFS.UnitTest/File Class/File.Move/File.Move_ExistingFile.cs @@ -30,18 +30,18 @@ public partial class MoveTest [TestMethod] - public void File_Move_LocalAndNetwork_Success() + public void File_Move_ExistingFile_LocalAndNetwork_Success() { - File_Move(false); - File_Move(true); + File_Move_ExistingFile(false); + File_Move_ExistingFile(true); } - private void File_Move(bool isNetwork) + private void File_Move_ExistingFile(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var srcFile = tempRoot.CreateRandomFile(); + var srcFile = tempRoot.CreateFile(); var dstFile = System.IO.Path.Combine(tempRoot.Directory.FullName, srcFile.Name + "-Moved.File"); diff --git a/AlphaFS.UnitTest/File Class/File.Open/File.OpenRead_OpenReadTwiceShouldNotLock.cs b/AlphaFS.UnitTest/File Class/File.Open/File.OpenRead_OpenReadTwiceShouldNotLock.cs index 2fa560763..5e3e9775b 100644 --- a/AlphaFS.UnitTest/File Class/File.Open/File.OpenRead_OpenReadTwiceShouldNotLock.cs +++ b/AlphaFS.UnitTest/File Class/File.Open/File.OpenRead_OpenReadTwiceShouldNotLock.cs @@ -41,7 +41,7 @@ private void File_OpenRead_OpenReadTwiceShouldNotLock(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/File Class/File.Open/File_Open_Append_NoObjectDisposedException.cs b/AlphaFS.UnitTest/File Class/File.Open/File_Open_Append_NoObjectDisposedException.cs index f85885c91..69491d2be 100644 --- a/AlphaFS.UnitTest/File Class/File.Open/File_Open_Append_NoObjectDisposedException.cs +++ b/AlphaFS.UnitTest/File Class/File.Open/File_Open_Append_NoObjectDisposedException.cs @@ -41,7 +41,7 @@ private void Open_Append_NoObjectDisposedException(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/File Class/File_AccessControl/File.GetAccessControl.cs b/AlphaFS.UnitTest/File Class/File_AccessControl/File.GetAccessControl.cs index 973b70119..d7e62bf9f 100644 --- a/AlphaFS.UnitTest/File Class/File_AccessControl/File.GetAccessControl.cs +++ b/AlphaFS.UnitTest/File Class/File_AccessControl/File.GetAccessControl.cs @@ -43,7 +43,7 @@ private void File_GetAccessControl(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/File Class/File_AccessControl/File.SetAccessControl.cs b/AlphaFS.UnitTest/File Class/File_AccessControl/File.SetAccessControl.cs index e922a3790..c9f4f8392 100644 --- a/AlphaFS.UnitTest/File Class/File_AccessControl/File.SetAccessControl.cs +++ b/AlphaFS.UnitTest/File Class/File_AccessControl/File.SetAccessControl.cs @@ -45,7 +45,7 @@ private void File_SetAccessControl(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]", file.FullName); diff --git a/AlphaFS.UnitTest/File Class/File_Attributes/File.GetAttributes.cs b/AlphaFS.UnitTest/File Class/File_Attributes/File.GetAttributes.cs index d9b4fad5b..27c7e7b1e 100644 --- a/AlphaFS.UnitTest/File Class/File_Attributes/File.GetAttributes.cs +++ b/AlphaFS.UnitTest/File Class/File_Attributes/File.GetAttributes.cs @@ -41,7 +41,7 @@ private void File_GetAttributes(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, true, true, true); + var folder = tempRoot.CreateRecursiveRandomizedAttributesTree(5); Console.WriteLine("Input Directory Path: [{0}]", folder); diff --git a/AlphaFS.UnitTest/File Class/File_Attributes/File.SetAttributes.cs b/AlphaFS.UnitTest/File Class/File_Attributes/File.SetAttributes.cs index 939615668..720ea4b59 100644 --- a/AlphaFS.UnitTest/File Class/File_Attributes/File.SetAttributes.cs +++ b/AlphaFS.UnitTest/File Class/File_Attributes/File.SetAttributes.cs @@ -41,7 +41,7 @@ private void File_SetAttributes(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = tempRoot.CreateRandomDirectoryStructure(5, true); + var folder = tempRoot.CreateRecursiveTree(5); Console.WriteLine("Input Directory Path: [{0}]", folder); diff --git a/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.CopyTimestamps.cs b/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.CopyTimestamps.cs index 6e7d9e2e4..4cdefa061 100644 --- a/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.CopyTimestamps.cs +++ b/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.CopyTimestamps.cs @@ -42,9 +42,9 @@ private void AlphaFS_File_CopyTimestamps(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file1 = tempRoot.CreateRandomFile(); + var file1 = tempRoot.CreateFile(); Thread.Sleep(1500); - var file2 = tempRoot.CreateRandomFile(); + var file2 = tempRoot.CreateFile(); Console.WriteLine("Input File1 Path: [{0}]", file1.FullName); Console.WriteLine("Input File2 Path: [{0}]", file2.FullName); diff --git a/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs b/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs index c7aff481a..1bb762520 100644 --- a/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs +++ b/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs @@ -60,7 +60,7 @@ private void AlphaFS_File_GetChangeTime(bool isNetwork) // 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.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]\n", file.FullName); diff --git a/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.SetTimestamps.cs b/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.SetTimestamps.cs index 273aac57e..4d3639eba 100644 --- a/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.SetTimestamps.cs +++ b/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.SetTimestamps.cs @@ -43,11 +43,12 @@ private void AlphaFS_File_SetTimestamps(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); - var symlinkPath = System.IO.Path.Combine(tempRoot.Directory.FullName, UnitTestConstants.GetRandomFileName()) + "-symlink"; + var symlinkPath = System.IO.Path.Combine(tempRoot.Directory.FullName, tempRoot.RandomString) + "_symlink"; - Console.WriteLine("Input File Path: [{0}]", file); + Console.WriteLine("Input File Path : [{0}]", file); + Console.WriteLine("Input SymLink Path: [{0}]", symlinkPath); Alphaleonis.Win32.Filesystem.File.CreateSymbolicLink(symlinkPath, file.FullName); diff --git a/AlphaFS.UnitTest/File Class/File_Timestamps/File_Timestamps_CompareTimestamps_NonExistingFile.cs b/AlphaFS.UnitTest/File Class/File_Timestamps/File_Timestamps_CompareTimestamps_NonExistingFile.cs index 951ed30da..b60754cfa 100644 --- a/AlphaFS.UnitTest/File Class/File_Timestamps/File_Timestamps_CompareTimestamps_NonExistingFile.cs +++ b/AlphaFS.UnitTest/File Class/File_Timestamps/File_Timestamps_CompareTimestamps_NonExistingFile.cs @@ -38,40 +38,39 @@ public void CompareTimestamps_NonExistingFile_Local_Success() private void CompareTimestamps_NonExistingFile() { - UnitTestConstants.PrintUnitTestHeader(false); + using (var tempRoot = new TemporaryDirectory()) + { + var file = tempRoot.RandomTxtFileFullPath; - var tempPath = UnitTestConstants.SysDrive + @"\nonExistingFile-" + UnitTestConstants.GetRandomFileName(); + Console.WriteLine("Input File Path: [{0}]", file); - Console.WriteLine("Input File Path: [{0}]", tempPath); + var newDateTime = new DateTime(1601, 1, 1); + var newDateTimeLocaltime = new DateTime(1601, 1, 1).ToLocalTime(); - Assert.IsFalse(System.IO.File.Exists(tempPath)); + UnitTestConstants.Dump(newDateTime, -11); + UnitTestConstants.Dump(newDateTimeLocaltime, -11); - var newDateTime = new DateTime(1601, 1, 1); - var newDateTimeLocaltime = new DateTime(1601, 1, 1).ToLocalTime(); + Assert.AreEqual(newDateTime, System.IO.File.GetCreationTimeUtc(file)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetCreationTimeUtc(file)); + Assert.AreEqual(newDateTime, System.IO.File.GetLastAccessTimeUtc(file)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetLastAccessTimeUtc(file)); - Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetCreationTime(tempPath)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetCreationTime(tempPath)); - - Assert.AreEqual(newDateTime, System.IO.File.GetCreationTimeUtc(tempPath)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetCreationTimeUtc(tempPath)); + Assert.AreEqual(newDateTime, System.IO.File.GetLastWriteTimeUtc(file)); + Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetLastWriteTimeUtc(file)); - Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetLastAccessTime(tempPath)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetLastAccessTime(tempPath)); + Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetCreationTime(file)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetCreationTime(file)); - Assert.AreEqual(newDateTime, System.IO.File.GetLastAccessTimeUtc(tempPath)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetLastAccessTimeUtc(tempPath)); - - - Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetLastWriteTime(tempPath)); - Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetLastWriteTime(tempPath)); - - Assert.AreEqual(newDateTime, System.IO.File.GetLastWriteTimeUtc(tempPath)); - Assert.AreEqual(newDateTime, Alphaleonis.Win32.Filesystem.File.GetLastWriteTimeUtc(tempPath)); + Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetLastAccessTime(file)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetLastAccessTime(file)); + Assert.AreEqual(newDateTimeLocaltime, System.IO.File.GetLastWriteTime(file)); + Assert.AreEqual(newDateTimeLocaltime, Alphaleonis.Win32.Filesystem.File.GetLastWriteTime(file)); + } Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingFile.cs b/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingFile.cs index 16e42b31f..0ec9e9f8b 100644 --- a/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingFile.cs +++ b/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingFile.cs @@ -41,7 +41,7 @@ private void FileInfo_InitializeInstance_ExistingFile(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); var alphaFSFileInfo = new Alphaleonis.Win32.Filesystem.FileInfo(file.FullName); diff --git a/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetFinalPathNameByHandle/AlphaFS_Path.GetFinalPathNameByHandle_ToGetFileStreamName.cs b/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetFinalPathNameByHandle/AlphaFS_Path.GetFinalPathNameByHandle_ToGetFileStreamName.cs index 8034c32af..394329481 100644 --- a/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetFinalPathNameByHandle/AlphaFS_Path.GetFinalPathNameByHandle_ToGetFileStreamName.cs +++ b/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetFinalPathNameByHandle/AlphaFS_Path.GetFinalPathNameByHandle_ToGetFileStreamName.cs @@ -39,7 +39,7 @@ public void AlphaFS_Path_GetFinalPathNameByHandle_ToGetFileStreamName_Success() using (var tempRoot = new TemporaryDirectory()) { - var file = tempRoot.CreateRandomFile(); + var file = tempRoot.CreateFile(); Console.WriteLine("Input File Path: [{0}]\n", file.FullName); diff --git a/AlphaFS.UnitTest/UnitTest Utility/DirectoryAssert.cs b/AlphaFS.UnitTest/UnitTest Utility/DirectoryAssert.cs index 9fb878ea1..89b84b00b 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/DirectoryAssert.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/DirectoryAssert.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System.Globalization; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -28,31 +29,35 @@ public static class DirectoryAssert public static void Exists(string directoryPath) { if (!System.IO.Directory.Exists(directoryPath)) - throw new AssertFailedException(string.Format("The directory: [{0}] does not exist, but is expected to.", directoryPath)); + throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "The directory: [{0}] does not exist, but is expected to.", directoryPath)); } - public static void IsEncrypted(string dirPath) + + public static void IsEncrypted(string directoryPath) { - if ((System.IO.File.GetAttributes(dirPath) & System.IO.FileAttributes.Encrypted) == 0) - throw new AssertFailedException(string.Format("The directory: [{0}] is not encrypted, but is expected to.", dirPath)); + 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 dirPath) + + public static void IsNotEncrypted(string directoryPath) { - if ((System.IO.File.GetAttributes(dirPath) & System.IO.FileAttributes.Encrypted) != 0) - throw new AssertFailedException(string.Format("The directory: [{0}] is encrypted, but is expected not to.", dirPath)); + 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 dirPath) + + public static void IsCompressed(string directoryPath) { - if ((System.IO.File.GetAttributes(dirPath) & System.IO.FileAttributes.Compressed) == 0) - throw new AssertFailedException(string.Format("The directory: [{0}] is not compressed, but is expected to.", dirPath)); + 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 dirPath) + + public static void IsNotCompressed(string directoryPath) { - if ((System.IO.File.GetAttributes(dirPath) & System.IO.FileAttributes.Compressed) != 0) - throw new AssertFailedException(string.Format("The directory: [{0}] is compressed, but is expected not to.", dirPath)); + 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)); } } } diff --git a/AlphaFS.UnitTest/UnitTest Utility/FileAssert.cs b/AlphaFS.UnitTest/UnitTest Utility/FileAssert.cs index 362ba1f69..74f2a7696 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/FileAssert.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/FileAssert.cs @@ -32,6 +32,7 @@ public static void Exists(string 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; @@ -51,6 +52,7 @@ public static void AreEqual(string expectedFilePath, string actualFilePath) } } + public static void AreNotEqual(string expectedFilePath, string actualFilePath) { var position = 0; @@ -72,24 +74,28 @@ public static void AreNotEqual(string expectedFilePath, string actualFilePath) 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) diff --git a/AlphaFS.UnitTest/UnitTest Utility/FolderDenyPermission.cs b/AlphaFS.UnitTest/UnitTest Utility/FolderDenyPermission.cs deleted file mode 100644 index 274ea8dee..000000000 --- a/AlphaFS.UnitTest/UnitTest Utility/FolderDenyPermission.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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.AccessControl; - -namespace AlphaFS.UnitTest -{ - public static partial class UnitTestConstants - { - public static void FolderDenyPermission(bool create, string tempPath) - { - var user = (Environment.UserDomainName + @"\" + Environment.UserName).TrimStart('\\'); - - var dirInfo = new DirectoryInfo(tempPath); - DirectorySecurity dirSecurity; - - // ╔═════════════╦═════════════╦═══════════════════════════════╦════════════════════════╦══════════════════╦═══════════════════════╦═════════════╦═════════════╗ - // ║ ║ 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 ║ - // ╚═════════════╩═════════════╩═══════════════════════════════╩════════════════════════╩══════════════════╩═══════════════════════╩═════════════╩═════════════╝ - - var rule = new FileSystemAccessRule(user, - FileSystemRights.FullControl, - InheritanceFlags.ContainerInherit | - InheritanceFlags.ObjectInherit, - PropagationFlags.None, AccessControlType.Deny); - - - // Create and set DENY for current user. - if (create) - { - dirInfo.Create(); - - dirSecurity = dirInfo.GetAccessControl(); - dirSecurity.AddAccessRule(rule); - dirInfo.SetAccessControl(dirSecurity); - } - - // Remove DENY for current user. - else - { - dirSecurity = dirInfo.GetAccessControl(); - dirSecurity.RemoveAccessRule(rule); - dirInfo.SetAccessControl(dirSecurity); - } - } - } -} diff --git a/AlphaFS.UnitTest/UnitTest Utility/GetRandomFileNameWithDiacriticCharacters.cs b/AlphaFS.UnitTest/UnitTest Utility/GetRandomFileNameWithDiacriticCharacters.cs deleted file mode 100644 index 2d9d6ad84..000000000 --- a/AlphaFS.UnitTest/UnitTest Utility/GetRandomFileNameWithDiacriticCharacters.cs +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS.UnitTest -{ - /// Containts static variables, used by unit tests. - public static partial class UnitTestConstants - { - /// Returns a random folder name or file name, possibly with diacritic characters. - public static string GetRandomFileName() - { - var randomFileName = System.IO.Path.GetRandomFileName(); - - switch (new Random(DateTime.UtcNow.Millisecond).Next(1, 3)) - { - case 1: - return randomFileName.Replace("a", "ä").Replace("e", "ë").Replace("i", "ï").Replace("o", "ö").Replace("u", "ü"); - - case 2: - return randomFileName.Replace("a", "á").Replace("e", "é").Replace("i", "í").Replace("o", "ó").Replace("u", "ú"); - - case 3: - return randomFileName.Replace("a", "â").Replace("e", "ê").Replace("i", "î").Replace("o", "ô").Replace("u", "û"); - - default: - return randomFileName; - } - } - } -} diff --git a/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs b/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs deleted file mode 100644 index f05b7ca29..000000000 --- a/AlphaFS.UnitTest/UnitTest Utility/InputPaths.cs +++ /dev/null @@ -1,134 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 -{ - /// Containts static variables, used by unit tests. - public static partial class UnitTestConstants - { - /// The Computer name. - public static readonly string LocalHost = Environment.MachineName; - - - /// The Computer system drive. For example "C:". - public static readonly string SysDrive = Environment.GetEnvironmentVariable("SystemDrive"); - - - public static readonly string MyStream = "ӍƔŞtrëƛɱ-" + GetRandomFileName(); - public static readonly string MyStream2 = "myStreamTWO-" + GetRandomFileName(); - public static readonly string[] AllStreams = {MyStream, MyStream2}; - public static readonly string StreamStringContent = "(1) Computer: [" + LocalHost + "]" + "\tHello there, " + Environment.UserName; - 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) " + TextHelloWorld + " " + TextUnicode - }; - - - 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.GlobalRootPrefix + @"device\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 + LocalHost + @"\Share", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\f", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fi", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fil", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.e", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ex", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ext", - - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\f", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fi", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fil", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.e", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ex", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ext" - }; - } -} diff --git a/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs index f6c700c9c..fafe32517 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs @@ -1,4 +1,4 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -21,6 +21,7 @@ using System; using System.Globalization; +using System.Security.AccessControl; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -44,12 +45,13 @@ public TemporaryDirectory(bool isNetwork, string folderPrefix = null, string roo if (isNetwork) root = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(root); + UnitTestConstants.PrintUnitTestHeader(isNetwork); do { - Directory = new System.IO.DirectoryInfo(System.IO.Path.Combine(root, folderPrefix + "." + UnitTestConstants.GetRandomFileName().Substring(0, 6))); + Directory = new System.IO.DirectoryInfo(System.IO.Path.Combine(root, folderPrefix + "." + RandomString)); } while (Directory.Exists); @@ -64,141 +66,257 @@ public TemporaryDirectory(bool isNetwork, string folderPrefix = null, string roo public System.IO.DirectoryInfo Directory { get; private set; } - /// Returns the full path to a non-existing directory with a random name, such as: "C:\Users\UserName\AppData\Local\Temp\AlphaFS.TempRoot.lpqdzf\Directory_wq��nmvh.z03". - public string RandomDirectoryFullPath + /// Returns a random directory name, such as: "Directory_wqáánmvh". + public string RandomDirectoryName { - get { return System.IO.Path.Combine(Directory.FullName, "Directory_" + RandomFileName); } + get { return string.Format(CultureInfo.InvariantCulture, "Directory.{0}", RandomString); } } - /// Returns the full path to a non-existing file with a random name, such as: "C:\Users\UserName\AppData\Local\Temp\AlphaFS.TempRoot.lpqdzf\File_wq��nmvh.txt". - public string RandomTxtFileFullPath + /// Returns the full path to a non-existing file with a random name, such as: "File_wqáánmvh.txt". + public string RandomTxtFileName { - get { return RandomFileNoExtensionFullPath + ".txt"; } + get { return string.Format(CultureInfo.InvariantCulture, "File_{0}.txt", RandomString); } } - /// Returns the full path to a non-existing file with a random name and without an extension, such as: "C:\Users\UserName\AppData\Local\Temp\AlphaFS.TempRoot.lpqdzf\File_wq��nmvh". - public string RandomFileNoExtensionFullPath + /// Returns the full path to a non-existing directory with a random name, such as: "C:\Users\UserName\AppData\Local\Temp\AlphaFS.TempRoot.lpqdzf\Directory_wqáánmvh.z03". + public string RandomDirectoryFullPath { - get { return System.IO.Path.Combine(Directory.FullName, "File_" + System.IO.Path.GetFileNameWithoutExtension(RandomFileName)); } + get { return System.IO.Path.Combine(Directory.FullName, RandomDirectoryName); } } - /// Returns a random folder or file name, such as: "wq��nmvh.z03". - public string RandomFileName + /// Returns the full path to a non-existing file with a random name, such as: "C:\Users\UserName\AppData\Local\Temp\AlphaFS.TempRoot.lpqdzf\File_wqáánmvh.txt". + public string RandomTxtFileFullPath { - get { return UnitTestConstants.GetRandomFileName(); } + get { return System.IO.Path.Combine(Directory.FullName, RandomTxtFileName); } } - public override string ToString() + /// Returns the full path to a non-existing file with a random name and without an extension, such as: "C:\Users\UserName\AppData\Local\Temp\AlphaFS.TempRoot.lpqdzf\File_wqáánmvh". + public string RandomFileNoExtensionFullPath { - return Directory.FullName; + get { return System.IO.Path.Combine(Directory.FullName, System.IO.Path.GetFileNameWithoutExtension(RandomTxtFileName)); } } + + + /// Returns a random string of 8 characters in length, possibly with diacritic characters. + public string RandomString + { + get + { + var randomFileName = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetRandomFileName()); + + switch (new Random(DateTime.UtcNow.Millisecond).Next(1, 3)) + { + case 1: + return randomFileName.Replace("a", "ä").Replace("e", "ë").Replace("i", "ï").Replace("o", "ö").Replace("u", "ü"); + + case 2: + return randomFileName.Replace("a", "á").Replace("e", "é").Replace("i", "í").Replace("o", "ó").Replace("u", "ú"); + case 3: + return randomFileName.Replace("a", "â").Replace("e", "ê").Replace("i", "î").Replace("o", "ô").Replace("u", "û"); + + default: + return randomFileName; + } + } + } + #endregion // Properties #region Methods + + /// Returns a instance to an existing directory. + public System.IO.DirectoryInfo CreateDirectory() + { + return CreateDirectory(null); + } + /// Returns a instance to an existing directory, possibly with hidden and/or read-only attributes set. - public System.IO.DirectoryInfo CreateDirectory(string folderFullPath, bool readOnly = false, bool hidden = false) + public System.IO.DirectoryInfo CreateDirectoryRandomizedAttributes() { - var dirInfo = System.IO.Directory.CreateDirectory(!Alphaleonis.Utils.IsNullOrWhiteSpace(folderFullPath) ? folderFullPath : RandomDirectoryFullPath); + return CreateDirectory(null, true, true); + } - if (readOnly && new Random(DateTime.UtcNow.Millisecond).Next(0, 1000) % 2 == 0) - dirInfo.Attributes |= System.IO.FileAttributes.ReadOnly; - - if (hidden && new Random(DateTime.UtcNow.Millisecond).Next(0, 1000) % 2 == 0) - dirInfo.Attributes |= System.IO.FileAttributes.Hidden; - - return dirInfo; - } - /// Returns a instance to an existing directory. - public System.IO.DirectoryInfo CreateRandomDirectory() + /// Returns a instance to an existing file. + public System.IO.FileInfo CreateFile() { - return CreateDirectory(null); + return CreateFile(null); } - - /// Returns a instance to an existing file, possibly with hidden and/or read-only attributes set. - public System.IO.FileInfo CreateFile(string fileFullPath, bool readOnly = false, bool hidden = false) + + /// Returns a instance to an existing file, possibly with hidden and/or read-only attributes set. + public System.IO.FileInfo CreateFileRandomizedAttributes() { - var fileInfo = new System.IO.FileInfo(!Alphaleonis.Utils.IsNullOrWhiteSpace(fileFullPath) ? fileFullPath : RandomTxtFileFullPath); + return CreateFile(null, true, true); + } - // File size is min 0 bytes, max 1 MB. - using (var fs = fileInfo.Create()) - fs.SetLength(new Random(DateTime.UtcNow.Millisecond).Next(0, 1048576)); - - if (readOnly && new Random(DateTime.UtcNow.Millisecond).Next(0, 1000) % 2 == 0) - fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly; - if (hidden && new Random(DateTime.UtcNow.Millisecond).Next(0, 1000) % 2 == 0) - fileInfo.Attributes |= System.IO.FileAttributes.Hidden; - - return fileInfo; + + + /// Creates a directory structure of levels deep, populated with subdirectories and files with of random size. + public System.IO.DirectoryInfo CreateTree(int level = 1) + { + return CreateTreeCore(null, level, false, false, false); } - /// Returns a instance to an existing file. - public System.IO.FileInfo CreateRandomFile() + /// Creates a recursive directory structure of levels deep, populated with subdirectories and files with of random size. + public System.IO.DirectoryInfo CreateRecursiveTree(int level = 1) { - return CreateFile(null); + return CreateTreeCore(null, level, true, false, false); } - public System.IO.DirectoryInfo CreateRandomDirectoryStructure(int max = 1, string rootPath = null) + /// Creates a recursive directory structure of levels deep, populated with subdirectories and files with of random size. + public System.IO.DirectoryInfo CreateRecursiveTree(int level, string rootFullPath) { - return CreateRandomDirectoryStructure(rootPath, max, false); + return CreateTreeCore(rootFullPath, level, true, false, false); } - public System.IO.DirectoryInfo CreateRandomDirectoryStructure(int max, bool recurse, bool readOnly = false, bool hidden = false) + /// Creates a directory structure of levels deep, populated with subdirectories and files with of random size. + public System.IO.DirectoryInfo CreateRandomizedAttributesTree(int level = 1) { - return CreateRandomDirectoryStructure(null, max, recurse, readOnly, hidden); + return CreateTreeCore(null, level, false, true, true); } - public System.IO.DirectoryInfo CreateRandomDirectoryStructure(string rootPath, int max, bool recurse, bool readOnly = false, bool hidden = false) + /// Creates a recursive directory structure of levels deep, populated with subdirectories and files with of random size. + public System.IO.DirectoryInfo CreateRecursiveRandomizedAttributesTree(int level = 1) { - var dirInfo = CreateDirectory(rootPath, readOnly, hidden); + return CreateTreeCore(null, level, true, true, true); + } + + + /// Creates an, optional recursive, directory structure of levels deep, populated with subdirectories and files with of random size and possibly with hidden and/or read-only attributes set. + private System.IO.DirectoryInfo CreateTreeCore(string rootFullPath, int level, bool recurse, bool readOnly, bool hidden) + { + var dirInfo = CreateDirectory(rootFullPath, readOnly, hidden); var folderCount = 0; - - for (var fsoCount = 0; fsoCount < max; fsoCount++) + + for (var fsoCount = 0; fsoCount < level; fsoCount++) { folderCount++; - var fsoName = System.IO.Path.GetFileNameWithoutExtension(RandomFileName) + "-" + fsoCount; - + var fsoName = RandomString + "-" + fsoCount; + // Always create folder. - var di = CreateDirectory(System.IO.Path.Combine(dirInfo.FullName, string.Format(CultureInfo.InvariantCulture, "{0}_directory", fsoName)), readOnly, hidden); + var di = CreateDirectory(System.IO.Path.Combine(dirInfo.FullName, string.Format(CultureInfo.InvariantCulture, "Directory_{0}_directory", fsoName)), readOnly, hidden); // Create file, every other iteration. - CreateFile(System.IO.Path.Combine(fsoCount % 2 == 0 ? di.FullName : dirInfo.FullName, string.Format(CultureInfo.InvariantCulture, "{0}_file.txt", fsoName)), readOnly, hidden); + CreateFile(System.IO.Path.Combine(fsoCount % 2 == 0 ? di.FullName : dirInfo.FullName, string.Format(CultureInfo.InvariantCulture, "File_{0}_file.txt", fsoName)), readOnly, hidden); } if (recurse) { foreach (var folder in System.IO.Directory.EnumerateDirectories(dirInfo.FullName)) - CreateRandomDirectoryStructure(folder, max, false, readOnly, hidden); + CreateTreeCore(folder, level, false, readOnly, hidden); } - Assert.AreEqual(max, folderCount, "The number of folders does not equal the max folder-level, but is expected to."); + Assert.AreEqual(level, folderCount, "The number of folders does not equal the level folder-level, but is expected to."); return dirInfo; } + + /// Enables or disables deny access for the current User. + public void SetDirectoryDenyPermission(bool enable, string folderFullPath) + { + // ╔═════════════╦═════════════╦═══════════════════════════════╦════════════════════════╦══════════════════╦═══════════════════════╦═════════════╦═════════════╗ + // ║ ║ 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 ║ + // ╚═════════════╩═════════════╩═══════════════════════════════╩════════════════════════╩══════════════════╩═══════════════════════╩═════════════╩═════════════╝ + + var user = (Environment.UserDomainName + @"\" + Environment.UserName).TrimStart('\\'); + + var rule = new FileSystemAccessRule(user, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Deny); + + DirectorySecurity dirSecurity; + + var dirInfo = CreateDirectory(folderFullPath); + + + // Set DENY for current User. + if (enable) + { + dirSecurity = dirInfo.GetAccessControl(); + dirSecurity.AddAccessRule(rule); + dirInfo.SetAccessControl(dirSecurity); + } + + // Remove DENY for current User. + else + { + dirSecurity = dirInfo.GetAccessControl(); + dirSecurity.RemoveAccessRule(rule); + dirInfo.SetAccessControl(dirSecurity); + } + } + + + public override string ToString() + { + return Directory.FullName; + } + #endregion // Methods + #region Private Members + + /// Returns a instance to an existing directory, possibly with hidden and/or read-only attributes set. + private System.IO.DirectoryInfo CreateDirectory(string folderFullPath, bool readOnly = false, bool hidden = false) + { + var dirInfo = System.IO.Directory.CreateDirectory(!Alphaleonis.Utils.IsNullOrWhiteSpace(folderFullPath) ? folderFullPath : RandomDirectoryFullPath); + + SetAttributes(dirInfo, readOnly, hidden); + + return dirInfo; + } + + + /// Returns a instance to an existing file, possibly with hidden and/or read-only attributes set. + private System.IO.FileInfo CreateFile(string fileFullPath, bool readOnly = false, bool hidden = false) + { + var fileInfo = new System.IO.FileInfo(!Alphaleonis.Utils.IsNullOrWhiteSpace(fileFullPath) ? fileFullPath : RandomTxtFileFullPath); + + // File size is min 0 bytes, level 1 MB. + using (var fs = fileInfo.Create()) + fs.SetLength(new Random(DateTime.UtcNow.Millisecond).Next(0, 1048576)); + + SetAttributes(fileInfo, readOnly, hidden); + + return fileInfo; + } + + + private static void SetAttributes(System.IO.FileSystemInfo fsi, bool readOnly = false, bool hidden = false) + { + if (readOnly && new Random(DateTime.UtcNow.Millisecond).Next(0, 1000) % 2 == 0) + fsi.Attributes |= System.IO.FileAttributes.ReadOnly; + + if (hidden && new Random(DateTime.UtcNow.Millisecond).Next(0, 1000) % 2 == 0) + fsi.Attributes |= System.IO.FileAttributes.Hidden; + } + + #endregion Private Members + + #region Disposable Members ~TemporaryDirectory() diff --git a/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs b/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs index 582ba60cf..e0406987b 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs @@ -20,17 +20,13 @@ */ using System; +using System.Globalization; namespace AlphaFS.UnitTest { /// Containts static variables, used by unit tests. public static partial class UnitTestConstants { - #region Fields - - public const string Local = @"LOCAL"; - public const string Network = @"NETWORK"; - #if NET35 public const string EMspace = "\u3000"; #endif @@ -50,6 +46,105 @@ public static partial class UnitTestConstants public const string TextGoodbyeWorld = "Góödbyé Wôrld!"; public const string TextUnicode = "ÛņïÇòdè; ǖŤƑ"; - #endregion // Fields + + /// The Computer name. + public static readonly string LocalHost = Environment.MachineName; + + + /// The Computer system drive. For example "C:". + public static readonly string SysDrive = Environment.GetEnvironmentVariable("SystemDrive"); + + + 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) " + TextHelloWorld + " " + TextUnicode + }; + + + 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.GlobalRootPrefix + @"device\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 + LocalHost + @"\Share", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\f", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fi", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fil", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.e", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ex", + Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ext", + + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\f", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fi", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fil", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.e", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ex", + Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ext" + }; } } From 571159267ecd95618959370f37a630f8630d5468 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 30 May 2018 17:56:58 +0200 Subject: [PATCH 076/133] Improved unit tests. --- .../AlphaFS_File.GetCompressedSize.cs | 5 +- ...ume.DefineDosDevice_RegularDriveMapping.cs | 2 +- .../AlphaFS_Device.EnumerateDevices.cs | 2 +- .../AlphaFS_File.GetHash.cs | 21 +- ...eFiles_UsingDirectoryEnumerationFilters.cs | 2 +- ...eFileSystemEntryInfos_TypeDirectoryInfo.cs | 2 +- ...merateFileSystemEntryInfos_TypeFileInfo.cs | 2 +- ...ystemEntryInfos_TypeFileSystemEntryInfo.cs | 2 +- ...numerateFileSystemEntryInfos_TypeString.cs | 2 +- ...lphaFS_Directory.GetFileSystemEntryInfo.cs | 2 +- ...ption_FileExistsWithSameNameAsDirectory.cs | 2 +- .../AlphaFS_File.GetFileSystemEntryInfo.cs | 2 +- ...ption_DirectoryExistsWithSameNameAsFile.cs | 2 +- ...S_Host.ConnectDrive_And_DisconnectDrive.cs | 28 +- ...st.ConnectTo_Ipc_And_DisconnectFrom_Ipc.cs | 18 +- ...onnectTo_Share_And_DisconnectFrom_Share.cs | 25 +- .../AlphaFS_Host.DriveConnection.cs | 20 +- .../AlphaFS_Host.EnumerateDrives.cs | 2 +- .../AlphaFS_Host.EnumerateOpenConnections.cs | 2 +- .../AlphaFS_Host.EnumerateOpenResources.cs | 2 +- .../AlphaFS_Host.EnumerateSessions.cs | 2 +- .../AlphaFS_Host.EnumerateShares.cs | 2 +- .../AlphaFS_Host.GetHostShareFromPath.cs | 4 +- .../AlphaFS_Host.GetUncName.cs | 4 +- ...e.CreateHardlink_And_EnumerateHardlinks.cs | 3 +- .../AlphaFS_Shell32.GetFileAssociation.cs | 2 +- .../AlphaFS_Shell32.GetFileIcon.cs | 4 +- .../AlphaFS_Shell32.GetVerbCommand.cs | 4 +- .../AlphaFS_Shell32Test.PathCreateFromUrl.cs | 20 +- ...haFS_Shell32Test.PathCreateFromUrlAlloc.cs | 20 +- .../AlphaFS_Shell32Test.PathFileExists.cs | 29 +- .../AlphaFS_Shell32Test.UrlIs.cs | 23 +- .../Directory.CreateDirectory_And_Delete.cs | 2 +- .../Directory.GetCurrentDirectory.cs | 4 +- .../Directory.SetCurrentDirectory.cs | 2 +- ...ectory.SetCurrentDirectory_WithLongPath.cs | 2 +- ...ctory.Exists_WithLeadingOrTrailingSpace.cs | 2 +- .../Directory.GetFileSystemEntries.cs | 2 +- .../Directory.Move_FileToMappedDriveLetter.cs | 2 +- .../AlphaFS_Directory.GetChangeTime.cs | 2 +- ...zeInstance_AnalyzeDirectoryInfoSecurity.cs | 70 +++-- ...haFS_File.EnumerateAlternateDataStreams.cs | 5 +- ..._File.Exists_WithLeadingOrTrailingSpace.cs | 2 +- .../File Class/File.Open/File.OpenRead.cs | 3 +- .../File Class/File.Open/File.OpenText.cs | 3 +- .../File Class/File.Open/File.OpenWrite.cs | 9 +- .../File Class/File.Open/File_Open_Append.cs | 7 +- .../File Class/File.Open/File_Open_Create.cs | 5 +- .../File Class/File.Replace/File.Replace.cs | 24 +- .../File.Replace/File.Replace_NoBackup.cs | 21 +- .../File Class/File_Create/File.Create.cs | 7 +- .../File Class/File_Create/File.CreateText.cs | 8 +- .../AlphaFS_File.GetChangeTime.cs | 2 +- ...Path.GetRelativePathResolveRelativePath.cs | 278 +++++++++--------- ...3PathAndGetLongFrom83ShortPath_FromFile.cs | 36 +-- .../Path Class/AlphaFS_Path.LocalToUnc.cs | 14 +- .../AlphaFS_Path.GetMappedConnectionName.cs | 24 +- .../AlphaFS_Path.GetMappedUncName.cs | 24 +- ...lphaFS_Path.GetDirectoryNameWithoutRoot.cs | 23 +- .../AlphaFS_Path.GetSuffixedDirectoryName.cs | 17 +- ...ath.GetSuffixedDirectoryNameWithoutRoot.cs | 27 +- ...Exception_PathContainsInvalidCharacters.cs | 17 +- ...owArgumentException_PathStartsWithColon.cs | 2 +- ...NotSupportedException_PathContainsColon.cs | 15 +- .../UnitTest Utility/TemporaryDirectory.cs | 16 +- .../UnitTest Utility/UnitTestConstants.cs | 92 +++--- AlphaFS/Network/Host Class/Host.cs | 1 - 67 files changed, 526 insertions(+), 506 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File.GetCompressedSize.cs b/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File.GetCompressedSize.cs index b91c07f10..5793b0b30 100644 --- a/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File.GetCompressedSize.cs +++ b/AlphaFS.UnitTest/AlphaFS Compression/AlphaFS_File.GetCompressedSize.cs @@ -47,7 +47,8 @@ private void AlphaFS_File_GetCompressedSize(bool isNetwork) long streamLength; - var thousand = 100 * UnitTestConstants.TenNumbers.Length; + var tenNumbers = "0123456789"; + var thousand = 100 * tenNumbers.Length; var compressedSize = 4096; @@ -58,7 +59,7 @@ private void AlphaFS_File_GetCompressedSize(bool isNetwork) // 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(UnitTestConstants.TenNumbers), 0, UnitTestConstants.TenNumbers.Length); + fs.Write(UnitTestConstants.StringToByteArray(tenNumbers), 0, tenNumbers.Length); streamLength = fs.Length; } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs index e3d851e9d..e50cc12c2 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs @@ -43,7 +43,7 @@ private void AlphaFS_Volume_DefineDosDevice_RegularDriveMapping(bool isNetwork) using (var tempRoot = new TemporaryDirectory(isNetwork)) { var folder = tempRoot.CreateDirectory(); - var drive = string.Format(CultureInfo.InvariantCulture, @"{0}:\", Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter()); + var drive = Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter() + ":"; Assert.IsFalse(System.IO.Directory.Exists(drive), "The drive exists, but it is expected not to."); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs index a2021ad00..c09d5a4b3 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs @@ -45,7 +45,7 @@ private void AlphaFS_Device_EnumerateDevices() { UnitTestConstants.PrintUnitTestHeader(false); - var tempPath = UnitTestConstants.LocalHost; + var tempPath = Environment.MachineName; var classCnt = 0; foreach (var deviceClass in EnumMemberToList()) diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File.GetHash.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File.GetHash.cs index d4dd33384..de7da0206 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File.GetHash.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File.GetHash.cs @@ -21,6 +21,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; +using System.Globalization; namespace AlphaFS.UnitTest { @@ -42,57 +43,57 @@ private void AlphaFS_File_GetHash(bool isNetwork) using (var tempRoot = new TemporaryDirectory(isNetwork)) { var file = System.IO.Path.Combine(tempRoot.Directory.FullName, "HashFile.txt"); - System.IO.File.WriteAllText(file, UnitTestConstants.TextHelloWorld); - + System.IO.File.WriteAllText(file, new Guid().ToString()); + Console.WriteLine("Input File Path: [{0}]\n", file); var type = Alphaleonis.Win32.Security.HashType.CRC32; var hash = Alphaleonis.Win32.Filesystem.File.GetHash(file, type); Console.WriteLine("\t{0,12} = {1}", type, hash); - Assert.AreEqual("1BF6339C", hash); + Assert.AreEqual("8151DA89", hash); type = Alphaleonis.Win32.Security.HashType.CRC64ISO3309; hash = Alphaleonis.Win32.Filesystem.File.GetHash(file, type); Console.WriteLine("\t{0,12} = {1}", type, hash); - Assert.AreEqual("AD3DE8A8C701F74E", hash); + Assert.AreEqual("130BC432FA070BC4", hash); type = Alphaleonis.Win32.Security.HashType.MD5; hash = Alphaleonis.Win32.Filesystem.File.GetHash(file, type); Console.WriteLine("\t{0,12} = {1}", type, hash); - Assert.AreEqual("4CF01535A68A0F4AAFD0631F3A000C52", hash); + Assert.AreEqual("9F89C84A559F573636A47FF8DAED0D33", hash); type = Alphaleonis.Win32.Security.HashType.RIPEMD160; hash = Alphaleonis.Win32.Filesystem.File.GetHash(file, type); Console.WriteLine("\t{0,12} = {1}", type, hash); - Assert.AreEqual("C2183FB7668FE4A2382A8E6D00501B3C114A6E9A", hash); + Assert.AreEqual("E38FD4F808D316C9671F0808AE1457330AD769AA", hash); type = Alphaleonis.Win32.Security.HashType.SHA1; hash = Alphaleonis.Win32.Filesystem.File.GetHash(file, type); Console.WriteLine("\t{0,12} = {1}", type, hash); - Assert.AreEqual("53F20D3D826642B232F5E514CB2AADFC359417E8", hash); + Assert.AreEqual("B602D594AFD2B0B327E07A06F36CA6A7E42546D0", hash); type = Alphaleonis.Win32.Security.HashType.SHA256; hash = Alphaleonis.Win32.Filesystem.File.GetHash(file, type); Console.WriteLine("\t{0,12} = {1}", type, hash); - Assert.AreEqual("07E7173232F22A1B746FE15C98BCB294A668F8300F645174BF0B83E2D8EADDCB", hash); + Assert.AreEqual("12B9377CBE7E5C94E8A70D9D23929523D14AFA954793130F8A3959C7B849ACA8", hash); type = Alphaleonis.Win32.Security.HashType.SHA384; hash = Alphaleonis.Win32.Filesystem.File.GetHash(file, type); Console.WriteLine("\t{0,12} = {1}", type, hash); - Assert.AreEqual("BF5FFD4053C364A8DB68608D79DB0A016E990B1BE8F1D91FCFC820AC89456F4AFAF8307DEEA4A7F663CE03D0EC21AD58", hash); + Assert.AreEqual("70255C353A82BC55634A251D657F1813A74B3ECA31DDE11DF99017F1DE7504820FB054D1853B6E5F53251AAEB66D0469", hash); type = Alphaleonis.Win32.Security.HashType.SHA512; hash = Alphaleonis.Win32.Filesystem.File.GetHash(file, type); Console.WriteLine("\t{0,12} = {1}", type, hash); - Assert.AreEqual("FFC32D18263B784A6E661E852DC5FF3A4C75425A42974CF067DDC01A17FFD34CF6E9717623A7D9C6EA19B04DBF5FDADECDE06122DAB0C26CFC83B1EA61C7B382", hash); + Assert.AreEqual("A13DC074B31564A6A3CF4A605BFF19FADE6C19992A4123A7022D5A07C2E2D2D5E059FF0BA25AE0750D709FDB0AC757A1C615199A1C1422902D33C41E45B9F9D5", hash); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs index 58d541281..aaacf3aba 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_EnumerateFiles_UsingDirectoryEnumerationFilters.cs @@ -46,7 +46,7 @@ private void AlphaFS_Directory_EnumerateFileSystemEntryInfos_EnumerateFiles_Usin { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var inputPath = UnitTestConstants.SysRoot; + var inputPath = Environment.SystemDirectory; if (isNetwork) inputPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(inputPath); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeDirectoryInfo.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeDirectoryInfo.cs index e09c6a518..da1149d5d 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeDirectoryInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeDirectoryInfo.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_EnumerateFileSystemEntryInfos_TypeDirectoryInfo(b { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = UnitTestConstants.SysRoot; + var tempPath = Environment.SystemDirectory; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeFileInfo.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeFileInfo.cs index f66b8d485..c370e5e45 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeFileInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeFileInfo.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_EnumerateFileSystemEntryInfos_TypeFileInfo(bool i { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = UnitTestConstants.SysRoot; + var tempPath = Environment.SystemDirectory; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeFileSystemEntryInfo.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeFileSystemEntryInfo.cs index d20f5cb15..86debcb1d 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeFileSystemEntryInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeFileSystemEntryInfo.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_EnumerateFileSystemEntryInfos_TypeFileSystemEntry { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = UnitTestConstants.SysRoot; + var tempPath = Environment.SystemDirectory; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeString.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeString.cs index ad851410a..73f5e8bcf 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeString.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.EnumerateFileSystemEntryInfos_TypeString.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_EnumerateFileSystemEntryInfos_TypeString(bool isN { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = UnitTestConstants.SysRoot; + var tempPath = Environment.SystemDirectory; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo.cs index a6506801d..b5bbebd75 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_GetFileSystemEntryInfo(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = UnitTestConstants.SysRoot; + var tempPath = Environment.SystemDirectory; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs index 6126139ff..ceba9fa96 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs @@ -39,7 +39,7 @@ public void AlphaFS_Directory_GetFileSystemEntryInfo_ThrowDirectoryNotFoundExcep private void AlphaFS_Directory_GetFileSystemEntryInfo_ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory(bool isNetwork) { - var path = UnitTestConstants.NotepadExe; + var path = System.IO.Path.Combine(Environment.SystemDirectory, "notepad.exe"); if (!System.IO.File.Exists(path)) UnitTestAssert.InconclusiveBecauseFileNotFound(path); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo.cs index 6a0a24e6c..7b8edcedc 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo.cs @@ -39,7 +39,7 @@ public void AlphaFS_File_GetFileSystemEntryInfo_LocalAndNetwork_Success() private void AlphaFS_File_GetFileSystemEntryInfo(bool isNetwork) { - var path = UnitTestConstants.NotepadExe; + var path = System.IO.Path.Combine(Environment.SystemDirectory, "notepad.exe"); if (!System.IO.File.Exists(path)) UnitTestAssert.InconclusiveBecauseFileNotFound(path); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo_ThrowFileNotFoundException_DirectoryExistsWithSameNameAsFile.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo_ThrowFileNotFoundException_DirectoryExistsWithSameNameAsFile.cs index 338d10712..6382471d5 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo_ThrowFileNotFoundException_DirectoryExistsWithSameNameAsFile.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo_ThrowFileNotFoundException_DirectoryExistsWithSameNameAsFile.cs @@ -41,7 +41,7 @@ private void AlphaFS_File_GetFileSystemEntryInfo_ThrowFileNotFoundException_Dire { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = UnitTestConstants.SysRoot; + var tempPath = Environment.SystemDirectory; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectDrive_And_DisconnectDrive.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectDrive_And_DisconnectDrive.cs index 6d85f5f58..efff6fdea 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectDrive_And_DisconnectDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectDrive_And_DisconnectDrive.cs @@ -21,7 +21,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Globalization; namespace AlphaFS.UnitTest { @@ -33,23 +32,34 @@ public partial class AlphaFS_HostTest [TestMethod] public void AlphaFS_Host_ConnectDrive_And_DisconnectDrive_Network_Success() { - UnitTestConstants.PrintUnitTestHeader(true); + using (var tempRoot = new TemporaryDirectory(true)) + { + // Randomly test the share where the local folder possibly has the read-only and/or hidden attributes set. - var drive = string.Format(CultureInfo.InvariantCulture, "{0}:", Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter()); + var folder = tempRoot.CreateDirectoryRandomizedAttributes(); - var share = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.TempPath); + var drive = Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter() + ":"; - // An Exception is thrown for any error, so no Assert needed. + try + { + Console.WriteLine("Connect drive [{0}] to share [{1}]", drive, folder.FullName); - Console.WriteLine("Connect drive [{0}] to [{1}]", drive, share); + Alphaleonis.Win32.Network.Host.ConnectDrive(drive, folder.FullName); - Alphaleonis.Win32.Network.Host.ConnectDrive(drive, share); + UnitTestConstants.Dump(new System.IO.DriveInfo(drive), -18); + Assert.IsTrue(System.IO.Directory.Exists(drive), "The drive does not exists, but is expected to."); + } + finally + { + Console.WriteLine("\nDisconnect drive from share."); - Console.WriteLine("\nDisconnect drive."); + Alphaleonis.Win32.Network.Host.DisconnectDrive(drive); - Alphaleonis.Win32.Network.Host.DisconnectDrive(drive); + Assert.IsFalse(System.IO.Directory.Exists(drive), "The drive exists, but is expected not to."); + } + } } } } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectTo_Ipc_And_DisconnectFrom_Ipc.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectTo_Ipc_And_DisconnectFrom_Ipc.cs index b9d620af5..37ee19daf 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectTo_Ipc_And_DisconnectFrom_Ipc.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectTo_Ipc_And_DisconnectFrom_Ipc.cs @@ -34,19 +34,23 @@ public void AlphaFS_Host_ConnectTo_Ipc_And_DisconnectFrom_Ipc_Network_Success() { UnitTestConstants.PrintUnitTestHeader(true); - var share = UnitTestConstants.LocalHost; + var share = Environment.MachineName; // An Exception is thrown for any error, so no Assert needed. - Console.WriteLine("Connect to Computer: [{0}]", share); + try + { + Console.WriteLine("Connect to Computer: [{0}]", share); - Alphaleonis.Win32.Network.Host.ConnectTo(share); + Alphaleonis.Win32.Network.Host.ConnectTo(share); + } + finally + { + Console.WriteLine("\nDisconnect from Computer."); - - Console.WriteLine("\nDisconnect Computer."); - - Alphaleonis.Win32.Network.Host.DisconnectFrom(share); + Alphaleonis.Win32.Network.Host.DisconnectFrom(share); + } } } } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectTo_Share_And_DisconnectFrom_Share.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectTo_Share_And_DisconnectFrom_Share.cs index aeea872f4..9f19f474e 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectTo_Share_And_DisconnectFrom_Share.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.ConnectTo_Share_And_DisconnectFrom_Share.cs @@ -32,21 +32,28 @@ public partial class AlphaFS_HostTest [TestMethod] public void AlphaFS_Host_ConnectTo_Share_And_DisconnectFrom_Share_Network_Success() { - UnitTestConstants.PrintUnitTestHeader(true); + using (var tempRoot = new TemporaryDirectory(true)) + { + // Randomly test the share where the local folder possibly has the read-only and/or hidden attributes set. - var share = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.TempPath); + var folder = tempRoot.CreateDirectoryRandomizedAttributes(); - // An Exception is thrown for any error, so no Assert needed. + // An Exception is thrown for any error, so no Assert needed. - Console.WriteLine("Connect to share: [{0}]", share); + try + { + Console.WriteLine("Connect to share: [{0}]", folder.FullName); - Alphaleonis.Win32.Network.Host.ConnectTo(share); + Alphaleonis.Win32.Network.Host.ConnectTo(folder.FullName); + } + finally + { + Console.WriteLine("\nDisconnect from share."); - - Console.WriteLine("\nDisconnect from share."); - - Alphaleonis.Win32.Network.Host.DisconnectFrom(share); + Alphaleonis.Win32.Network.Host.DisconnectFrom(folder.FullName); + } + } } } } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.DriveConnection.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.DriveConnection.cs index f4319f917..6daa18f29 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.DriveConnection.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.DriveConnection.cs @@ -32,19 +32,23 @@ public partial class AlphaFS_HostTest [TestMethod] public void AlphaFS_Host_DriveConnection_Network_Success() { - UnitTestConstants.PrintUnitTestHeader(true); + using (var tempRoot = new TemporaryDirectory(true)) + { + // Randomly test the share where the local folder possibly has the read-only and/or hidden attributes set. - var share = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.TempPath); + var folder = tempRoot.CreateDirectoryRandomizedAttributes(); - using (var connection = new Alphaleonis.Win32.Network.DriveConnection(share)) - { - Console.WriteLine("Mapped drive [{0}] to [{1}]", connection.LocalName, share); - UnitTestConstants.Dump(connection, -9); + using (var connection = new Alphaleonis.Win32.Network.DriveConnection(folder.FullName)) + { + Console.WriteLine("Mapped drive [{0}] to share [{1}]", connection.LocalName, folder.FullName); + + UnitTestConstants.Dump(connection, -9); - Assert.AreEqual(share, connection.Share); + Assert.AreEqual(folder.FullName, connection.Share); - Assert.IsTrue(System.IO.Directory.Exists(share)); + Assert.IsTrue(System.IO.Directory.Exists(folder.FullName)); + } } } } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDrives.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDrives.cs index 11a91175a..e648381d6 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDrives.cs @@ -37,7 +37,7 @@ public void AlphaFS_Host_EnumerateDrives_Network_Success() UnitTestConstants.PrintUnitTestHeader(true); - var host = UnitTestConstants.LocalHost; + var host = Environment.MachineName; var drives = Alphaleonis.Win32.Network.Host.EnumerateDrives(host, true).ToArray(); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenConnections.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenConnections.cs index bd0432b53..e9a8ac340 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenConnections.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenConnections.cs @@ -32,7 +32,7 @@ public partial class EnumerationTest [TestMethod] public void AlphaFS_Host_EnumerateOpenConnections_Local_Success() { - var host = UnitTestConstants.LocalHost; + var host = Environment.MachineName; var share = UnitTestConstants.SysDrive[0] + Alphaleonis.Win32.Filesystem.Path.NetworkDriveSeparator; // Create an active connection to the "remote" host. diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenResources.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenResources.cs index 6ceded9b0..de4b0b5dd 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenResources.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenResources.cs @@ -35,7 +35,7 @@ public void AlphaFS_Host_EnumerateOpenResources_Local_Success() UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); - var host = UnitTestConstants.LocalHost; + var host = Environment.MachineName; Console.WriteLine("Connected to Host: [{0}]", host); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs index 90e9e9b46..ff0fcb91c 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs @@ -34,7 +34,7 @@ public void AlphaFS_Host_EnumerateSessions_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); - var host = UnitTestConstants.LocalHost; + var host = Environment.MachineName; Console.WriteLine("Input Host: [{0}]", host); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateShares.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateShares.cs index aaf0cd54c..eb88ed7bc 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateShares.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateShares.cs @@ -34,7 +34,7 @@ public void AlphaFS_Host_EnumerateShares_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); - var host = UnitTestConstants.LocalHost; + var host = Environment.MachineName; Console.WriteLine("Input Host: [{0}]", host); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetHostShareFromPath.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetHostShareFromPath.cs index 2cefde9ad..7a0b574a2 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetHostShareFromPath.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetHostShareFromPath.cs @@ -63,7 +63,7 @@ public void AlphaFS_Host_GetHostShareFromPath_Network_Success() // Local Path. - uncPath = Alphaleonis.Win32.Filesystem.Path.GetLongPath(UnitTestConstants.SysRoot + folderWithspaces); + 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); @@ -115,7 +115,7 @@ public void AlphaFS_Host_GetHostShareFromPath_Network_Success() // Network Path as long path. - uncPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.SysRoot + folderWithspaces, Alphaleonis.Win32.Filesystem.GetFullPathOptions.AsLongPath); + 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]); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetUncName.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetUncName.cs index ff7e6044b..3c6e370b0 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetUncName.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.GetUncName.cs @@ -35,9 +35,9 @@ public void AlphaFS_Host_GetUncName_Network_Success() UnitTestConstants.PrintUnitTestHeader(true); var hostUncName = Alphaleonis.Win32.Network.Host.GetUncName(); - Console.WriteLine("Host.GetUncName(): [{0}]", hostUncName); - + Console.WriteLine("Host UNC Name: [{0}]", hostUncName); + Assert.IsTrue(hostUncName.StartsWith(Alphaleonis.Win32.Filesystem.Path.UncPrefix)); Assert.AreEqual(Alphaleonis.Win32.Filesystem.Path.UncPrefix + Environment.MachineName, hostUncName); diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateHardlink_And_EnumerateHardlinks.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateHardlink_And_EnumerateHardlinks.cs index f213cb12e..73be4c157 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateHardlink_And_EnumerateHardlinks.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateHardlink_And_EnumerateHardlinks.cs @@ -21,6 +21,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -48,7 +49,7 @@ private void AlphaFS_File_CreateHardlink_And_EnumerateHardlinks() Console.WriteLine("Input File Path: [{0}]\n", file); // Create original file with text content. - System.IO.File.WriteAllText(file, UnitTestConstants.TextHelloWorld); + System.IO.File.WriteAllText(file, DateTime.Now.ToString(CultureInfo.CurrentCulture)); // Create a random number of hardlinks to the original file. diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetFileAssociation.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetFileAssociation.cs index 144bee27a..df2c9ac7f 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetFileAssociation.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetFileAssociation.cs @@ -38,7 +38,7 @@ private void AlphaFS_Shell32_GetFileAssociation(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var inputPath = UnitTestConstants.SysRoot; + var inputPath = Environment.SystemDirectory; if (isNetwork) inputPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(inputPath); diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetFileIcon.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetFileIcon.cs index 25a99c8f3..143d90259 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetFileIcon.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetFileIcon.cs @@ -43,9 +43,9 @@ private void AlphaFS_Shell32_GetFileIcon(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var file = UnitTestConstants.NotepadExe; + var file = System.IO.Path.Combine(Environment.SystemDirectory, "notepad.exe"); if (isNetwork) - file = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.NotepadExe); + file = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(System.IO.Path.Combine(Environment.SystemDirectory, "notepad.exe")); Console.WriteLine("Input File Path: {0}", file); diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetVerbCommand.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetVerbCommand.cs index 20e2eaf83..f084cf33a 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetVerbCommand.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32.GetVerbCommand.cs @@ -57,7 +57,7 @@ private void AlphaFS_Shell32Info_GetVerbCommand(bool isNetwork) Console.WriteLine("\tMethod: Shell32Info.GetVerbCommand(\"{0}\") == [{1}]", cmd, result); - Assert.IsTrue(result.StartsWith(UnitTestConstants.NotepadExe, StringComparison.OrdinalIgnoreCase)); + Assert.IsTrue(result.StartsWith(System.IO.Path.Combine(Environment.SystemDirectory, "notepad.exe"), StringComparison.OrdinalIgnoreCase)); cmd = "print"; @@ -65,7 +65,7 @@ private void AlphaFS_Shell32Info_GetVerbCommand(bool isNetwork) Console.WriteLine("\tMethod: Shell32Info.GetVerbCommand(\"{0}\") == [{1}]\n", cmd, result); - Assert.IsTrue(result.StartsWith(UnitTestConstants.NotepadExe, StringComparison.OrdinalIgnoreCase)); + Assert.IsTrue(result.StartsWith(System.IO.Path.Combine(Environment.SystemDirectory, "notepad.exe"), StringComparison.OrdinalIgnoreCase)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathCreateFromUrl.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathCreateFromUrl.cs index 051c02137..ebfc430fb 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathCreateFromUrl.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathCreateFromUrl.cs @@ -19,8 +19,8 @@ * THE SOFTWARE. */ -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest { @@ -29,23 +29,15 @@ public partial class AlphaFS_Shell32Test [TestMethod] public void AlphaFS_Shell32_PathCreateFromUrl() { - var urlPath = Alphaleonis.Win32.Filesystem.Shell32.UrlCreateFromPath(UnitTestConstants.AppData); - var filePath = Alphaleonis.Win32.Filesystem.Shell32.PathCreateFromUrl(urlPath); + var folder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - Console.WriteLine("\n\tDirectory : [{0}]", UnitTestConstants.AppData); - Console.WriteLine("\n\tShell32.UrlCreateFromPath(): [{0}]", urlPath); - Console.WriteLine("\n\tShell32.PathCreateFromUrl() == [{0}]\n", filePath); - - var startsWith = urlPath.StartsWith("file:///"); - var equalsAppData = filePath.Equals(UnitTestConstants.AppData); - - Console.WriteLine("\n\turlPath.StartsWith(\"file:///\") == [{0}]: {1}", UnitTestConstants.TextTrue, startsWith); - Console.WriteLine("\n\tfilePath.Equals(AppData) == [{0}]: {1}\n", UnitTestConstants.TextTrue, equalsAppData); + var urlPath = Alphaleonis.Win32.Filesystem.Shell32.UrlCreateFromPath(folder); + var filePath = Alphaleonis.Win32.Filesystem.Shell32.PathCreateFromUrl(urlPath); - Assert.IsTrue(startsWith); + Assert.IsTrue(urlPath.StartsWith("file:///")); - Assert.IsTrue(equalsAppData); + Assert.IsTrue(filePath.Equals(folder)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathCreateFromUrlAlloc.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathCreateFromUrlAlloc.cs index a8e4cdf66..6d60ad432 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathCreateFromUrlAlloc.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathCreateFromUrlAlloc.cs @@ -19,8 +19,8 @@ * THE SOFTWARE. */ -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest { @@ -29,23 +29,15 @@ public partial class AlphaFS_Shell32Test [TestMethod] public void AlphaFS_Shell32_PathCreateFromUrlAlloc() { - var urlPath = Alphaleonis.Win32.Filesystem.Shell32.UrlCreateFromPath(UnitTestConstants.AppData); - var filePath = Alphaleonis.Win32.Filesystem.Shell32.PathCreateFromUrlAlloc(urlPath); + var folder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - Console.WriteLine("\n\tDirectory : [{0}]", UnitTestConstants.AppData); - Console.WriteLine("\n\tShell32.UrlCreateFromPath(): [{0}]", urlPath); - Console.WriteLine("\n\tShell32.PathCreateFromUrlAlloc() == [{0}]\n", filePath); - - var startsWith = urlPath.StartsWith("file:///"); - var equalsAppData = filePath.Equals(UnitTestConstants.AppData); - - Console.WriteLine("\n\turlPath.StartsWith(\"file:///\") == [{0}]: {1}", UnitTestConstants.TextTrue, startsWith); - Console.WriteLine("\n\tfilePath.Equals(AppData) == [{0}]: {1}\n", UnitTestConstants.TextTrue, equalsAppData); + var urlPath = Alphaleonis.Win32.Filesystem.Shell32.UrlCreateFromPath(folder); + var filePath = Alphaleonis.Win32.Filesystem.Shell32.PathCreateFromUrlAlloc(urlPath); - Assert.IsTrue(startsWith); + Assert.IsTrue(urlPath.StartsWith("file:///")); - Assert.IsTrue(equalsAppData); + Assert.IsTrue(filePath.Equals(folder)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathFileExists.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathFileExists.cs index bd9aa2849..e5072a9eb 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathFileExists.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.PathFileExists.cs @@ -29,39 +29,26 @@ public partial class AlphaFS_Shell32Test [TestMethod] public void AlphaFS_Shell32_PathFileExists() { - var path = UnitTestConstants.SysRoot; + 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(UnitTestConstants.SysRoot, "BlaBlaBla"), false); - var cnt = 0; - foreach (var file in System.IO.Directory.EnumerateFiles(UnitTestConstants.SysRoot)) - { - var fileExists = Alphaleonis.Win32.Filesystem.Shell32.PathFileExists(file); + Shell32_PathFileExists(System.IO.Path.Combine(Environment.SystemDirectory, "BlaBlaBla"), false); - Console.WriteLine("\t#{0:000}\tShell32.PathFileExists() == [{1}]: {2}\t\t[{3}]", ++cnt, UnitTestConstants.TextTrue, fileExists, file); + foreach (var file in System.IO.Directory.EnumerateFiles(path)) - Assert.IsTrue(fileExists); - } - - Console.WriteLine(); + Assert.IsTrue(Alphaleonis.Win32.Filesystem.Shell32.PathFileExists(file)); } - - - - private void Shell32_PathFileExists(string path, bool doesExist) + + private static void Shell32_PathFileExists(string path, bool doesExist) { - Console.WriteLine("\n\tPath: [{0}]\n", path); - var fileExists = Alphaleonis.Win32.Filesystem.Shell32.PathFileExists(path); - Console.WriteLine("\t\tShell32.PathFileExists() == [{0}]: {1}\t\t[{2}]", doesExist ? UnitTestConstants.TextTrue : UnitTestConstants.TextFalse, doesExist == fileExists, path); - Console.WriteLine("\t\tFile.Exists() == [{0}]: {1}\t\t[{2}]", doesExist ? UnitTestConstants.TextTrue : UnitTestConstants.TextFalse, doesExist == System.IO.File.Exists(path), path); - Console.WriteLine("\t\tDirectory.Exists() == [{0}]: {1}\t\t[{2}]", doesExist ? UnitTestConstants.TextTrue : UnitTestConstants.TextFalse, doesExist == System.IO.Directory.Exists(path), path); - if (doesExist) Assert.IsTrue(fileExists); diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.UrlIs.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.UrlIs.cs index 5a96736b7..9eafc0953 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.UrlIs.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Test.UrlIs.cs @@ -19,8 +19,8 @@ * THE SOFTWARE. */ -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest { @@ -29,26 +29,13 @@ public partial class AlphaFS_Shell32Test [TestMethod] public void AlphaFS_Shell32_UrlIs() { - var urlPath = Alphaleonis.Win32.Filesystem.Shell32.UrlCreateFromPath(UnitTestConstants.AppData); - var filePath = Alphaleonis.Win32.Filesystem.Shell32.PathCreateFromUrlAlloc(urlPath); + var urlPath = Alphaleonis.Win32.Filesystem.Shell32.UrlCreateFromPath(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); - var isFileUrl1 = Alphaleonis.Win32.Filesystem.Shell32.UrlIsFileUrl(urlPath); - var isFileUrl2 = Alphaleonis.Win32.Filesystem.Shell32.UrlIsFileUrl(filePath); - var isNoHistory = Alphaleonis.Win32.Filesystem.Shell32.UrlIs(filePath, Alphaleonis.Win32.Filesystem.Shell32.UrlType.IsNoHistory); - var isOpaque = Alphaleonis.Win32.Filesystem.Shell32.UrlIs(filePath, Alphaleonis.Win32.Filesystem.Shell32.UrlType.IsOpaque); - - Console.WriteLine("\n\tDirectory: [{0}]", UnitTestConstants.AppData); - Console.WriteLine("\n\tShell32.UrlCreateFromPath() == IsFileUrl == [{0}] : {1}\t\t[{2}]", UnitTestConstants.TextTrue, isFileUrl1, urlPath); - Console.WriteLine("\n\tShell32.PathCreateFromUrlAlloc() == IsFileUrl == [{0}]: {1}\t\t[{2}]", UnitTestConstants.TextFalse, isFileUrl2, filePath); - - Console.WriteLine("\n\tShell32.UrlIsFileUrl() == [{0}]: {1}\t\t[{2}]", UnitTestConstants.TextTrue, isFileUrl1, urlPath); - Console.WriteLine("\n\tShell32.UrlIsNoHistory() == [{0}]: {1}\t\t[{2}]", UnitTestConstants.TextTrue, isNoHistory, urlPath); - Console.WriteLine("\n\tShell32.UrlIsOpaque() == [{0}]: {1}\t\t[{2}]", UnitTestConstants.TextTrue, isOpaque, urlPath); - + var filePath = Alphaleonis.Win32.Filesystem.Shell32.PathCreateFromUrlAlloc(urlPath); - Assert.IsTrue(isFileUrl1); + Assert.IsTrue(Alphaleonis.Win32.Filesystem.Shell32.UrlIsFileUrl(urlPath)); - Assert.IsTrue(isFileUrl2 == false); + Assert.IsFalse(Alphaleonis.Win32.Filesystem.Shell32.UrlIsFileUrl(filePath)); } } } diff --git a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_And_Delete.cs b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_And_Delete.cs index 94f04cda5..763c7a916 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_And_Delete.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_And_Delete.cs @@ -51,7 +51,7 @@ private void Directory_CreateDirectory_And_Delete(bool isNetwork) #if NET35 // MSDN: .NET 4+ Trailing spaces are removed from the end of the path parameter before deleting the directory. - folder += UnitTestConstants.EMspace; + folder += "\u3000"; // EMspace #endif var root = folder; diff --git a/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.GetCurrentDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.GetCurrentDirectory.cs index 46a7b811e..8c8d5b9b5 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.GetCurrentDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.GetCurrentDirectory.cs @@ -42,7 +42,7 @@ private void Directory_GetCurrentDirectory(bool isNetwork) UnitTestConstants.PrintUnitTestHeader(isNetwork); // #1 - var tempPath = UnitTestConstants.AppData; + var tempPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); @@ -60,7 +60,7 @@ private void Directory_GetCurrentDirectory(bool isNetwork) // #2 - tempPath = UnitTestConstants.SysRoot; + tempPath = Environment.SystemDirectory; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.SetCurrentDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.SetCurrentDirectory.cs index e0db01f4d..c2c31c647 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.SetCurrentDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.SetCurrentDirectory.cs @@ -41,7 +41,7 @@ private void Directory_SetCurrentDirectory(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = UnitTestConstants.SysRoot; + var tempPath = Environment.SystemDirectory; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.SetCurrentDirectory_WithLongPath.cs b/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.SetCurrentDirectory_WithLongPath.cs index 1b0713af9..b2498509b 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.SetCurrentDirectory_WithLongPath.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.CurrentDirectory/Directory.SetCurrentDirectory_WithLongPath.cs @@ -41,7 +41,7 @@ private void Directory_SetCurrentDirectory_WithLongPath(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = UnitTestConstants.SysRoot; + var tempPath = Environment.SystemDirectory; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Exists/AlphaFS_Directory.Exists_WithLeadingOrTrailingSpace.cs b/AlphaFS.UnitTest/Directory Class/Directory.Exists/AlphaFS_Directory.Exists_WithLeadingOrTrailingSpace.cs index 2020c44d7..9506f2c45 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Exists/AlphaFS_Directory.Exists_WithLeadingOrTrailingSpace.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Exists/AlphaFS_Directory.Exists_WithLeadingOrTrailingSpace.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_Exists_WithLeadingOrTrailingSpace(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = UnitTestConstants.SysRoot32; + var tempPath = Environment.SystemDirectory; if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.GetFileSystemEntries.cs b/AlphaFS.UnitTest/Directory Class/Directory.GetFileSystemEntries.cs index 0cef127d4..812a8e3bc 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.GetFileSystemEntries.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.GetFileSystemEntries.cs @@ -41,7 +41,7 @@ private void Directory_GetFileSystemEntries(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var inputPath = UnitTestConstants.SysRoot; + var inputPath = Environment.SystemDirectory; if (isNetwork) inputPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(inputPath); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_FileToMappedDriveLetter.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_FileToMappedDriveLetter.cs index 2c1e1879e..df297f06d 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_FileToMappedDriveLetter.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_FileToMappedDriveLetter.cs @@ -43,7 +43,7 @@ public void Directory_Move_FileToMappedDriveLetter_LocalAndNetwork_Success() var srcFile = System.IO.Path.Combine(tempRoot.Directory.FullName, srcFileName); - var drive = string.Format(CultureInfo.InvariantCulture, @"{0}:\", Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter()); + var drive = Alphaleonis.Win32.Filesystem.DriveInfo.GetFreeDriveLetter() + @":\"; var share = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempRoot.Directory.Parent.FullName); var dstFile = System.IO.Path.Combine(drive, dstFileName); diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.GetChangeTime.cs b/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.GetChangeTime.cs index d7fc21651..404b57787 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.GetChangeTime.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Timestamps/AlphaFS_Directory.GetChangeTime.cs @@ -42,7 +42,7 @@ private void AlphaFS_Directory_GetChangeTime(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var folder = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.SysRoot32) : UnitTestConstants.SysRoot32; + var folder = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(Environment.SystemDirectory) : Environment.SystemDirectory; Console.WriteLine("Input Directory Path: [{0}]", folder); diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_AnalyzeDirectoryInfoSecurity.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_AnalyzeDirectoryInfoSecurity.cs index 6ef157aac..3324c446c 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_AnalyzeDirectoryInfoSecurity.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_AnalyzeDirectoryInfoSecurity.cs @@ -19,8 +19,8 @@ * THE SOFTWARE. */ -using Microsoft.VisualStudio.TestTools.UnitTesting; using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; namespace AlphaFS.UnitTest @@ -31,48 +31,76 @@ public partial class DirectoryInfoTest [TestMethod] - public void AnalyzeDirectoryInfoSecurity_Local_ShouldNotExist() + public void AnalyzeDirectoryInfoSecurity_ShouldNotExist_LocalAndNetwork() { - var testDir = GetTempDirectoryName(); + 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, -23); + + Assert.IsFalse(HasLocalAces(accessRules), "Local access rules are found, but it is not expected."); - SetSecuritySystem(testDir); + - var dirsec = new System.IO.DirectoryInfo(testDir + @"\inherited").GetAccessControl(); - var accessRules = dirsec.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); - Assert.IsFalse(HasLocalAces(accessRules), "local access rules found."); + folder = tempRoot.CreateDirectory(); + Console.WriteLine("\nInput Directory Path: [{0}]", folder.FullName); - testDir = GetTempDirectoryName(); - SetSecurityAlpha(testDir); + SetSecurityAlpha(folder.FullName); - dirsec = new Alphaleonis.Win32.Filesystem.DirectoryInfo(testDir + @"\inherited").GetAccessControl(); - accessRules = dirsec.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); + dirsec = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder.FullName + @"\inherited").GetAccessControl(); - Assert.IsFalse(HasLocalAces(accessRules), "local access rules found."); + accessRules = dirsec.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); + + UnitTestConstants.Dump(dirsec, -23); + + Assert.IsFalse(HasLocalAces(accessRules), "Local access rules are found, but it is not expected."); + } + + Console.WriteLine(); } - private void SetSecurityAlpha(string directory) + private static void SetSecurityAlpha(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")); + 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 void SetSecuritySystem(string directory) + private static void SetSecuritySystem(string directory) { if (System.IO.Directory.Exists(directory)) System.IO.Directory.Delete(directory, true); @@ -84,20 +112,16 @@ private void SetSecuritySystem(string directory) 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 string GetTempDirectoryName() - { - return System.IO.Path.Combine(UnitTestConstants.TempPath, Guid.NewGuid().ToString("N")); - } - - - private bool HasLocalAces(System.Security.AccessControl.AuthorizationRuleCollection rules) + private static bool HasLocalAces(System.Security.AccessControl.AuthorizationRuleCollection rules) { return null != rules.Cast().FirstOrDefault(a => !a.IsInherited); } diff --git a/AlphaFS.UnitTest/File Class/AlphaFS_File.EnumerateAlternateDataStreams.cs b/AlphaFS.UnitTest/File Class/AlphaFS_File.EnumerateAlternateDataStreams.cs index 3857e254d..64ac3bead 100644 --- a/AlphaFS.UnitTest/File Class/AlphaFS_File.EnumerateAlternateDataStreams.cs +++ b/AlphaFS.UnitTest/File Class/AlphaFS_File.EnumerateAlternateDataStreams.cs @@ -51,11 +51,12 @@ private void AlphaFS_EnumerateAlternateDataStreams(bool isNetwork) var myStream2 = "myStreamTWO-" + tempRoot.RandomString; var allStreams = new[] {myStream, myStream2}; var streamStringContent = "(1) Computer: [" + Environment.MachineName + "]" + "\tHello there, " + Environment.UserName; + var tenNumbers = "0123456789"; Console.WriteLine("\nA file is created and {0} streams are added.", allStreams.Length.ToString(CultureInfo.CurrentCulture)); // Create file and add 10 characters to it, file is created in ANSI format. - System.IO.File.WriteAllText(file, UnitTestConstants.TenNumbers); + System.IO.File.WriteAllText(file, tenNumbers); var fi = new Alphaleonis.Win32.Filesystem.FileInfo(file); @@ -69,7 +70,7 @@ private void AlphaFS_EnumerateAlternateDataStreams(bool isNetwork) var fileSize = Alphaleonis.Win32.Filesystem.File.GetSize(file); - Assert.AreEqual(UnitTestConstants.TenNumbers.Length, fileSize); + Assert.AreEqual(tenNumbers.Length, fileSize); // Create alternate data streams. diff --git a/AlphaFS.UnitTest/File Class/File.Exists/AlphaFS_File.Exists_WithLeadingOrTrailingSpace.cs b/AlphaFS.UnitTest/File Class/File.Exists/AlphaFS_File.Exists_WithLeadingOrTrailingSpace.cs index 22ccb8459..2e6819791 100644 --- a/AlphaFS.UnitTest/File Class/File.Exists/AlphaFS_File.Exists_WithLeadingOrTrailingSpace.cs +++ b/AlphaFS.UnitTest/File Class/File.Exists/AlphaFS_File.Exists_WithLeadingOrTrailingSpace.cs @@ -41,7 +41,7 @@ private void AlphaFS_File_Exists_WithLeadingOrTrailingSpace(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - var tempPath = UnitTestConstants.NotepadExe; + var tempPath = System.IO.Path.Combine(Environment.SystemDirectory, "notepad.exe"); if (isNetwork) tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); diff --git a/AlphaFS.UnitTest/File Class/File.Open/File.OpenRead.cs b/AlphaFS.UnitTest/File Class/File.Open/File.OpenRead.cs index eaee003b1..c1635e9bf 100644 --- a/AlphaFS.UnitTest/File Class/File.Open/File.OpenRead.cs +++ b/AlphaFS.UnitTest/File Class/File.Open/File.OpenRead.cs @@ -21,6 +21,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; +using System.Globalization; using System.Text; namespace AlphaFS.UnitTest @@ -47,7 +48,7 @@ private void File_OpenRead(bool isNetwork) Console.WriteLine("Input File Path: [{0}]\n", file); - System.IO.File.WriteAllText(file, UnitTestConstants.TextHelloWorld); + System.IO.File.WriteAllText(file, DateTime.Now.ToString(CultureInfo.CurrentCulture)); var sysIOStreamText = string.Empty; diff --git a/AlphaFS.UnitTest/File Class/File.Open/File.OpenText.cs b/AlphaFS.UnitTest/File Class/File.Open/File.OpenText.cs index cb3033dd1..e63cd9f1a 100644 --- a/AlphaFS.UnitTest/File Class/File.Open/File.OpenText.cs +++ b/AlphaFS.UnitTest/File Class/File.Open/File.OpenText.cs @@ -21,6 +21,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; +using System.Globalization; namespace AlphaFS.UnitTest { @@ -46,7 +47,7 @@ private void File_OpenText(bool isNetwork) Console.WriteLine("Input File Path: [{0}]\n", file); - System.IO.File.WriteAllText(file, UnitTestConstants.TextHelloWorld); + System.IO.File.WriteAllText(file, DateTime.Now.ToString(CultureInfo.CurrentCulture)); var sysIOStreamText = string.Empty; diff --git a/AlphaFS.UnitTest/File Class/File.Open/File.OpenWrite.cs b/AlphaFS.UnitTest/File Class/File.Open/File.OpenWrite.cs index 67209be9f..dee361f9b 100644 --- a/AlphaFS.UnitTest/File Class/File.Open/File.OpenWrite.cs +++ b/AlphaFS.UnitTest/File Class/File.Open/File.OpenWrite.cs @@ -21,6 +21,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; +using System.Globalization; using System.Text; namespace AlphaFS.UnitTest @@ -44,21 +45,23 @@ private void File_OpenWrite(bool isNetwork) { var file1 = tempRoot.RandomTxtFileFullPath; var file2 = tempRoot.RandomTxtFileFullPath; + var text = DateTime.Now.ToString(CultureInfo.CurrentCulture); Console.WriteLine("Input File1 Path: [{0}]", file1); Console.WriteLine("Input File2 Path: [{0}]", file2); - + Console.WriteLine("Text : [{0}]", text); + using (var stream = System.IO.File.OpenWrite(file1)) { - var info = new UTF8Encoding(true).GetBytes(UnitTestConstants.TextHelloWorld); + var info = new UTF8Encoding(true).GetBytes(text); stream.Write(info, 0, info.Length); } using (var stream = Alphaleonis.Win32.Filesystem.File.OpenWrite(file2)) { - var info = new UTF8Encoding(true).GetBytes(UnitTestConstants.TextHelloWorld); + var info = new UTF8Encoding(true).GetBytes(text); stream.Write(info, 0, info.Length); } diff --git a/AlphaFS.UnitTest/File Class/File.Open/File_Open_Append.cs b/AlphaFS.UnitTest/File Class/File.Open/File_Open_Append.cs index d16bc713d..d3a95e15a 100644 --- a/AlphaFS.UnitTest/File Class/File.Open/File_Open_Append.cs +++ b/AlphaFS.UnitTest/File Class/File.Open/File_Open_Append.cs @@ -47,7 +47,8 @@ private void Open_Append(bool isNetwork) long fileLength; - var ten = UnitTestConstants.TenNumbers.Length; + var tenNumbers = "0123456789"; + var ten = tenNumbers.Length; @@ -55,7 +56,7 @@ private void Open_Append(bool isNetwork) using (var fs = Alphaleonis.Win32.Filesystem.File.Open(file, System.IO.FileMode.Create)) { // According to NotePad++, creates a file type: "ANSI", which is reported as: "Unicode (UTF-8)". - fs.Write(UnitTestConstants.StringToByteArray(UnitTestConstants.TenNumbers), 0, ten); + fs.Write(UnitTestConstants.StringToByteArray(tenNumbers), 0, ten); fileLength = fs.Length; } @@ -68,7 +69,7 @@ private void Open_Append(bool isNetwork) using (var fs = Alphaleonis.Win32.Filesystem.File.Open(file, System.IO.FileMode.Append)) { // According to NotePad++, creates a file type: "ANSI", which is reported as: "Unicode (UTF-8)". - fs.Write(UnitTestConstants.StringToByteArray(UnitTestConstants.TenNumbers), 0, ten); + fs.Write(UnitTestConstants.StringToByteArray(tenNumbers), 0, ten); fileLength = fs.Length; } diff --git a/AlphaFS.UnitTest/File Class/File.Open/File_Open_Create.cs b/AlphaFS.UnitTest/File Class/File.Open/File_Open_Create.cs index 405dd6191..82265f1b2 100644 --- a/AlphaFS.UnitTest/File Class/File.Open/File_Open_Create.cs +++ b/AlphaFS.UnitTest/File Class/File.Open/File_Open_Create.cs @@ -47,12 +47,13 @@ private void File_Open_Create(bool isNetwork) long fileLength; - var ten = UnitTestConstants.TenNumbers.Length; + var tenNumbers = "0123456789"; + var ten = tenNumbers.Length; using (var fs = Alphaleonis.Win32.Filesystem.File.Open(file, System.IO.FileMode.Create)) { // According to NotePad++, creates a file type: "ANSI", which is reported as: "Unicode (UTF-8)". - fs.Write(UnitTestConstants.StringToByteArray(UnitTestConstants.TenNumbers), 0, ten); + fs.Write(UnitTestConstants.StringToByteArray(tenNumbers), 0, ten); fileLength = fs.Length; } diff --git a/AlphaFS.UnitTest/File Class/File.Replace/File.Replace.cs b/AlphaFS.UnitTest/File Class/File.Replace/File.Replace.cs index 23512c1f3..f9a52d045 100644 --- a/AlphaFS.UnitTest/File Class/File.Replace/File.Replace.cs +++ b/AlphaFS.UnitTest/File Class/File.Replace/File.Replace.cs @@ -41,30 +41,36 @@ private void File_Replace(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var fileSrc = tempRoot.RandomFileNoExtensionFullPath + "-" + UnitTestConstants.TextHelloWorld + ".txt"; - var fileDst = tempRoot.RandomFileNoExtensionFullPath + "-" + UnitTestConstants.TextGoodbyeWorld + ".txt"; - var fileBackup = tempRoot.RandomFileNoExtensionFullPath + "-Backup.txt"; + var fileSrc = tempRoot.RandomTxtFileFullPath; + var fileDst = tempRoot.RandomTxtFileFullPath; + var fileBackup = tempRoot.RandomTxtFileFullPath + "-Backup.txt"; + var text = System.IO.Path.GetRandomFileName(); - Console.WriteLine("Input File Path: [{0}]", fileSrc); + Console.WriteLine("Src File Path: [{0}]", fileSrc); + Console.WriteLine("Dst File Path: [{0}]", fileDst); + Console.WriteLine("Backup File Path: [{0}]", fileBackup); + Console.WriteLine("Text : [{0}]", text); using (var stream = System.IO.File.CreateText(fileSrc)) - stream.Write(UnitTestConstants.TextHelloWorld); + stream.Write(text); using (var stream = System.IO.File.CreateText(fileDst)) - stream.Write(UnitTestConstants.TextGoodbyeWorld); + stream.Write(text); Alphaleonis.Win32.Filesystem.File.Replace(fileSrc, fileDst, fileBackup); Assert.IsFalse(System.IO.File.Exists(fileSrc), "The file exists, but is expected not to."); + Assert.IsTrue(System.IO.File.Exists(fileDst), "The file does not exist, but is expected to."); - Assert.IsTrue(System.IO.File.Exists(fileBackup), "The file does not exist, but is expected to."); + Assert.IsTrue(System.IO.File.Exists(fileBackup), "The file does not exist, but is expected to."); + + Assert.AreEqual(text, Alphaleonis.Win32.Filesystem.File.ReadAllText(fileDst), "The texts do not match, but are expected to."); - Assert.AreEqual(UnitTestConstants.TextHelloWorld, Alphaleonis.Win32.Filesystem.File.ReadAllText(fileDst), "The texts do not match, but are expected to."); - Assert.AreEqual(UnitTestConstants.TextGoodbyeWorld, Alphaleonis.Win32.Filesystem.File.ReadAllText(fileBackup), "The texts do not match, but are expected to."); + Assert.AreEqual(text, Alphaleonis.Win32.Filesystem.File.ReadAllText(fileBackup), "The texts do not match, but are expected to."); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/File Class/File.Replace/File.Replace_NoBackup.cs b/AlphaFS.UnitTest/File Class/File.Replace/File.Replace_NoBackup.cs index 1dbf069ee..d05260ac7 100644 --- a/AlphaFS.UnitTest/File Class/File.Replace/File.Replace_NoBackup.cs +++ b/AlphaFS.UnitTest/File Class/File.Replace/File.Replace_NoBackup.cs @@ -41,29 +41,34 @@ private void File_Replace_NoBackup(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var fileSrc = tempRoot.RandomFileNoExtensionFullPath + "-" + UnitTestConstants.TextHelloWorld + ".txt"; - var fileDst = tempRoot.RandomFileNoExtensionFullPath + "-" + UnitTestConstants.TextGoodbyeWorld + ".txt"; - var fileBackup = tempRoot.RandomFileNoExtensionFullPath + "-Backup.txt"; + var fileSrc = tempRoot.RandomTxtFileFullPath; + var fileDst = tempRoot.RandomTxtFileFullPath; + var fileBackup = tempRoot.RandomTxtFileFullPath + "-Backup.txt"; + var text = System.IO.Path.GetRandomFileName(); - Console.WriteLine("Input File Path: [{0}]", fileSrc); + Console.WriteLine("Src File Path: [{0}]", fileSrc); + Console.WriteLine("Dst File Path: [{0}]", fileDst); + Console.WriteLine("Backup File Path: [{0}]", fileBackup); + Console.WriteLine("Text : [{0}]", text); using (var stream = System.IO.File.CreateText(fileSrc)) - stream.Write(UnitTestConstants.TextHelloWorld); + stream.Write(text); using (var stream = System.IO.File.CreateText(fileDst)) - stream.Write(UnitTestConstants.TextGoodbyeWorld); + stream.Write(text); Alphaleonis.Win32.Filesystem.File.Replace(fileSrc, fileDst, null); Assert.IsFalse(System.IO.File.Exists(fileSrc), "The file exists, but is expected not to."); + Assert.IsTrue(System.IO.File.Exists(fileDst), "The file does not exist, but is expected to."); - Assert.IsFalse(System.IO.File.Exists(fileBackup), "The file exists, but is expected not to."); + Assert.IsFalse(System.IO.File.Exists(fileBackup), "The file exists, but is expected not to."); - Assert.AreEqual(UnitTestConstants.TextHelloWorld, Alphaleonis.Win32.Filesystem.File.ReadAllText(fileDst), "The texts do not match, but are expected to."); + Assert.AreEqual(text, Alphaleonis.Win32.Filesystem.File.ReadAllText(fileDst), "The texts do not match, but are expected to."); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/File Class/File_Create/File.Create.cs b/AlphaFS.UnitTest/File Class/File_Create/File.Create.cs index b4a88bd6d..8f04b44a2 100644 --- a/AlphaFS.UnitTest/File Class/File_Create/File.Create.cs +++ b/AlphaFS.UnitTest/File Class/File_Create/File.Create.cs @@ -45,19 +45,20 @@ private void File_Create(bool isNetwork) #if NET35 // MSDN: .NET 4+ Trailing spaces are removed from the end of the path parameter before deleting the directory. - file += UnitTestConstants.EMspace; + file += "\u3000"; // EMspace #endif Console.WriteLine("Input File Path: [{0}]\n", file); long fileLength; - var ten = UnitTestConstants.TenNumbers.Length; + 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(UnitTestConstants.TenNumbers), 0, ten); + fs.Write(UnitTestConstants.StringToByteArray(tenNumbers), 0, ten); fileLength = fs.Length; } diff --git a/AlphaFS.UnitTest/File Class/File_Create/File.CreateText.cs b/AlphaFS.UnitTest/File Class/File_Create/File.CreateText.cs index 2aff46875..db2407874 100644 --- a/AlphaFS.UnitTest/File Class/File_Create/File.CreateText.cs +++ b/AlphaFS.UnitTest/File Class/File_Create/File.CreateText.cs @@ -44,18 +44,20 @@ private void File_CreateText(bool isNetwork) { var file1 = tempRoot.RandomTxtFileFullPath; var file2 = tempRoot.RandomTxtFileFullPath; + var text = System.IO.Path.GetRandomFileName(); Console.WriteLine("Input File1 Path: [{0}]", file1); Console.WriteLine("Input File2 Path: [{0}]", file2); - + Console.WriteLine("Text : [{0}]", text); using (var stream = System.IO.File.CreateText(file1)) - stream.Write(UnitTestConstants.TextHelloWorld); + stream.Write(text); using (var stream = Alphaleonis.Win32.Filesystem.File.CreateText(file2)) { - stream.Write(UnitTestConstants.TextHelloWorld); + stream.Write(text); + Assert.AreEqual(stream.Encoding, Encoding.UTF8, "The text encoding is not equal, but is expected to."); } diff --git a/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs b/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs index 1bb762520..600898697 100644 --- a/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs +++ b/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs @@ -42,7 +42,7 @@ private void AlphaFS_File_GetChangeTime(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { - var notepadFile = UnitTestConstants.NotepadExe; + var notepadFile = System.IO.Path.Combine(Environment.SystemDirectory, "notepad.exe"); Console.WriteLine("Input File Path: [{0}]", notepadFile); diff --git a/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetRelativePathResolveRelativePath.cs b/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetRelativePathResolveRelativePath.cs index c839dc943..b53172a9a 100644 --- a/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetRelativePathResolveRelativePath.cs +++ b/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetRelativePathResolveRelativePath.cs @@ -39,173 +39,175 @@ public void AlphaFS_Path_GetRelativePathResolveRelativePath_LocalAndNetwork_Succ private void AlphaFS_Path_GetRelativePathResolveRelativePath(bool isNetwork) { - UnitTestConstants.PrintUnitTestHeader(isNetwork); - - var tempPath = UnitTestConstants.TempPath; - var sysDrive = UnitTestConstants.SysDrive; - - if (isNetwork) - { - tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); - sysDrive = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(sysDrive); - } - - - string[] relativePaths = + using (var tempRoot = new TemporaryDirectory(isNetwork)) { - // 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", + var sysDrive = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.SysDrive) : UnitTestConstants.SysDrive; - sysDrive + @"\a\b", - sysDrive + @"\a", - @"..\a", - @"b", + 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 + @"\x\y\fso", + @"..\..\x\y\fso", + @"..\..\..\a\b", - sysDrive + @"\a\b\", - sysDrive + @"\", - @"..\..\", - @"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\fso", + @"..\..\fso", + @"..\b\c", - sysDrive + @"\a\b\c", - sysDrive + @"\a\x\y\fso", - @"..\..\x\y\fso", - @"..\..\..\b\c", + sysDrive + @"\a\b\c", + sysDrive + @"\a\x\fso", + @"..\..\x\fso", + @"..\..\b\c", - sysDrive + @"\a\b\c", - sysDrive + @"\fso", - @"..\..\..\fso", - @"..\a\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, - tempPath, - tempPath, - string.Empty, - string.Empty - }; + tempRoot.Directory.FullName, + tempRoot.Directory.FullName, + tempRoot.Directory.Name, + tempRoot.Directory.Name + }; - var totalPaths = relativePaths.Length; + + 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]; + 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); + 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); + 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); + var verify = System.IO.Path.IsPathRooted(current) && current[0] != Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar; - Assert.AreEqual(selected, absolute, "The absolute paths do not match, but are expected to."); - } + if (verify) + { + Console.WriteLine("\tAbsolute: [{0}]", absolute); - Console.WriteLine(); + Assert.AreEqual(selected, absolute, "The absolute paths do not match, but are expected to."); + } - Assert.AreEqual(shouldBeCurrent, relative, "The relative 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); + relative = Alphaleonis.Win32.Filesystem.Path.GetRelativePath(selected, current); + absolute = Alphaleonis.Win32.Filesystem.Path.ResolveRelativePath(selected, current); - verify = System.IO.Path.IsPathRooted(selected) && selected[0] != Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar; - if (verify) - { - Console.WriteLine("\t Absolute: [{0}]", absolute); + Console.WriteLine("\t Current : [{0}]", selected); + Console.WriteLine("\t Selected: [{0}]", current); + Console.WriteLine("\t Relative: [{0}]", relative); - Assert.AreEqual(current, absolute, "The absolute paths do not match, but are expected to."); - } + 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."); + Assert.AreEqual(shouldBeSelected, relative, "The relative paths do not match, but are expected to."); - Console.WriteLine(); + + Console.WriteLine(); + } } } } diff --git a/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetShort83PathAndGetLongFrom83ShortPath_FromFile.cs b/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetShort83PathAndGetLongFrom83ShortPath_FromFile.cs index 61a58a0d1..669be2fff 100644 --- a/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetShort83PathAndGetLongFrom83ShortPath_FromFile.cs +++ b/AlphaFS.UnitTest/Path Class/AlphaFS_Path.GetShort83PathAndGetLongFrom83ShortPath_FromFile.cs @@ -44,36 +44,32 @@ public void AlphaFS_Path_GetShort83PathAndGetLongFrom83ShortPath_FromFile_LocalA private void AlphaFS_Path_GetShort83PathAndGetLongFrom83ShortPath_FromFile(bool isNetwork) { - UnitTestConstants.PrintUnitTestHeader(isNetwork); + using (var tempRoot = new TemporaryDirectory(isNetwork)) + { + var folder = System.IO.Path.Combine(tempRoot.Directory.FullName, "My Long Data File Or Directory"); + + string short83Path; - var myLongPath = System.IO.Path.Combine(UnitTestConstants.TempPath, "My Long Data File Or Directory"); - if (isNetwork) - myLongPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(myLongPath); + using (System.IO.File.Create(folder)) + short83Path = Alphaleonis.Win32.Filesystem.Path.GetShort83Path(folder); - string short83Path; + Console.WriteLine("Short 8.3 File Path: [{0}]", short83Path); + + Assert.IsTrue(!short83Path.Equals(folder)); - using (System.IO.File.Create(myLongPath)) - short83Path = Alphaleonis.Win32.Filesystem.Path.GetShort83Path(myLongPath); + Assert.IsTrue(short83Path.EndsWith(@"~1")); - Console.WriteLine("Short 8.3 File Path: [{0}]", short83Path); + var longFrom83Path = Alphaleonis.Win32.Filesystem.Path.GetLongFrom83ShortPath(short83Path); - Assert.IsTrue(!short83Path.Equals(myLongPath)); + Console.WriteLine("Long path from 8.3 path: [{0}]", longFrom83Path); - 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(myLongPath)); - - Assert.IsFalse(longFrom83Path.EndsWith(@"~1")); + Assert.IsTrue(longFrom83Path.Equals(folder)); + Assert.IsFalse(longFrom83Path.EndsWith(@"~1")); + } Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/Path Class/AlphaFS_Path.LocalToUnc.cs b/AlphaFS.UnitTest/Path Class/AlphaFS_Path.LocalToUnc.cs index cbde8b881..9a7f5cea6 100644 --- a/AlphaFS.UnitTest/Path Class/AlphaFS_Path.LocalToUnc.cs +++ b/AlphaFS.UnitTest/Path Class/AlphaFS_Path.LocalToUnc.cs @@ -35,7 +35,7 @@ public void AlphaFS_Path_LocalToUnc_Success() UnitTestConstants.PrintUnitTestHeader(false); var sysDrive = UnitTestConstants.SysDrive; - var sysRoot = UnitTestConstants.SysRoot; + 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; @@ -52,13 +52,13 @@ public void AlphaFS_Path_LocalToUnc_Success() uncPrefix + hostName + backslash, uncLongPrefix + hostName + backslash, - sysRoot, - uncPrefix + hostName + backslash + System.IO.Path.GetFileName(sysRoot), - uncLongPrefix + hostName + backslash + System.IO.Path.GetFileName(sysRoot), + windowsFolder, + uncPrefix + hostName + backslash + System.IO.Path.GetFileName(windowsFolder), + uncLongPrefix + hostName + backslash + System.IO.Path.GetFileName(windowsFolder), - sysRoot + backslash + "TempPath" + backslash, - uncPrefix + hostName + backslash + System.IO.Path.GetFileName(sysRoot) + backslash + "TempPath" + backslash, - uncLongPrefix + hostName + backslash + System.IO.Path.GetFileName(sysRoot) + backslash + "TempPath" + backslash + 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 }; diff --git a/AlphaFS.UnitTest/Path Class/AlphaFS_Path_GetMappedName/AlphaFS_Path.GetMappedConnectionName.cs b/AlphaFS.UnitTest/Path Class/AlphaFS_Path_GetMappedName/AlphaFS_Path.GetMappedConnectionName.cs index 455461bcf..deb209ccb 100644 --- a/AlphaFS.UnitTest/Path Class/AlphaFS_Path_GetMappedName/AlphaFS_Path.GetMappedConnectionName.cs +++ b/AlphaFS.UnitTest/Path Class/AlphaFS_Path_GetMappedName/AlphaFS_Path.GetMappedConnectionName.cs @@ -32,24 +32,26 @@ public partial class PathTest [TestMethod] public void AlphaFS_Path_GetMappedConnectionName() { - UnitTestConstants.PrintUnitTestHeader(false); + using (var tempRoot = new TemporaryDirectory(true)) + { + // Randomly test the share where the local folder possibly has the read-only and/or hidden attributes set. - var share = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.TempPath); + var folder = tempRoot.CreateDirectoryRandomizedAttributes(); - using (var connection = new Alphaleonis.Win32.Network.DriveConnection(share)) - { - var driveName = connection.LocalName; - Console.WriteLine("Mapped drive letter [{0}] to [{1}]", driveName, share); + using (var connection = new Alphaleonis.Win32.Network.DriveConnection(folder.FullName)) + { + var driveName = connection.LocalName; + + Console.WriteLine("Mapped drive letter [{0}] to [{1}]", driveName, folder.FullName); - UnitTestConstants.Dump(connection, -9); - + UnitTestConstants.Dump(connection, -9); - var connectionName = Alphaleonis.Win32.Filesystem.Path.GetMappedConnectionName(driveName); - Console.WriteLine("\n\tGetMappedConnectionName: [{0}]", connectionName); + var connectionName = Alphaleonis.Win32.Filesystem.Path.GetMappedConnectionName(driveName); - Assert.AreEqual(share, connectionName + @"\"); + Assert.AreEqual(folder.FullName, connectionName); + } } } } diff --git a/AlphaFS.UnitTest/Path Class/AlphaFS_Path_GetMappedName/AlphaFS_Path.GetMappedUncName.cs b/AlphaFS.UnitTest/Path Class/AlphaFS_Path_GetMappedName/AlphaFS_Path.GetMappedUncName.cs index 230064103..63836203a 100644 --- a/AlphaFS.UnitTest/Path Class/AlphaFS_Path_GetMappedName/AlphaFS_Path.GetMappedUncName.cs +++ b/AlphaFS.UnitTest/Path Class/AlphaFS_Path_GetMappedName/AlphaFS_Path.GetMappedUncName.cs @@ -32,24 +32,26 @@ public partial class PathTest [TestMethod] public void AlphaFS_Path_GetMappedUncName() { - UnitTestConstants.PrintUnitTestHeader(false); + using (var tempRoot = new TemporaryDirectory(true)) + { + // Randomly test the share where the local folder possibly has the read-only and/or hidden attributes set. - var share = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.TempPath); + var folder = tempRoot.CreateDirectoryRandomizedAttributes(); - using (var connection = new Alphaleonis.Win32.Network.DriveConnection(share)) - { - var driveName = connection.LocalName; - Console.WriteLine("Mapped drive letter [{0}] to [{1}]", driveName, share); + using (var connection = new Alphaleonis.Win32.Network.DriveConnection(folder.FullName)) + { + var driveName = connection.LocalName; + + Console.WriteLine("Mapped drive letter [{0}] to [{1}]", driveName, folder.FullName); - UnitTestConstants.Dump(connection, -9); - + UnitTestConstants.Dump(connection, -9); - var shareName = Alphaleonis.Win32.Filesystem.Path.GetMappedUncName(driveName); - Console.WriteLine("\n\tGetMappedUncName: [{0}]", shareName); + var connectionName = Alphaleonis.Win32.Filesystem.Path.GetMappedUncName(driveName); - Assert.AreEqual(share, shareName + @"\"); + Assert.AreEqual(folder.FullName, connectionName); + } } } } diff --git a/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetDirectoryNameWithoutRoot.cs b/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetDirectoryNameWithoutRoot.cs index 2862f91b7..cc33f1f44 100644 --- a/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetDirectoryNameWithoutRoot.cs +++ b/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetDirectoryNameWithoutRoot.cs @@ -32,8 +32,7 @@ public partial class PathTest [TestMethod] public void AlphaFS_Path_GetDirectoryNameWithoutRoot_LocalAndNetwork_Success() { - // Note: since System.IO.Path does not have a similar method, - // some more work is needed to test the validity of these result. + // Note: System.IO.Path does not have a similar method to compare with. AlphaFS_Path_GetDirectoryNameWithoutRoot(false); AlphaFS_Path_GetDirectoryNameWithoutRoot(true); @@ -43,12 +42,12 @@ public void AlphaFS_Path_GetDirectoryNameWithoutRoot_LocalAndNetwork_Success() private void AlphaFS_Path_GetDirectoryNameWithoutRoot(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); - + const string neDir = "Non-Existing Directory"; - const string sys32 = "system32"; + const string system32Folder = "system32"; - var fullPath = System.IO.Path.Combine(UnitTestConstants.SysRoot32, neDir); + var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, neDir); if (isNetwork) fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath); @@ -57,7 +56,7 @@ private void AlphaFS_Path_GetDirectoryNameWithoutRoot(bool isNetwork) Console.WriteLine("Full Path : " + fullPath); Console.WriteLine("GetDirectoryNameWithoutRoot: " + directoryNameWithoutRoot); - Assert.AreEqual(directoryNameWithoutRoot, sys32); + Assert.AreEqual(system32Folder, directoryNameWithoutRoot); @@ -71,12 +70,12 @@ private void AlphaFS_Path_GetDirectoryNameWithoutRoot(bool isNetwork) Console.WriteLine("\nFull Path : " + fullPath); Console.WriteLine("GetDirectoryNameWithoutRoot: " + directoryNameWithoutRoot); - Assert.AreEqual(directoryNameWithoutRoot, neDir); + Assert.AreEqual(neDir, directoryNameWithoutRoot); - fullPath = UnitTestConstants.SysRoot; + fullPath = Environment.SystemDirectory; if (isNetwork) fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath); @@ -85,7 +84,13 @@ private void AlphaFS_Path_GetDirectoryNameWithoutRoot(bool isNetwork) Console.WriteLine("\nFull Path : " + fullPath); Console.WriteLine("GetDirectoryNameWithoutRoot: " + directoryNameWithoutRoot); - Assert.AreEqual(null, directoryNameWithoutRoot); + + var windowsFolderName = System.IO.Path.GetDirectoryName(fullPath) .Replace(System.IO.Directory.GetDirectoryRoot(fullPath), string.Empty); + + if (isNetwork) + windowsFolderName = windowsFolderName.TrimStart(Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar); + + Assert.AreEqual(windowsFolderName, directoryNameWithoutRoot); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetSuffixedDirectoryName.cs b/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetSuffixedDirectoryName.cs index 620ec9cb3..135ebbe1f 100644 --- a/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetSuffixedDirectoryName.cs +++ b/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetSuffixedDirectoryName.cs @@ -42,14 +42,17 @@ private void AlphaFS_Path_GetSuffixedDirectoryName(bool isNetwork) UnitTestConstants.PrintUnitTestHeader(isNetwork); var neDir = "Non-Existing Directory"; - var sys32 = UnitTestConstants.SysRoot32 + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator; + var windowsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Windows); + var system32Folder = Environment.SystemDirectory + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator; - var fullPath = System.IO.Path.Combine(UnitTestConstants.SysRoot32, neDir); + + var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, neDir); if (isNetwork) { fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath); - sys32 = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(sys32); + windowsFolder = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(windowsFolder); + system32Folder = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(system32Folder); } var suffixedDirectoryName = Alphaleonis.Win32.Filesystem.Path.GetSuffixedDirectoryName(fullPath); @@ -57,13 +60,13 @@ private void AlphaFS_Path_GetSuffixedDirectoryName(bool isNetwork) Console.WriteLine("Full Path : " + fullPath); Console.WriteLine("GetSuffixedDirectoryName: " + suffixedDirectoryName); - Assert.IsTrue(suffixedDirectoryName.Equals(sys32, StringComparison.OrdinalIgnoreCase)); + Assert.IsTrue(suffixedDirectoryName.Equals(system32Folder, StringComparison.OrdinalIgnoreCase)); fullPath = System.IO.Path.Combine(fullPath, "Non-Existing file.txt"); - neDir = System.IO.Path.Combine(UnitTestConstants.SysRoot32, neDir) + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator; + neDir = System.IO.Path.Combine(Environment.SystemDirectory, neDir) + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator; if (isNetwork) { fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath); @@ -80,7 +83,7 @@ private void AlphaFS_Path_GetSuffixedDirectoryName(bool isNetwork) - fullPath = UnitTestConstants.SysRoot; + fullPath = Environment.SystemDirectory; if (isNetwork) fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath); @@ -89,7 +92,7 @@ private void AlphaFS_Path_GetSuffixedDirectoryName(bool isNetwork) Console.WriteLine("\nFull Path : " + fullPath); Console.WriteLine("GetSuffixedDirectoryName: " + suffixedDirectoryName); - Assert.AreEqual(null, suffixedDirectoryName); + Assert.AreEqual(windowsFolder, suffixedDirectoryName.TrimEnd(Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar)); diff --git a/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetSuffixedDirectoryNameWithoutRoot.cs b/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetSuffixedDirectoryNameWithoutRoot.cs index ff89693f3..8adb559f4 100644 --- a/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetSuffixedDirectoryNameWithoutRoot.cs +++ b/AlphaFS.UnitTest/Path Class/Path.GetDirectoryName/AlphaFS_Path.GetSuffixedDirectoryNameWithoutRoot.cs @@ -32,9 +32,7 @@ public partial class PathTest [TestMethod] public void AlphaFS_Path_GetSuffixedDirectoryNameWithoutRoot_LocalAndNetwork_Success() { - // Note: since System.IO.Path does not have a similar method, - // some more work is needed to test the validity of these result. - + // Note: System.IO.Path does not have a similar method to compare with. AlphaFS_Path_GetSuffixedDirectoryNameWithoutRoot(false); AlphaFS_Path_GetSuffixedDirectoryNameWithoutRoot(true); @@ -45,11 +43,12 @@ private void AlphaFS_Path_GetSuffixedDirectoryNameWithoutRoot(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); + var backslash = Alphaleonis.Win32.Filesystem.Path.DirectorySeparator; var neDir = "Non-Existing Directory"; - var sys32 = (UnitTestConstants.SysRoot32 + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator).Replace(UnitTestConstants.SysDrive + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator, ""); + var system32Folder = (Environment.SystemDirectory + backslash).Replace(UnitTestConstants.SysDrive + backslash, string.Empty); - var fullPath = System.IO.Path.Combine(UnitTestConstants.SysRoot32 + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator, neDir); + var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, neDir); if (isNetwork) fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath); @@ -58,13 +57,13 @@ private void AlphaFS_Path_GetSuffixedDirectoryNameWithoutRoot(bool isNetwork) Console.WriteLine("Full Path : " + fullPath); Console.WriteLine("GetSuffixedDirectoryNameWithoutRoot: " + suffixedDirectoryNameWithoutRoot); - Assert.AreEqual(sys32, suffixedDirectoryNameWithoutRoot); + Assert.AreEqual(system32Folder, suffixedDirectoryNameWithoutRoot); fullPath = System.IO.Path.Combine(fullPath, "Non-Existing file.txt"); - neDir = (System.IO.Path.Combine(UnitTestConstants.SysRoot32, neDir) + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator).Replace(UnitTestConstants.SysDrive + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator, ""); + neDir = (System.IO.Path.Combine(Environment.SystemDirectory, neDir) + backslash).Replace(UnitTestConstants.SysDrive + backslash, string.Empty); if (isNetwork) fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath); @@ -73,12 +72,12 @@ private void AlphaFS_Path_GetSuffixedDirectoryNameWithoutRoot(bool isNetwork) Console.WriteLine("\nFull Path : " + fullPath); Console.WriteLine("GetSuffixedDirectoryNameWithoutRoot: " + suffixedDirectoryNameWithoutRoot); - Assert.AreEqual(suffixedDirectoryNameWithoutRoot, neDir); + Assert.AreEqual(neDir, suffixedDirectoryNameWithoutRoot); - fullPath = UnitTestConstants.SysRoot; + fullPath = Environment.SystemDirectory; if (isNetwork) fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath); @@ -87,12 +86,18 @@ private void AlphaFS_Path_GetSuffixedDirectoryNameWithoutRoot(bool isNetwork) Console.WriteLine("\nFull Path : " + fullPath); Console.WriteLine("GetSuffixedDirectoryNameWithoutRoot: " + suffixedDirectoryNameWithoutRoot); - Assert.AreEqual(null, 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 + Alphaleonis.Win32.Filesystem.Path.DirectorySeparator; + fullPath = UnitTestConstants.SysDrive + backslash; if (isNetwork) fullPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(fullPath); diff --git a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathContainsInvalidCharacters.cs b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathContainsInvalidCharacters.cs index 526065d0c..0e2e7fd82 100644 --- a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathContainsInvalidCharacters.cs +++ b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathContainsInvalidCharacters.cs @@ -32,19 +32,14 @@ public partial class PathTest [TestMethod] public void AlphaFS_Path_CheckSupportedPathFormat_ThrowArgumentException_PathContainsInvalidCharacters_Local_Success() { - Path_CheckSupportedPathFormat_ThrowArgumentException_PathContainsInvalidCharacters(); - } - - - private void Path_CheckSupportedPathFormat_ThrowArgumentException_PathContainsInvalidCharacters() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var invalidPath = UnitTestConstants.TempPath + @"\ThisIsFile"; + using (var tempRoot = new TemporaryDirectory()) + { + var folder = tempRoot.Directory.FullName + @"\ThisIsFile"; - Console.WriteLine("Invalid Path: [{0}]", invalidPath); + Console.WriteLine("Input Path: [{0}]", folder); - ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Path.CheckSupportedPathFormat(invalidPath, true, true)); + ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Path.CheckSupportedPathFormat(folder, true, true)); + } } } } diff --git a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathStartsWithColon.cs b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathStartsWithColon.cs index 666a4363d..fabfe6a8d 100644 --- a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathStartsWithColon.cs +++ b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathStartsWithColon.cs @@ -42,7 +42,7 @@ private void Path_CheckSupportedPathFormat_ThrowArgumentException_PathStartsWith const string invalidPath = @":AAAAAAAAAA"; - Console.WriteLine("Invalid Path: [{0}]", invalidPath); + Console.WriteLine("Input Path: [{0}]", invalidPath); ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Path.CheckSupportedPathFormat(invalidPath, true, true)); } diff --git a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowNotSupportedException_PathContainsColon.cs b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowNotSupportedException_PathContainsColon.cs index 230621f95..bfc38c0da 100644 --- a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowNotSupportedException_PathContainsColon.cs +++ b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowNotSupportedException_PathContainsColon.cs @@ -39,16 +39,15 @@ public void AlphaFS_Path_CheckSupportedPathFormat_ThrowNotSupportedException_Pat private void Path_CheckSupportedPathFormat_ThrowNotSupportedException_PathContainsColon(bool isNetwork) { - UnitTestConstants.PrintUnitTestHeader(isNetwork); + using (var tempRoot = new TemporaryDirectory(isNetwork)) + { + var folder = tempRoot.Directory.FullName + @"\My:FilePath"; - const string colonText = @"\My:FilePath"; - - var invalidPath = (isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(UnitTestConstants.TempPath) : UnitTestConstants.TempPath + @"\dev\test") + colonText; - - Console.WriteLine("Invalid Path: [{0}]", invalidPath); - - ExceptionAssert.NotSupportedException(() => Alphaleonis.Win32.Filesystem.Path.CheckSupportedPathFormat(invalidPath, true, true)); + Console.WriteLine("Input Path: [{0}]", folder); + ExceptionAssert.NotSupportedException(() => Alphaleonis.Win32.Filesystem.Path.CheckSupportedPathFormat(folder, true, true)); + } + Console.WriteLine(); } } diff --git a/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs index fafe32517..27e38d105 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs @@ -40,7 +40,7 @@ public TemporaryDirectory(bool isNetwork, string folderPrefix = null, string roo folderPrefix = "AlphaFS.TempRoot"; if (Alphaleonis.Utils.IsNullOrWhiteSpace(root)) - root = UnitTestConstants.TempPath; + root = TempPath; if (isNetwork) root = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(root); @@ -137,7 +137,7 @@ public System.IO.DirectoryInfo CreateDirectory() } - /// Returns a instance to an existing directory, possibly with hidden and/or read-only attributes set. + /// Returns a instance to an existing directory, possibly with read-only and/or hidden attributes set. public System.IO.DirectoryInfo CreateDirectoryRandomizedAttributes() { return CreateDirectory(null, true, true); @@ -153,7 +153,7 @@ public System.IO.FileInfo CreateFile() } - /// Returns a instance to an existing file, possibly with hidden and/or read-only attributes set. + /// Returns a instance to an existing file, possibly with read-only and/or hidden attributes set. public System.IO.FileInfo CreateFileRandomizedAttributes() { return CreateFile(null, true, true); @@ -197,7 +197,7 @@ public System.IO.DirectoryInfo CreateRecursiveRandomizedAttributesTree(int level } - /// Creates an, optional recursive, directory structure of levels deep, populated with subdirectories and files with of random size and possibly with hidden and/or read-only attributes set. + /// Creates an, optional recursive, directory structure of levels deep, populated with subdirectories and files with of random size and possibly with read-only and/or hidden attributes set. private System.IO.DirectoryInfo CreateTreeCore(string rootFullPath, int level, bool recurse, bool readOnly, bool hidden) { var dirInfo = CreateDirectory(rootFullPath, readOnly, hidden); @@ -279,7 +279,11 @@ public override string ToString() #region Private Members - /// Returns a instance to an existing directory, possibly with hidden and/or read-only attributes set. + /// The path to the temporary folder, ending with a backslash. + private static readonly string TempPath = System.IO.Path.GetTempPath(); + + + /// Returns a instance to an existing directory, possibly with read-only and/or hidden attributes set. private System.IO.DirectoryInfo CreateDirectory(string folderFullPath, bool readOnly = false, bool hidden = false) { var dirInfo = System.IO.Directory.CreateDirectory(!Alphaleonis.Utils.IsNullOrWhiteSpace(folderFullPath) ? folderFullPath : RandomDirectoryFullPath); @@ -290,7 +294,7 @@ private System.IO.DirectoryInfo CreateDirectory(string folderFullPath, bool read } - /// Returns a instance to an existing file, possibly with hidden and/or read-only attributes set. + /// Returns a instance to an existing file, possibly with read-only and/or hidden attributes set. private System.IO.FileInfo CreateFile(string fileFullPath, bool readOnly = false, bool hidden = false) { var fileInfo = new System.IO.FileInfo(!Alphaleonis.Utils.IsNullOrWhiteSpace(fileFullPath) ? fileFullPath : RandomTxtFileFullPath); diff --git a/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs b/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs index e0406987b..398482e5c 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs @@ -27,30 +27,6 @@ namespace AlphaFS.UnitTest /// Containts static variables, used by unit tests. public static partial class UnitTestConstants { -#if NET35 - public const string EMspace = "\u3000"; -#endif - - /// The path to the temporary folder, ending with a backslash. - public static readonly string TempPath = System.IO.Path.GetTempPath(); - - public static readonly string SysRoot = Environment.GetEnvironmentVariable("SystemRoot"); - public static readonly string SysRoot32 = Environment.SystemDirectory; - public static readonly string AppData = Environment.GetEnvironmentVariable("AppData"); - public static readonly string NotepadExe = System.IO.Path.Combine(SysRoot32, "notepad.exe"); - - public const string TextTrue = "IsTrue"; - public const string TextFalse = "IsFalse"; - public const string TenNumbers = "0123456789"; - public const string TextHelloWorld = "Hëllõ Wørld!"; - public const string TextGoodbyeWorld = "Góödbyé Wôrld!"; - public const string TextUnicode = "ÛņïÇòdè; ǖŤƑ"; - - - /// The Computer name. - public static readonly string LocalHost = Environment.MachineName; - - /// The Computer system drive. For example "C:". public static readonly string SysDrive = Environment.GetEnvironmentVariable("SystemDrive"); @@ -59,7 +35,7 @@ public static partial class UnitTestConstants { "(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) " + TextHelloWorld + " " + TextUnicode + "(3) " + System.IO.Path.GetRandomFileName() }; @@ -112,39 +88,39 @@ public static partial class UnitTestConstants 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 + LocalHost + @"\Share", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\f", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fi", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\fil", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.e", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ex", - Alphaleonis.Win32.Filesystem.Path.UncPrefix + LocalHost + @"\Share\d1\d2\file.ext", - - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\f", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fi", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\fil", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.e", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ex", - Alphaleonis.Win32.Filesystem.Path.LongPathUncPrefix + LocalHost + @"\Share\d1\d2\file.ext" + 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" }; } } diff --git a/AlphaFS/Network/Host Class/Host.cs b/AlphaFS/Network/Host Class/Host.cs index 5257392c4..384561137 100644 --- a/AlphaFS/Network/Host Class/Host.cs +++ b/AlphaFS/Network/Host Class/Host.cs @@ -105,7 +105,6 @@ internal static string ConnectDisconnectCore(ConnectDisconnectArguments argument arguments.LocalName = Path.RemoveTrailingDirectorySeparator(arguments.LocalName).ToUpperInvariant(); - // Add backslashes. if (!Utils.IsNullOrWhiteSpace(arguments.RemoteName)) { if (!arguments.RemoteName.StartsWith(Path.UncPrefix, StringComparison.Ordinal)) From 3cbe48c8758b7c0817de70917bec89c9d7a71582 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 30 May 2018 18:11:15 +0200 Subject: [PATCH 077/133] Fixed unit tests that would fail on a subst.exe created drive mapping. --- .../AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs | 2 +- .../AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs | 2 +- .../AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs index 9f0049184..2817c8189 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs @@ -41,7 +41,7 @@ public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrive_Success() foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { - if (drive.DriveType == System.IO.DriveType.Network) + if (drive.DriveType == System.IO.DriveType.NoRootDirectory || drive.DriveType == System.IO.DriveType.Network) continue; var storageAdapterInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageAdapterInfo(drive.Name); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index 48110dfec..14730ce13 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -40,7 +40,7 @@ public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { - if (drive.DriveType == System.IO.DriveType.Network) + if (drive.DriveType == System.IO.DriveType.NoRootDirectory || drive.DriveType == System.IO.DriveType.Network) continue; var storageDeviceInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageDeviceInfo(drive.Name); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs index b8daca66c..bbb3660ee 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs @@ -40,7 +40,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrive_Success() foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { - if (drive.DriveType == System.IO.DriveType.Network) + if (drive.DriveType == System.IO.DriveType.NoRootDirectory || drive.DriveType == System.IO.DriveType.Network) continue; var storagePartitionInfo = Alphaleonis.Win32.Filesystem.Device.GetStoragePartitionInfo(drive.Name); From 2f6829d98f8da4747e02799f6e1e83a4a0cdcdf5 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 31 May 2018 22:16:01 +0200 Subject: [PATCH 078/133] Simplified unit test exception testing. (#449) (#450) --- ...am_ThrowIOException_FilePortionIsLocked.cs | 2 +- ...ThrowIOException_SegmentAlreadyUnlocked.cs | 2 +- ...efineDosDevice_SymbolicLinkDriveMapping.cs | 4 +- ...ption_FileExistsWithSameNameAsDirectory.cs | 4 +- ...ption_DirectoryExistsWithSameNameAsFile.cs | 2 +- ...tion_ThrowArgumentException_MappedDrive.cs | 2 +- ...Junction_ThrowArgumentException_UncPath.cs | 2 +- ...unction_ThrowDirectoryNotEmptyException.cs | 2 +- ...ption_FileExistsWithSameNameAsDirectory.cs | 2 +- ...ption_FileExistsWithSameNameAsDirectory.cs | 2 +- ...ption_DirectoryExistsWithSameNameAsFile.cs | 2 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 1 - ..._Overwrite_DestinationFileAlreadyExists.cs | 2 +- ...sException_DestinationFileAlreadyExists.cs | 2 +- ...tion_NonExistingDestinationLogicalDrive.cs | 2 +- ...Exception_NonExistingSourceLogicalDrive.cs | 2 +- ...undException_NonExistingSourceDirectory.cs | 2 +- ...ion_UserExplicitDenyOnDestinationFolder.cs | 2 +- ...ption_FileExistsWithSameNameAsDirectory.cs | 4 +- ...otReadyException_NonExistingDriveLetter.cs | 4 +- ...otFoundException_NonExistingDriveLetter.cs | 4 +- ...tReadyException_NonExistingLogicalDrive.cs | 8 +- ...toryNotEmptyException_NonEmptyDirectory.cs | 4 +- ...ryReadOnlyException_DirectoryIsReadOnly.cs | 4 +- ...ption_FileExistsWithSameNameAsDirectory.cs | 4 +- ...yNotFoundException_NonExistingDirectory.cs | 4 +- ...essException_DirectoryHasDenyPermission.cs | 4 +- ...ption_DestinationDirectoryAlreadyExists.cs | 4 +- ...tion_NonExistingDestinationLogicalDrive.cs | 2 +- ...Exception_NonExistingSourceLogicalDrive.cs | 2 +- ...undException_NonExistingSourceDirectory.cs | 4 +- ...rowIOException_SameSourceAndDestination.cs | 4 +- ...ion_UserExplicitDenyOnDestinationFolder.cs | 2 +- ...S_DirectoryInfo.MoveTo_DelayUntilReboot.cs | 2 +- ...tion_FolderNameGreaterThan255Characters.cs | 4 +- ..._Overwrite_DestinationFileAlreadyExists.cs | 4 +- ...sException_DestinationFileAlreadyExists.cs | 4 +- ...tion_NonExistingDestinationLogicalDrive.cs | 4 +- ...Exception_NonExistingSourceLogicalDrive.cs | 8 +- ...undException_NonExistingSourceDirectory.cs | 4 +- ...NotFoundException_NonExistingSourceFile.cs | 4 +- ...cessException_DestinationFileIsReadOnly.cs | 4 +- ...ThrowFileReadOnlyException_ReadOnlyFile.cs | 6 +- ...otFoundException_NonExistingDriveLetter.cs | 4 +- ...otReadyException_NonExistingDriveLetter.cs | 4 +- ...ccessException_PathIsADirectoryNotAFile.cs | 4 +- ..._Overwrite_DestinationFileAlreadyExists.cs | 4 +- ...sException_DestinationFileAlreadyExists.cs | 4 +- ...tion_NonExistingDestinationLogicalDrive.cs | 4 +- ...Exception_NonExistingSourceLogicalDrive.cs | 4 +- ...undException_NonExistingSourceDirectory.cs | 4 +- ...NotFoundException_NonExistingSourceFile.cs | 4 +- ...hrowArgumentException_InvalidLocalPath1.cs | 4 +- ...hrowArgumentException_InvalidLocalPath2.cs | 4 +- ....GetFullPath_ThrowNotSupportedException.cs | 5 +- ...hRoot_ThrowArgumentExceptionEmptyString.cs | 7 +- ...Exception_PathContainsInvalidCharacters.cs | 2 +- ...owArgumentException_PathStartsWithColon.cs | 2 +- ...NotSupportedException_PathContainsColon.cs | 2 +- .../UnitTest Utility/ExceptionAssert.cs | 135 ------------------ .../UnitTest Utility/UnitTestAssert.cs | 38 ++++- 61 files changed, 139 insertions(+), 237 deletions(-) delete mode 100644 AlphaFS.UnitTest/UnitTest Utility/ExceptionAssert.cs diff --git a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_FilePortionIsLocked.cs b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_FilePortionIsLocked.cs index 62de8fafc..667e40ee8 100644 --- a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_FilePortionIsLocked.cs +++ b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_FilePortionIsLocked.cs @@ -54,7 +54,7 @@ private void AlphaFS_BackupFileStream_ThrowIOException_FilePortionIsLocked(bool bfs.Lock(0, 10); - ExceptionAssert.IOException(() => bfs.Lock(0, 10)); + UnitTestAssert.ThrowsException(() => bfs.Lock(0, 10)); } finally { diff --git a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_SegmentAlreadyUnlocked.cs b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_SegmentAlreadyUnlocked.cs index 475e4c391..c4159b097 100644 --- a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_SegmentAlreadyUnlocked.cs +++ b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_ThrowIOException_SegmentAlreadyUnlocked.cs @@ -51,7 +51,7 @@ private void AlphaFS_BackupFileStream_ThrowIOException_SegmentAlreadyUnlocked(bo { bfs.ReadStreamInfo(); - ExceptionAssert.IOException(() => bfs.Unlock(0, 10)); + UnitTestAssert.ThrowsException(() => bfs.Unlock(0, 10)); } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs index a92c928c1..e91e8f49c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs @@ -55,8 +55,8 @@ public void AlphaFS_Volume_DefineDosDevice_SymbolicLinkDriveMapping(bool isNetwo // Remove Symbolic Link, no exact match: fail. - - ExceptionAssert.FileNotFoundException(() => Alphaleonis.Win32.Filesystem.Volume.DeleteDosDevice(drive, folder.FullName)); + + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Volume.DeleteDosDevice(drive, folder.FullName)); } finally { diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs index ceba9fa96..ddcb143cf 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs @@ -52,8 +52,8 @@ private void AlphaFS_Directory_GetFileSystemEntryInfo_ThrowDirectoryNotFoundExce tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath); Console.WriteLine("Input Directory Path: [{0}]", tempPath); - - ExceptionAssert.DirectoryNotFoundException(() => Alphaleonis.Win32.Filesystem.Directory.GetFileSystemEntryInfo(tempPath)); + + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.GetFileSystemEntryInfo(tempPath)); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo_ThrowFileNotFoundException_DirectoryExistsWithSameNameAsFile.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo_ThrowFileNotFoundException_DirectoryExistsWithSameNameAsFile.cs index 6382471d5..30e644124 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo_ThrowFileNotFoundException_DirectoryExistsWithSameNameAsFile.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_File.GetFileSystemEntryInfo_ThrowFileNotFoundException_DirectoryExistsWithSameNameAsFile.cs @@ -47,7 +47,7 @@ private void AlphaFS_File_GetFileSystemEntryInfo_ThrowFileNotFoundException_Dire Console.WriteLine("Input File Path: [{0}]", tempPath); - ExceptionAssert.FileNotFoundException(() => Alphaleonis.Win32.Filesystem.File.GetFileSystemEntryInfo(tempPath)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.GetFileSystemEntryInfo(tempPath)); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_MappedDrive.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_MappedDrive.cs index 6e30ffdc7..70b01486e 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_MappedDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_MappedDrive.cs @@ -45,7 +45,7 @@ public void AlphaFS_Directory_CreateJunction_ThrowArgumentException_MappedDrive_ var junction = System.IO.Path.Combine(toDelete.FullName, "JunctionPoint"); - ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Directory.CreateJunction(junction, target.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.CreateJunction(junction, target.FullName)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_UncPath.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_UncPath.cs index fd7a65d00..67c6b78cc 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_UncPath.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowArgumentException_UncPath.cs @@ -43,7 +43,7 @@ public void AlphaFS_Directory_CreateJunction_ThrowArgumentException_UncPath_Netw var junction = System.IO.Path.Combine(toDelete.FullName, "JunctionPoint"); - ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Directory.CreateJunction(junction, target.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.CreateJunction(junction, target.FullName)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowDirectoryNotEmptyException.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowDirectoryNotEmptyException.cs index b121f560f..762653f70 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowDirectoryNotEmptyException.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowDirectoryNotEmptyException.cs @@ -47,7 +47,7 @@ public void AlphaFS_Directory_CreateJunction_ThrowDirectoryNotEmptyException_Loc dirInfo.CreateSubdirectory("Extra Folder"); - ExceptionAssert.DirectoryNotEmptyException(() => Alphaleonis.Win32.Filesystem.Directory.CreateJunction(junction, target.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.CreateJunction(junction, target.FullName)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowIOException_FileExistsWithSameNameAsDirectory.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowIOException_FileExistsWithSameNameAsDirectory.cs index cbfa54531..ba51ac62e 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowIOException_FileExistsWithSameNameAsDirectory.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_ThrowIOException_FileExistsWithSameNameAsDirectory.cs @@ -44,7 +44,7 @@ public void AlphaFS_Directory_CreateJunction_ThrowIOException_FileExistsWithSame using (System.IO.File.CreateText(junction)) { } - ExceptionAssert.IOException(() => Alphaleonis.Win32.Filesystem.Directory.CreateJunction(junction, target.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.CreateJunction(junction, target.FullName)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateSymbolicLink_ThrowIOException_FileExistsWithSameNameAsDirectory.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateSymbolicLink_ThrowIOException_FileExistsWithSameNameAsDirectory.cs index f899ad805..b45820a62 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateSymbolicLink_ThrowIOException_FileExistsWithSameNameAsDirectory.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateSymbolicLink_ThrowIOException_FileExistsWithSameNameAsDirectory.cs @@ -49,7 +49,7 @@ private void AlphaFS_Directory_CreateSymbolicLink_ThrowIOException_FileExistsWit Console.WriteLine("Input File Path : [{0}]", fileInfo.FullName); Console.WriteLine("Input Directory Link: [{0}]", folderLink); - ExceptionAssert.IOException(() => Alphaleonis.Win32.Filesystem.Directory.CreateSymbolicLink(folderLink, fileInfo.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.CreateSymbolicLink(folderLink, fileInfo.FullName)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateSymbolicLink_ThrowIOException_DirectoryExistsWithSameNameAsFile.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateSymbolicLink_ThrowIOException_DirectoryExistsWithSameNameAsFile.cs index ba6dcf921..0dbc60126 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateSymbolicLink_ThrowIOException_DirectoryExistsWithSameNameAsFile.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_File.CreateSymbolicLink_ThrowIOException_DirectoryExistsWithSameNameAsFile.cs @@ -50,7 +50,7 @@ private void AlphaFS_File_File_CreateSymbolicLink_ThrowIOException_DirectoryExis Console.WriteLine("Input Directory Link: [{0}]", folderLink); - ExceptionAssert.IOException(() => Alphaleonis.Win32.Filesystem.File.CreateSymbolicLink(folderLink, dirInfo.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.CreateSymbolicLink(folderLink, dirInfo.FullName)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 9412f4534..e6ee8b775 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -158,7 +158,6 @@ - diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_Overwrite_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_Overwrite_DestinationFileAlreadyExists.cs index 93f690b23..20035c0b7 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_Overwrite_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_Overwrite_DestinationFileAlreadyExists.cs @@ -61,7 +61,7 @@ private void AlphaFS_Directory_Copy_Overwrite_DestinationFileAlreadyExists(bool Console.WriteLine("\n\tTotal size: [{0}] - Total Folders: [{1}] - Files: [{2}]", Alphaleonis.Utils.UnitSizeToText(sourceTotalSize), sourceTotal - sourceTotalFiles, sourceTotalFiles); - ExceptionAssert.AlreadyExistsException(() => Alphaleonis.Win32.Filesystem.Directory.Copy(folderSrc.FullName, folderDst)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Copy(folderSrc.FullName, folderDst)); Assert.IsTrue(System.IO.Directory.Exists(folderDst), "The directory does not exist, but is expected to."); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs index 0d2fa58c4..992d2fdeb 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs @@ -53,7 +53,7 @@ private void AlphaFS_Directory_Copy_ThrowAlreadyExistsException_DestinationFileA action(); // 2nd Copy action. - ExceptionAssert.AlreadyExistsException(() => action()); + UnitTestAssert.ThrowsException(() => action()); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs index 171ddb254..5882324dc 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs @@ -56,7 +56,7 @@ private void AlphaFS_Directory_Copy_ThrowDeviceNotReadyException_NonExistingDest Console.WriteLine("Dst Directory Path: [{0}]", dstFolder); - ExceptionAssert.DeviceNotReadyException(() => Alphaleonis.Win32.Filesystem.Directory.Copy(srcFolder, dstFolder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Copy(srcFolder, dstFolder)); Assert.IsFalse(System.IO.Directory.Exists(dstFolder), "The directory exists, but is expected not to."); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs index bcdee44b9..ba50ff33b 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs @@ -56,7 +56,7 @@ private void AlphaFS_Directory_Copy_ThrowDeviceNotReadyException_NonExistingSour Console.WriteLine("Dst Directory Path: [{0}]", dstFolder); - ExceptionAssert.DeviceNotReadyException(() => Alphaleonis.Win32.Filesystem.Directory.Copy(srcFolder, dstFolder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Copy(srcFolder, dstFolder)); Assert.IsFalse(System.IO.Directory.Exists(dstFolder), "The directory exists, but is expected not to."); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs index 6b75e0fb6..ab6a3ef16 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs @@ -54,7 +54,7 @@ private void AlphaFS_Directory_Copy_ThrowDirectoryNotFoundException_NonExistingS Console.WriteLine("Dst Directory Path: [{0}]", dstFolder); - ExceptionAssert.DirectoryNotFoundException(() => Alphaleonis.Win32.Filesystem.Directory.Copy(srcFolder, dstFolder), srcFolder); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Copy(srcFolder, dstFolder), srcFolder); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs index dfd980bd0..7dd930c2e 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs @@ -66,7 +66,7 @@ private void AlphaFS_Directory_Copy_ThrowUnauthorizedAccessException_UserExplici try { - ExceptionAssert.UnauthorizedAccessException(() => Alphaleonis.Win32.Filesystem.Directory.Copy(srcFolder.FullName, dstFolder.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Copy(srcFolder.FullName, dstFolder.FullName)); } finally { diff --git a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowAlreadyExistsException_FileExistsWithSameNameAsDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowAlreadyExistsException_FileExistsWithSameNameAsDirectory.cs index 79f2aea43..5318f6ac9 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowAlreadyExistsException_FileExistsWithSameNameAsDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowAlreadyExistsException_FileExistsWithSameNameAsDirectory.cs @@ -45,9 +45,9 @@ private void Directory_CreateDirectory_ThrowAlreadyExistsException_FileExistsWit Console.WriteLine("Input File Path: [{0}]", file.FullName); - ExceptionAssert.IOException(() => System.IO.Directory.CreateDirectory(file.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.CreateDirectory(file.FullName)); - ExceptionAssert.AlreadyExistsException(() => Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(file.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(file.FullName)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowDeviceNotReadyException_NonExistingDriveLetter.cs b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowDeviceNotReadyException_NonExistingDriveLetter.cs index 2359fd601..a40867482 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowDeviceNotReadyException_NonExistingDriveLetter.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowDeviceNotReadyException_NonExistingDriveLetter.cs @@ -47,9 +47,9 @@ private void Directory_CreateDirectory_ThrowIOExceptionOrDeviceNotReadyException Console.WriteLine("Input Directory Path: [{0}]", folder); - ExceptionAssert.IOException(() => System.IO.Directory.CreateDirectory(folder)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.CreateDirectory(folder)); - ExceptionAssert.IOException(() => Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(folder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(folder)); // Local: IOException. // UNC: IOException or DeviceNotReadyException. diff --git a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowDirectoryNotFoundException_NonExistingDriveLetter.cs b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowDirectoryNotFoundException_NonExistingDriveLetter.cs index 9b79786be..fd284875e 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowDirectoryNotFoundException_NonExistingDriveLetter.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.CreateDirectory/Directory.CreateDirectory_ThrowDirectoryNotFoundException_NonExistingDriveLetter.cs @@ -46,9 +46,9 @@ private void Directory_CreateDirectory_ThrowDirectoryNotFoundException_NonExisti Console.WriteLine("Input Directory Path: [{0}]", folder); - ExceptionAssert.DirectoryNotFoundException(() => System.IO.Directory.CreateDirectory(folder)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.CreateDirectory(folder)); - ExceptionAssert.DirectoryNotFoundException(() => Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(folder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(folder)); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDeviceNotReadyException_NonExistingLogicalDrive.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDeviceNotReadyException_NonExistingLogicalDrive.cs index 97bad9a62..1e05bd65f 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDeviceNotReadyException_NonExistingLogicalDrive.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDeviceNotReadyException_NonExistingLogicalDrive.cs @@ -52,16 +52,16 @@ private void AlphaFS_Directory_Delete_ThrowDeviceNotReadyException_NonExistingLo if (isNetwork) { - ExceptionAssert.IOException(() => System.IO.Directory.Delete(folder)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.Delete(folder)); - ExceptionAssert.DeviceNotReadyException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder)); } else { - ExceptionAssert.DirectoryNotFoundException(() => System.IO.Directory.Delete(folder)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.Delete(folder)); - ExceptionAssert.DeviceNotReadyException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryNotEmptyException_NonEmptyDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryNotEmptyException_NonEmptyDirectory.cs index a97d73dbb..477f06320 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryNotEmptyException_NonEmptyDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryNotEmptyException_NonEmptyDirectory.cs @@ -50,9 +50,9 @@ private void AlphaFS_Directory_Delete_ThrowDirectoryNotEmptyException_NonEmptyDi using (System.IO.File.Create(System.IO.Path.Combine(folder.FullName, file))) { } - ExceptionAssert.IOException(() => System.IO.Directory.Delete(folder.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.Delete(folder.FullName)); - ExceptionAssert.DirectoryNotEmptyException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder.FullName)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryReadOnlyException_DirectoryIsReadOnly.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryReadOnlyException_DirectoryIsReadOnly.cs index 6d30504b9..f50994e83 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryReadOnlyException_DirectoryIsReadOnly.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/AlphaFS_Directory.Delete_ThrowDirectoryReadOnlyException_DirectoryIsReadOnly.cs @@ -47,9 +47,9 @@ private void AlphaFS_Directory_Delete_ThrowDirectoryReadOnlyException_DirectoryI System.IO.File.SetAttributes(folder.FullName, System.IO.FileAttributes.ReadOnly); - ExceptionAssert.IOException(() => System.IO.Directory.Delete(folder.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.Delete(folder.FullName)); - ExceptionAssert.DirectoryReadOnlyException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder.FullName)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs index 1781d74aa..de940687b 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_FileExistsWithSameNameAsDirectory.cs @@ -46,11 +46,11 @@ private void Directory_Delete_ThrowDirectoryNotFoundException_FileExistsWithSame Console.WriteLine("Input File Path: [{0}]", file.FullName); - ExceptionAssert.IOException(() => System.IO.Directory.Delete(file.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.Delete(file.FullName)); // 2018-05-29 BUG: Throws wrong Exception. - ExceptionAssert.DirectoryNotFoundException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(file.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(file.FullName)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_NonExistingDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_NonExistingDirectory.cs index f0a8bd47f..9d1e48b14 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_NonExistingDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete.ThrowDirectoryNotFoundException_NonExistingDirectory.cs @@ -45,9 +45,9 @@ private void Directory_Delete_ThrowDirectoryNotFoundException_NonExistingDirecto Console.WriteLine("Input Directory Path: [{0}]", folder); - ExceptionAssert.DirectoryNotFoundException(() => System.IO.Directory.Delete(folder)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.Delete(folder)); - ExceptionAssert.DirectoryNotFoundException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete_ThrowUnauthorizedAccessException_DirectoryHasDenyPermission.cs b/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete_ThrowUnauthorizedAccessException_DirectoryHasDenyPermission.cs index 718df778d..cae4609ee 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete_ThrowUnauthorizedAccessException_DirectoryHasDenyPermission.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Delete/Directory.Delete_ThrowUnauthorizedAccessException_DirectoryHasDenyPermission.cs @@ -50,11 +50,11 @@ private void Directory_Delete_ThrowUnauthorizedAccessException_DirectoryHasDenyP try { - ExceptionAssert.IOException(() => System.IO.Directory.Delete(folder.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.Delete(folder.FullName)); // 2018-05-29 BUG: Throws wrong Exception. - ExceptionAssert.UnauthorizedAccessException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Delete(folder.FullName)); } finally { diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowAlreadyExistsException_DestinationDirectoryAlreadyExists.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowAlreadyExistsException_DestinationDirectoryAlreadyExists.cs index 47374d95f..d9870d3e4 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowAlreadyExistsException_DestinationDirectoryAlreadyExists.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowAlreadyExistsException_DestinationDirectoryAlreadyExists.cs @@ -47,9 +47,9 @@ private void AlphaFS_Directory_Move_ThrowAlreadyExistsException_DestinationDirec Console.WriteLine("Src Directory Path: [{0}]", srcFolder.FullName); Console.WriteLine("Dst Directory Path: [{0}]", dstFfolder.FullName); - ExceptionAssert.IOException(() => System.IO.Directory.Move(srcFolder.FullName, dstFfolder.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.Move(srcFolder.FullName, dstFfolder.FullName)); - ExceptionAssert.AlreadyExistsException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder.FullName, dstFfolder.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder.FullName, dstFfolder.FullName)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs index 8fef16742..37c0f53b4 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs @@ -56,7 +56,7 @@ private void AlphaFS_Directory_Move_ThrowDeviceNotReadyException_NonExistingDest Console.WriteLine("Dst Directory Path: [{0}]", dstFolder); - ExceptionAssert.DeviceNotReadyException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder, dstFolder, Alphaleonis.Win32.Filesystem.MoveOptions.CopyAllowed)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder, dstFolder, Alphaleonis.Win32.Filesystem.MoveOptions.CopyAllowed)); Assert.IsFalse(System.IO.Directory.Exists(dstFolder), "The directory exists, but is expected not to."); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs index fa2c1deb0..a0a0f8919 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs @@ -56,7 +56,7 @@ private void AlphaFS_Directory_Move_ThrowDeviceNotReadyException_NonExistingSour Console.WriteLine("Dst Directory Path: [{0}]", dstFolder); - ExceptionAssert.DeviceNotReadyException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder, dstFolder, Alphaleonis.Win32.Filesystem.MoveOptions.CopyAllowed)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder, dstFolder, Alphaleonis.Win32.Filesystem.MoveOptions.CopyAllowed)); Assert.IsFalse(System.IO.Directory.Exists(dstFolder), "The directory exists, but is expected not to."); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs index 9c5995f07..21d4b3357 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs @@ -54,9 +54,9 @@ private void Directory_Move_ThrowDirectoryNotFoundException_NonExistingSourceDir Console.WriteLine("Dst Directory Path: [{0}]", dstFolder); - ExceptionAssert.DirectoryNotFoundException(() => System.IO.Directory.Move(srcFolder, dstFolder), srcFolder); + UnitTestAssert.ThrowsException(() => System.IO.Directory.Move(srcFolder, dstFolder), srcFolder); - ExceptionAssert.DirectoryNotFoundException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder, dstFolder), srcFolder); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder, dstFolder), srcFolder); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowIOException_SameSourceAndDestination.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowIOException_SameSourceAndDestination.cs index 3750034bb..e81be0a7c 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowIOException_SameSourceAndDestination.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowIOException_SameSourceAndDestination.cs @@ -48,9 +48,9 @@ private void Directory_Move_ThrowIOException_SameSourceAndDestination(bool isNet Console.WriteLine("Dst Directory Path: [{0}]", dstFolder.FullName); - ExceptionAssert.IOException(() => System.IO.Directory.Move(srcFolder.FullName, dstFolder.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.Directory.Move(srcFolder.FullName, dstFolder.FullName)); - ExceptionAssert.IOException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder.FullName, dstFolder.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder.FullName, dstFolder.FullName)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs index 23a89dfb2..6e2e6cd80 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/Directory.Move_ThrowUnauthorizedAccessException_UserExplicitDenyOnDestinationFolder.cs @@ -66,7 +66,7 @@ private void Directory_Move_ThrowUnauthorizedAccessException_UserExplicitDenyOnD try { - ExceptionAssert.UnauthorizedAccessException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder.FullName, dstFolder.FullName, Alphaleonis.Win32.Filesystem.MoveOptions.ReplaceExisting)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Directory.Move(srcFolder.FullName, dstFolder.FullName, Alphaleonis.Win32.Filesystem.MoveOptions.ReplaceExisting)); } finally { diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/AlphaFS_DirectoryInfo.MoveTo_DelayUntilReboot.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/AlphaFS_DirectoryInfo.MoveTo_DelayUntilReboot.cs index 133a9be82..ba9d8e6ac 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/AlphaFS_DirectoryInfo.MoveTo_DelayUntilReboot.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.MoveTo/AlphaFS_DirectoryInfo.MoveTo_DelayUntilReboot.cs @@ -52,7 +52,7 @@ private void AlphaFS_DirectoryInfo_MoveTo_DelayUntilReboot(bool isNetwork) if (isNetwork) // Trigger DelayUntilReboot. - ExceptionAssert.ArgumentException(() => folder.MoveTo(null, Alphaleonis.Win32.Filesystem.MoveOptions.DelayUntilReboot)); + UnitTestAssert.ThrowsException(() => folder.MoveTo(null, Alphaleonis.Win32.Filesystem.MoveOptions.DelayUntilReboot)); else { diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.ThrowPathTooLongException_FolderNameGreaterThan255Characters.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.ThrowPathTooLongException_FolderNameGreaterThan255Characters.cs index 9e839dd13..4d528de4d 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.ThrowPathTooLongException_FolderNameGreaterThan255Characters.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.ThrowPathTooLongException_FolderNameGreaterThan255Characters.cs @@ -57,9 +57,9 @@ private void DirectoryInfo_ThrowPathTooLongException_FolderNameGreaterThan255Cha Console.WriteLine(); - ExceptionAssert.PathTooLongException(() => new System.IO.DirectoryInfo(isNetwork ? unc : local)); + UnitTestAssert.ThrowsException(() => new System.IO.DirectoryInfo(isNetwork ? unc : local)); - ExceptionAssert.PathTooLongException(() => new Alphaleonis.Win32.Filesystem.DirectoryInfo(isNetwork ? unc : local)); + UnitTestAssert.ThrowsException(() => new Alphaleonis.Win32.Filesystem.DirectoryInfo(isNetwork ? unc : local)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_Overwrite_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_Overwrite_DestinationFileAlreadyExists.cs index 103dce73e..53ca18104 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_Overwrite_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_Overwrite_DestinationFileAlreadyExists.cs @@ -27,9 +27,9 @@ private void AlphaFS_File_Copy_Overwrite_DestinationFileAlreadyExists(bool isNet Console.WriteLine("Dst File Path: [{0}]", dstFile.FullName); - ExceptionAssert.IOException(() => System.IO.File.Copy(srcFile.FullName, dstFile.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.File.Copy(srcFile.FullName, dstFile.FullName)); - ExceptionAssert.AlreadyExistsException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFile.FullName, dstFile.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFile.FullName, dstFile.FullName)); Alphaleonis.Win32.Filesystem.File.Copy(srcFile.FullName, dstFile.FullName, true); diff --git a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs index 09ddbb3e7..43809b186 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs @@ -47,9 +47,9 @@ private void AlphaFS_File_Copy_ThrowAlreadyExistsException_DestinationFileAlread Console.WriteLine("Src File Path: [{0}]", srcFile); Console.WriteLine("Dst File Path: [{0}]", dstFile); - ExceptionAssert.IOException(() => System.IO.File.Copy(srcFile.FullName, dstFile.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.File.Copy(srcFile.FullName, dstFile.FullName)); - ExceptionAssert.AlreadyExistsException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFile.FullName, dstFile.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFile.FullName, dstFile.FullName)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs index 48808db1f..50b795b4d 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs @@ -56,9 +56,9 @@ private void AlphaFS_File_Copy_ThrowDeviceNotReadyException_NonExistingDestinati Console.WriteLine("Dst File Path: [{0}]", dstFolder); - ExceptionAssert.FileNotFoundException(() => System.IO.File.Copy(srcFolder, dstFolder)); + UnitTestAssert.ThrowsException(() => System.IO.File.Copy(srcFolder, dstFolder)); - ExceptionAssert.DeviceNotReadyException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFolder, dstFolder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFolder, dstFolder)); Assert.IsFalse(System.IO.Directory.Exists(dstFolder), "The file exists, but is expected not to."); diff --git a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs index 7201f584d..d176a218b 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs @@ -58,16 +58,16 @@ private void AlphaFS_File_Copy_ThrowDeviceNotReadyException_NonExistingSourceLog if (isNetwork) { - ExceptionAssert.IOException(() => System.IO.File.Copy(srcFolder, dstFolder)); + UnitTestAssert.ThrowsException(() => System.IO.File.Copy(srcFolder, dstFolder)); - ExceptionAssert.DeviceNotReadyException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFolder, dstFolder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFolder, dstFolder)); } else { - ExceptionAssert.DirectoryNotFoundException(() => System.IO.File.Copy(srcFolder, dstFolder)); + UnitTestAssert.ThrowsException(() => System.IO.File.Copy(srcFolder, dstFolder)); - ExceptionAssert.DeviceNotReadyException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFolder, dstFolder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFolder, dstFolder)); } Assert.IsFalse(System.IO.Directory.Exists(dstFolder), "The file exists, but is expected not to."); diff --git a/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs b/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs index a6a06a6f5..51e99b083 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs @@ -54,9 +54,9 @@ private void File_Copy_ThrowDirectoryNotFoundException_NonExistingSourceDirector Console.WriteLine("Dst File Path: [{0}]", dstFolder); - ExceptionAssert.DirectoryNotFoundException(() => System.IO.File.Copy(srcFolder, dstFolder), srcFolder); + UnitTestAssert.ThrowsException(() => System.IO.File.Copy(srcFolder, dstFolder), srcFolder); - ExceptionAssert.DirectoryNotFoundException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFolder, dstFolder), srcFolder); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFolder, dstFolder), srcFolder); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowFileNotFoundException_NonExistingSourceFile.cs b/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowFileNotFoundException_NonExistingSourceFile.cs index 26dc0d355..2e1d1d608 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowFileNotFoundException_NonExistingSourceFile.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowFileNotFoundException_NonExistingSourceFile.cs @@ -48,9 +48,9 @@ private void File_Copy_ThrowFileNotFoundException_NonExistingSourceFile(bool isN Console.WriteLine("Dst File Path: [{0}]", dstFile); - ExceptionAssert.FileNotFoundException(() => System.IO.File.Copy(srcFile, dstFile)); + UnitTestAssert.ThrowsException(() => System.IO.File.Copy(srcFile, dstFile)); - ExceptionAssert.FileNotFoundException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFile, dstFile)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFile, dstFile)); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowUnauthorizedAccessException_DestinationFileIsReadOnly.cs b/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowUnauthorizedAccessException_DestinationFileIsReadOnly.cs index 789c68a5d..c3067538e 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowUnauthorizedAccessException_DestinationFileIsReadOnly.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/File.Copy_ThrowUnauthorizedAccessException_DestinationFileIsReadOnly.cs @@ -54,9 +54,9 @@ private void File_Copy_ThrowUnauthorizedAccessException_DestinationFileIsReadOnl try { - ExceptionAssert.UnauthorizedAccessException(() => System.IO.File.Copy(srcFile.FullName, dstFile, true)); + UnitTestAssert.ThrowsException(() => System.IO.File.Copy(srcFile.FullName, dstFile, true)); - ExceptionAssert.UnauthorizedAccessException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFile.FullName, dstFile, true)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Copy(srcFile.FullName, dstFile, true)); } finally { diff --git a/AlphaFS.UnitTest/File Class/File.Delete/AlphaFS_File.Delete_ThrowFileReadOnlyException_ReadOnlyFile.cs b/AlphaFS.UnitTest/File Class/File.Delete/AlphaFS_File.Delete_ThrowFileReadOnlyException_ReadOnlyFile.cs index cdb817693..1753137c7 100644 --- a/AlphaFS.UnitTest/File Class/File.Delete/AlphaFS_File.Delete_ThrowFileReadOnlyException_ReadOnlyFile.cs +++ b/AlphaFS.UnitTest/File Class/File.Delete/AlphaFS_File.Delete_ThrowFileReadOnlyException_ReadOnlyFile.cs @@ -47,9 +47,9 @@ private void AlphaFS_File_Delete_ThrowFileReadOnlyException_ReadOnlyFile(bool is System.IO.File.SetAttributes(file.FullName, System.IO.FileAttributes.ReadOnly); - ExceptionAssert.UnauthorizedAccessException(() => System.IO.File.Delete(file.FullName)); - - ExceptionAssert.FileReadOnlyException(() => Alphaleonis.Win32.Filesystem.File.Delete(file.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.File.Delete(file.FullName)); + + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Delete(file.FullName)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowDirectoryNotFoundException_NonExistingDriveLetter.cs b/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowDirectoryNotFoundException_NonExistingDriveLetter.cs index 933db1e9c..665bf08cb 100644 --- a/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowDirectoryNotFoundException_NonExistingDriveLetter.cs +++ b/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowDirectoryNotFoundException_NonExistingDriveLetter.cs @@ -46,9 +46,9 @@ private void File_Delete_ThrowDirectoryNotFoundException_NonExistingDriveLetter( Console.WriteLine("Input File Path: [{0}]", folder); - ExceptionAssert.DirectoryNotFoundException(() => System.IO.File.Delete(folder)); + UnitTestAssert.ThrowsException(() => System.IO.File.Delete(folder)); - ExceptionAssert.DirectoryNotFoundException(() => Alphaleonis.Win32.Filesystem.File.Delete(folder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Delete(folder)); } } } diff --git a/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowIOExceptionOrDeviceNotReadyException_NonExistingDriveLetter.cs b/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowIOExceptionOrDeviceNotReadyException_NonExistingDriveLetter.cs index fe7afcef0..113785d22 100644 --- a/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowIOExceptionOrDeviceNotReadyException_NonExistingDriveLetter.cs +++ b/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowIOExceptionOrDeviceNotReadyException_NonExistingDriveLetter.cs @@ -46,9 +46,9 @@ private void File_Delete_ThrowIOExceptionOrDeviceNotReadyException_NonExistingDr Console.WriteLine("Input File Path: [{0}]", folder); - ExceptionAssert.IOException(() => System.IO.File.Delete(folder)); + UnitTestAssert.ThrowsException(() => System.IO.File.Delete(folder)); - ExceptionAssert.IOException(() => Alphaleonis.Win32.Filesystem.File.Delete(folder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Delete(folder)); // Local: IOException. // UNC: IOException or DeviceNotReadyException. diff --git a/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowUnauthorizedAccessException_PathIsADirectoryNotAFile.cs b/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowUnauthorizedAccessException_PathIsADirectoryNotAFile.cs index 8da63d37d..688c3271b 100644 --- a/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowUnauthorizedAccessException_PathIsADirectoryNotAFile.cs +++ b/AlphaFS.UnitTest/File Class/File.Delete/File.Delete_ThrowUnauthorizedAccessException_PathIsADirectoryNotAFile.cs @@ -45,9 +45,9 @@ private void File_Delete_ThrowUnauthorizedAccessException_PathIsADirectoryNotAFi Console.WriteLine("Input Directory Path: [{0}]", folder.FullName); - ExceptionAssert.UnauthorizedAccessException(() => System.IO.File.Delete(folder.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.File.Delete(folder.FullName)); - ExceptionAssert.UnauthorizedAccessException(() => Alphaleonis.Win32.Filesystem.File.Delete(folder.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Delete(folder.FullName)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_Overwrite_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_Overwrite_DestinationFileAlreadyExists.cs index 4bf3e4a14..f68c4e5bc 100644 --- a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_Overwrite_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_Overwrite_DestinationFileAlreadyExists.cs @@ -47,9 +47,9 @@ private void AlphaFS_File_Move_Overwrite_DestinationFileAlreadyExists(bool isNet Console.WriteLine("Source File Path: [{0}]", fileSource.FullName); - ExceptionAssert.IOException(() => System.IO.File.Move(fileSource.FullName, fileCopy.FullName)); + UnitTestAssert.ThrowsException(() => System.IO.File.Move(fileSource.FullName, fileCopy.FullName)); - ExceptionAssert.AlreadyExistsException(() => Alphaleonis.Win32.Filesystem.File.Move(fileSource.FullName, fileCopy.FullName)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Move(fileSource.FullName, fileCopy.FullName)); Alphaleonis.Win32.Filesystem.File.Move(fileSource.FullName, fileCopy.FullName, Alphaleonis.Win32.Filesystem.MoveOptions.ReplaceExisting); diff --git a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs index e6aeb44f6..7c7a55b1e 100644 --- a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs +++ b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowAlreadyExistsException_DestinationFileAlreadyExists.cs @@ -50,9 +50,9 @@ private void AlphaFS_File_Move_ThrowAlreadyExistsException_DestinationFileAlread System.IO.File.Copy(srcFile.FullName, dstFile); - ExceptionAssert.IOException(() => System.IO.File.Move(srcFile.FullName, dstFile)); + UnitTestAssert.ThrowsException(() => System.IO.File.Move(srcFile.FullName, dstFile)); - ExceptionAssert.AlreadyExistsException(() => Alphaleonis.Win32.Filesystem.File.Move(srcFile.FullName, dstFile)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Move(srcFile.FullName, dstFile)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs index 25693b1bb..e4bbc4a83 100644 --- a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs +++ b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowDeviceNotReadyException_NonExistingDestinationLogicalDrive.cs @@ -56,9 +56,9 @@ private void AlphaFS_File_Move_ThrowDeviceNotReadyException_NonExistingDestinati Console.WriteLine("Dst File Path: [{0}]", dstFile); - ExceptionAssert.FileNotFoundException(() => System.IO.File.Move(srcFile, dstFile)); + UnitTestAssert.ThrowsException(() => System.IO.File.Move(srcFile, dstFile)); - ExceptionAssert.DeviceNotReadyException(() => Alphaleonis.Win32.Filesystem.File.Move(srcFile, dstFile)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Move(srcFile, dstFile)); Assert.IsFalse(System.IO.Directory.Exists(dstFile), "The file exists, but is expected not to."); diff --git a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs index c68a8081d..0ec0e84a4 100644 --- a/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs +++ b/AlphaFS.UnitTest/File Class/File.Move/AlphaFS_File.Move_ThrowDeviceNotReadyException_NonExistingSourceLogicalDrive.cs @@ -56,9 +56,9 @@ private void AlphaFS_File_Move_ThrowDeviceNotReadyException_NonExistingSourceLog Console.WriteLine("Dst File Path: [{0}]", dstFolder); - ExceptionAssert.FileNotFoundException(() => System.IO.File.Move(srcFolder, dstFolder)); + UnitTestAssert.ThrowsException(() => System.IO.File.Move(srcFolder, dstFolder)); - ExceptionAssert.DeviceNotReadyException(() => Alphaleonis.Win32.Filesystem.File.Move(srcFolder, dstFolder)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Move(srcFolder, dstFolder)); Assert.IsFalse(System.IO.Directory.Exists(dstFolder), "The file exists, but is expected not to."); diff --git a/AlphaFS.UnitTest/File Class/File.Move/File.Move_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs b/AlphaFS.UnitTest/File Class/File.Move/File.Move_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs index d7d3c3c3c..73eaaf6cd 100644 --- a/AlphaFS.UnitTest/File Class/File.Move/File.Move_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs +++ b/AlphaFS.UnitTest/File Class/File.Move/File.Move_ThrowDirectoryNotFoundException_NonExistingSourceDirectory.cs @@ -54,11 +54,11 @@ private void File_Move_ThrowDirectoryNotFoundException_NonExistingSourceDirector Console.WriteLine("Dst File Path: [{0}]", dstFolder); - ExceptionAssert.FileNotFoundException(() => System.IO.File.Move(srcFolder, dstFolder), srcFolder); + UnitTestAssert.ThrowsException(() => System.IO.File.Move(srcFolder, dstFolder), srcFolder); // 2018-05-29 BUG: Throws wrong Exception. - ExceptionAssert.DirectoryNotFoundException(() => Alphaleonis.Win32.Filesystem.File.Move(srcFolder, dstFolder), srcFolder); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Move(srcFolder, dstFolder), srcFolder); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/File Class/File.Move/File.Move_ThrowFileNotFoundException_NonExistingSourceFile.cs b/AlphaFS.UnitTest/File Class/File.Move/File.Move_ThrowFileNotFoundException_NonExistingSourceFile.cs index bb8dea451..393a93570 100644 --- a/AlphaFS.UnitTest/File Class/File.Move/File.Move_ThrowFileNotFoundException_NonExistingSourceFile.cs +++ b/AlphaFS.UnitTest/File Class/File.Move/File.Move_ThrowFileNotFoundException_NonExistingSourceFile.cs @@ -48,9 +48,9 @@ private void File_Move_ThrowFileNotFoundException_NonExistingSourceFile(bool isN Console.WriteLine("Dst File Path: [{0}]", dstFile); - ExceptionAssert.FileNotFoundException(() => System.IO.File.Move(srcFile, dstFile)); + UnitTestAssert.ThrowsException(() => System.IO.File.Move(srcFile, dstFile)); - ExceptionAssert.FileNotFoundException(() => Alphaleonis.Win32.Filesystem.File.Move(srcFile, dstFile)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.File.Move(srcFile, dstFile)); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowArgumentException_InvalidLocalPath1.cs b/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowArgumentException_InvalidLocalPath1.cs index 660cb1884..8e6f263f1 100644 --- a/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowArgumentException_InvalidLocalPath1.cs +++ b/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowArgumentException_InvalidLocalPath1.cs @@ -34,9 +34,9 @@ public void Path_GetFullPath_ThrowArgumentException_InvalidLocalPath1_Success() { UnitTestConstants.PrintUnitTestHeader(false); - ExceptionAssert.ArgumentException(() => System.IO.Path.GetFullPath(UnitTestConstants.SysDrive + @"\?test.txt")); + UnitTestAssert.ThrowsException(() => System.IO.Path.GetFullPath(UnitTestConstants.SysDrive + @"\?test.txt")); - ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Path.GetFullPath(UnitTestConstants.SysDrive + @"\?test.txt")); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Path.GetFullPath(UnitTestConstants.SysDrive + @"\?test.txt")); // @"\*test.txt"); // @"\\test.txt"); diff --git a/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowArgumentException_InvalidLocalPath2.cs b/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowArgumentException_InvalidLocalPath2.cs index 6e3797eff..59a16e49d 100644 --- a/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowArgumentException_InvalidLocalPath2.cs +++ b/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowArgumentException_InvalidLocalPath2.cs @@ -34,9 +34,9 @@ public void Path_GetFullPath_ThrowArgumentException_InvalidLocalPath2_Success() { UnitTestConstants.PrintUnitTestHeader(false); - ExceptionAssert.ArgumentException(() => System.IO.Path.GetFullPath(@"\\\\.txt")); + UnitTestAssert.ThrowsException(() => System.IO.Path.GetFullPath(@"\\\\.txt")); - ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Path.GetFullPath(@"\\\\.txt")); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Path.GetFullPath(@"\\\\.txt")); } } } diff --git a/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowNotSupportedException.cs b/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowNotSupportedException.cs index 6cbe4901e..92444ccdf 100644 --- a/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowNotSupportedException.cs +++ b/AlphaFS.UnitTest/Path Class/Path.GetFullPath/Path.GetFullPath_ThrowNotSupportedException.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -33,9 +34,9 @@ public void Path_GetFullPath_ThrowNotSupportedException_Success() { UnitTestConstants.PrintUnitTestHeader(false); - ExceptionAssert.NotSupportedException(() => System.IO.Path.GetFullPath(UnitTestConstants.SysDrive + @"\dev\test\aaa:aaa.txt")); + UnitTestAssert.ThrowsException(() => System.IO.Path.GetFullPath(UnitTestConstants.SysDrive + @"\dev\test\aaa:aaa.txt")); - ExceptionAssert.NotSupportedException(() => Alphaleonis.Win32.Filesystem.Path.GetFullPath(UnitTestConstants.SysDrive + @"\dev\test\aaa:aaa.txt")); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Path.GetFullPath(UnitTestConstants.SysDrive + @"\dev\test\aaa:aaa.txt")); } } } diff --git a/AlphaFS.UnitTest/Path Class/Path.GetPathRoot/Path.GetPathRoot_ThrowArgumentExceptionEmptyString.cs b/AlphaFS.UnitTest/Path Class/Path.GetPathRoot/Path.GetPathRoot_ThrowArgumentExceptionEmptyString.cs index 578fa7361..6271675b3 100644 --- a/AlphaFS.UnitTest/Path Class/Path.GetPathRoot/Path.GetPathRoot_ThrowArgumentExceptionEmptyString.cs +++ b/AlphaFS.UnitTest/Path Class/Path.GetPathRoot/Path.GetPathRoot_ThrowArgumentExceptionEmptyString.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -33,9 +34,9 @@ public void Path_GetPathRoot_ThrowArgumentExceptionEmptyString_Success() { UnitTestConstants.PrintUnitTestHeader(false); - ExceptionAssert.ArgumentException(() => System.IO.Path.GetPathRoot(string.Empty)); - - ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Path.GetPathRoot(string.Empty)); + UnitTestAssert.ThrowsException(() => System.IO.Path.GetPathRoot(string.Empty)); + + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Path.GetPathRoot(string.Empty)); } } } diff --git a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathContainsInvalidCharacters.cs b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathContainsInvalidCharacters.cs index 0e2e7fd82..648b5885a 100644 --- a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathContainsInvalidCharacters.cs +++ b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathContainsInvalidCharacters.cs @@ -38,7 +38,7 @@ public void AlphaFS_Path_CheckSupportedPathFormat_ThrowArgumentException_PathCon Console.WriteLine("Input Path: [{0}]", folder); - ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Path.CheckSupportedPathFormat(folder, true, true)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Path.CheckSupportedPathFormat(folder, true, true)); } } } diff --git a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathStartsWithColon.cs b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathStartsWithColon.cs index fabfe6a8d..e11568531 100644 --- a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathStartsWithColon.cs +++ b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowArgumentException_PathStartsWithColon.cs @@ -44,7 +44,7 @@ private void Path_CheckSupportedPathFormat_ThrowArgumentException_PathStartsWith Console.WriteLine("Input Path: [{0}]", invalidPath); - ExceptionAssert.ArgumentException(() => Alphaleonis.Win32.Filesystem.Path.CheckSupportedPathFormat(invalidPath, true, true)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Path.CheckSupportedPathFormat(invalidPath, true, true)); } } } diff --git a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowNotSupportedException_PathContainsColon.cs b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowNotSupportedException_PathContainsColon.cs index bfc38c0da..a21f00606 100644 --- a/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowNotSupportedException_PathContainsColon.cs +++ b/AlphaFS.UnitTest/Path Class/Path_CheckSupportedPathFormat/Path.CheckSupportedPathFormat_ThrowNotSupportedException_PathContainsColon.cs @@ -45,7 +45,7 @@ private void Path_CheckSupportedPathFormat_ThrowNotSupportedException_PathContai Console.WriteLine("Input Path: [{0}]", folder); - ExceptionAssert.NotSupportedException(() => Alphaleonis.Win32.Filesystem.Path.CheckSupportedPathFormat(folder, true, true)); + UnitTestAssert.ThrowsException(() => Alphaleonis.Win32.Filesystem.Path.CheckSupportedPathFormat(folder, true, true)); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/UnitTest Utility/ExceptionAssert.cs b/AlphaFS.UnitTest/UnitTest Utility/ExceptionAssert.cs deleted file mode 100644 index 4efceab70..000000000 --- a/AlphaFS.UnitTest/UnitTest Utility/ExceptionAssert.cs +++ /dev/null @@ -1,135 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 ExceptionAssert - { - public static void AlreadyExistsException(Action action, string findString = null) - { - TestException(action, typeof(Alphaleonis.Win32.Filesystem.AlreadyExistsException), findString); - } - - - public static void ArgumentException(Action action, string findString = null) - { - TestException(action, typeof(ArgumentException), findString); - } - - - public static void DeviceNotReadyException(Action action, string findString = null) - { - TestException(action, typeof(Alphaleonis.Win32.Filesystem.DeviceNotReadyException), findString); - } - - - public static void DirectoryNotEmptyException(Action action, string findString = null) - { - TestException(action, typeof(Alphaleonis.Win32.Filesystem.DirectoryNotEmptyException), findString); - } - - - public static void DirectoryNotFoundException(Action action, string findString = null) - { - TestException(action, typeof(System.IO.DirectoryNotFoundException), findString); - } - - - public static void DirectoryReadOnlyException(Action action, string findString = null) - { - TestException(action, typeof(Alphaleonis.Win32.Filesystem.DirectoryReadOnlyException), findString); - } - - - public static void FileNotFoundException(Action action, string findString = null) - { - TestException(action, typeof(System.IO.FileNotFoundException), findString); - } - - - public static void FileReadOnlyException(Action action, string findString = null) - { - TestException(action, typeof(Alphaleonis.Win32.Filesystem.FileReadOnlyException), findString); - } - - - public static void IOException(Action action, string findString = null) - { - TestException(action, typeof(System.IO.IOException), findString); - } - - - public static void NotSupportedException(Action action, string findString = null) - { - TestException(action, typeof(NotSupportedException), findString); - } - - - public static void PathTooLongException(Action action, string findString = null) - { - TestException(action, typeof(System.IO.PathTooLongException), findString); - } - - - public static void UnauthorizedAccessException(Action action, string findString = null) - { - TestException(action, typeof(UnauthorizedAccessException), findString); - } - - - private static void TestException(Action action, Type expectedException, string findString = null) - { - Exception exception = null; - var message = string.Empty; - - 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."); - } - } -} diff --git a/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs b/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs index 9196a9986..1e62129eb 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs @@ -21,6 +21,7 @@ using System; using System.Globalization; +using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -33,7 +34,7 @@ public static void IsElevatedProcess() Inconclusive("This unit test must be run elevated."); } - + public static void Inconclusive(string errorMessage) { Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0}{1}{0}", Environment.NewLine, errorMessage)); @@ -54,5 +55,40 @@ public static void InconclusiveBecauseFileNotFound(string fullPath) { Inconclusive("The file system object was not found: " + fullPath); } + + + public static void ThrowsException(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."); + } } } From 335887f3e24d89354394b444dc84f2469ccc8b8a Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 2 Jun 2018 00:30:24 +0200 Subject: [PATCH 079/133] Implemented #451: Add overloaded method for File.GetSize to retrieve the size of all streams. --- .../AlphaFS_Directory_Encrypt_And_Decrypt.cs | 2 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 4 +- ...Directory.EnumerateAlternateDataStreams.cs | 6 +- .../AlphaFS_File.GetSize_AllStreams.cs | 82 +++++++++ .../AlphaFS_File.GetSize_Stream0.cs} | 13 +- .../UnitTest Utility/TemporaryDirectory.cs | 16 +- .../UnitTest Utility/UnitTestAssert.cs | 2 +- .../UnitTest Utility/UnitTestConstants.cs | 2 +- AlphaFS/AlphaFS.csproj | 2 +- AlphaFS/Filesystem/File Class/File.Copy.cs | 2 +- .../File.EnumerateAlternateDataStreams.cs | 98 ++++++----- AlphaFS/Filesystem/File Class/File.GetSize.cs | 156 +++++++++++++++--- CHANGELOG.md | 3 +- 13 files changed, 304 insertions(+), 84 deletions(-) create mode 100644 AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize/AlphaFS_File.GetSize_AllStreams.cs rename AlphaFS.UnitTest/File Class/{AlphaFS_File.GetSize.cs => AlphaFS_File_GetSize/AlphaFS_File.GetSize_Stream0.cs} (80%) diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs index 2104e1ce2..65ed6e0a8 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs @@ -55,7 +55,7 @@ private void AlphaFS_Directory_EncryptDecrypt(bool isNetwork) foreach (var fsei in Alphaleonis.Win32.Filesystem.Directory.EnumerateFileSystemEntryInfos(folder.FullName, Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions.Recursive)) { cnt++; - Assert.IsTrue((fsei.Attributes & System.IO.FileAttributes.Encrypted) == 0, "It is expected that the file system object is decrypted, but it is not."); + Assert.IsTrue((fsei.Attributes & System.IO.FileAttributes.Encrypted) == 0, "It is expected that the file system object is encrypted, but it is not."); } if (cnt == 0) diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index fb67bd647..69a0b202d 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -145,10 +145,12 @@ + + @@ -431,7 +433,7 @@ - + diff --git a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateAlternateDataStreams.cs b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateAlternateDataStreams.cs index 7f296b592..54784869a 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateAlternateDataStreams.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory_Enumeration/AlphaFS_Directory.EnumerateAlternateDataStreams.cs @@ -64,12 +64,14 @@ private void AlphaFS_Directory_EnumerateAlternateDataStreams(bool isNetwork) 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. - var stream1Name = folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream; - var stream2Name = folder + Alphaleonis.Win32.Filesystem.Path.StreamSeparator + myStream2; 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); diff --git a/AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize/AlphaFS_File.GetSize_AllStreams.cs b/AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize/AlphaFS_File.GetSize_AllStreams.cs new file mode 100644 index 000000000..020acb6d3 --- /dev/null +++ b/AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize/AlphaFS_File.GetSize_AllStreams.cs @@ -0,0 +1,82 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 FileTest + { + // Pattern: ___ + + + [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}] [{1}]\n", Alphaleonis.Utils.UnitSizeToText(file.Length), file); + + + var totalStreams = new Random(DateTime.UtcNow.Millisecond).Next(0, 10); + var allStreamsSize = 0; + + for (var i = 0; i < totalStreams; i++) + { + var streamName = file + ":" + i.ToString() +"myStream"; + + // File size: min 0 bytes, max 10 (!) MB. + var streamText = new string('X', new Random(DateTime.UtcNow.Millisecond).Next(0, 10485760)); + + allStreamsSize += streamText.Length; + + Console.WriteLine("\tAdd stream: [{0}] [{1}]", Alphaleonis.Utils.UnitSizeToText(allStreamsSize), 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 totalFileSize = Alphaleonis.Win32.Filesystem.File.GetSize(file.FullName, true); + + Console.WriteLine("\nTotal File size + {0} streams: [{1}]", totalStreams, Alphaleonis.Utils.UnitSizeToText(totalFileSize)); + + Assert.AreEqual(file.Length + allStreamsSize, totalFileSize, "The file sizes do not match, but it is expected."); + } + + Console.WriteLine(); + } + } +} diff --git a/AlphaFS.UnitTest/File Class/AlphaFS_File.GetSize.cs b/AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize/AlphaFS_File.GetSize_Stream0.cs similarity index 80% rename from AlphaFS.UnitTest/File Class/AlphaFS_File.GetSize.cs rename to AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize/AlphaFS_File.GetSize_Stream0.cs index 1f84fe677..b0b955e1d 100644 --- a/AlphaFS.UnitTest/File Class/AlphaFS_File.GetSize.cs +++ b/AlphaFS.UnitTest/File Class/AlphaFS_File_GetSize/AlphaFS_File.GetSize_Stream0.cs @@ -30,24 +30,25 @@ partial class FileTest [TestMethod] - public void AlphaFS_File_GetSize_LocalAndNetwork_Success() + public void AlphaFS_File_GetSize_Stream0_LocalAndNetwork_Success() { - AlphaFS_File_GetSize(false); - AlphaFS_File_GetSize(true); + AlphaFS_File_GetSize_Stream0(false); + AlphaFS_File_GetSize_Stream0(true); } - private void AlphaFS_File_GetSize(bool isNetwork) + private void AlphaFS_File_GetSize_Stream0(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { var file = tempRoot.CreateFile(); - Console.WriteLine("Input File Path: [{0}]", file.FullName); + Console.WriteLine("Input File Path: [{0}]\n", file.FullName); var fileLength = Alphaleonis.Win32.Filesystem.File.GetSize(file.FullName); - Console.WriteLine("\n\tFile sizes: [{0}] vs [{1}]", file.Length, fileLength); + Console.WriteLine("\tSystem.IO File size: {0}", file.Length); + Console.WriteLine("\tAlphaFS File size: {0}", fileLength); Assert.AreEqual(file.Length, fileLength, "The file sizes do not match, but are expected to."); } diff --git a/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs index f79456aad..b7c006ab5 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs @@ -167,7 +167,7 @@ public System.IO.FileInfo CreateFile() } - /// Returns a instance to an existing file, possibly with read-only and/or hidden attributes set. + /// Returns a instance to an existing file, possibly with read-only and/or hidden attributes set. public System.IO.FileInfo CreateFileRandomizedAttributes() { return CreateFileCore(null, true, true); @@ -176,42 +176,42 @@ public System.IO.FileInfo CreateFileRandomizedAttributes() - /// Creates a directory structure of levels deep, populated with subdirectories and files with of random size. + /// Creates a directory structure of populated with subdirectories and files of random size. public System.IO.DirectoryInfo CreateTree(int level = 1) { return CreateTreeCore(null, level); } - /// Creates a recursive directory structure of levels deep, populated with subdirectories and files with of random size. + /// Creates a recursive directory structure of populated with subdirectories and files of random size. public System.IO.DirectoryInfo CreateRecursiveTree(int level = 1) { return CreateTreeCore(null, level, true); } - /// Creates a recursive directory structure of levels deep, populated with subdirectories and files with of random size. + /// Creates a recursive directory structure of populated with subdirectories and files of random size. public System.IO.DirectoryInfo CreateRecursiveTree(int level, string rootFullPath) { return CreateTreeCore(rootFullPath, level, true); } - /// Creates a directory structure of levels deep, populated with subdirectories and files with of random size. + /// Creates a directory structure of populated with subdirectories and files of random size and possibly with read-only and/or hidden attributes set. public System.IO.DirectoryInfo CreateRandomizedAttributesTree(int level = 1) { return CreateTreeCore(null, level, false, true, true); } - /// Creates a recursive directory structure of levels deep, populated with subdirectories and files with of random size. + /// Creates a recursive directory structure of populated with subdirectories and files of random size and possibly with read-only and/or hidden attributes set. public System.IO.DirectoryInfo CreateRecursiveRandomizedAttributesTree(int level = 1) { return CreateTreeCore(null, level, true, true, true); } - /// Creates an, optional recursive, directory structure of levels deep, populated with subdirectories and files with of random size and possibly with read-only and/or hidden attributes set. + /// Creates an, optional recursive, directory structure of levels deep, populated with subdirectories and files of random size and possibly with read-only and/or hidden attributes set. private System.IO.DirectoryInfo CreateTreeCore(string rootFullPath, int level = 1, bool recurse = false, bool readOnly = false, bool hidden = false) { var dirInfo = CreateDirectoryCore(rootFullPath, readOnly, hidden); @@ -313,7 +313,7 @@ private System.IO.FileInfo CreateFileCore(string fileFullPath, bool readOnly = f { var fileInfo = new System.IO.FileInfo(!Alphaleonis.Utils.IsNullOrWhiteSpace(fileFullPath) ? fileFullPath : RandomTxtFileFullPath); - // File size is min 0 bytes, level 1 MB. + // File size: min 0 bytes, max 1 MB. using (var fs = fileInfo.Create()) fs.SetLength(new Random(DateTime.UtcNow.Millisecond).Next(0, 1048576)); diff --git a/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs b/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs index 1e62129eb..090c56a5a 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs @@ -37,7 +37,7 @@ public static void IsElevatedProcess() public static void Inconclusive(string errorMessage) { - Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0}{1}{0}", Environment.NewLine, errorMessage)); + Console.WriteLine("{0}{1}{0}", Environment.NewLine, errorMessage); Assert.Inconclusive(errorMessage); diff --git a/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs b/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs index 398482e5c..5cfe57e05 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/UnitTestConstants.cs @@ -35,7 +35,7 @@ public static partial class UnitTestConstants { "(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) " + System.IO.Path.GetRandomFileName() + "(3) Computer: [" + Environment.MachineName + "]" + "\tHello there, " + Environment.UserName }; diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 8ffe2bfba..75ce8a0ca 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -668,7 +668,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Filesystem/File Class/File.Copy.cs b/AlphaFS/Filesystem/File Class/File.Copy.cs index 85c5dbeeb..a523a1474 100644 --- a/AlphaFS/Filesystem/File Class/File.Copy.cs +++ b/AlphaFS/Filesystem/File Class/File.Copy.cs @@ -828,7 +828,7 @@ internal static CopyMoveResult CopyMoveCore(KernelTransaction transaction, bool if (isSingleFileAction) // We take an extra hit by getting the file size for a single file Copy or Move action. - cmr.TotalBytes = GetSizeCore(transaction, null, destinationPathLp, PathFormat.LongFullPath); + cmr.TotalBytes = GetSizeCore(transaction, null, destinationPathLp, false, PathFormat.LongFullPath); if (preserveDates) diff --git a/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs b/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs index f7fc7b786..2f0eee365 100644 --- a/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs +++ b/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs @@ -27,40 +27,40 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class File { - /// [AlphaFS] Enumerates the streams of type :$DATA from the specified file. + /// [AlphaFS] Enumerates all altername datastreams of the specified file. /// The path to the file to enumerate streams of. - /// The streams of type :$DATA in the specified file. + /// An enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreams(string path) { return EnumerateAlternateDataStreamsCore(null, path, PathFormat.RelativePath); } - /// [AlphaFS] Enumerates the streams of type :$DATA from the specified file. + /// [AlphaFS] Enumerates all altername datastreams of the specified file. /// The path to the file to enumerate streams of. /// Indicates the format of the path parameter(s). - /// The streams of type :$DATA in the specified file. + /// An enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreams(string path, PathFormat pathFormat) { return EnumerateAlternateDataStreamsCore(null, path, pathFormat); } - /// [AlphaFS] Enumerates the streams of type :$DATA from the specified file. + /// [AlphaFS] Enumerates all altername datastreams of the specified file. /// The transaction. /// The path to the file to enumerate streams of. - /// The streams of type :$DATA in the specified file. + /// An enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreamsTransacted(KernelTransaction transaction, string path) { return EnumerateAlternateDataStreamsCore(transaction, path, PathFormat.RelativePath); } - /// [AlphaFS] Enumerates the streams of type :$DATA from the specified file. + /// [AlphaFS] Enumerates all altername datastreams of the specified file. /// The transaction. /// The path to the file to enumerate streams of. /// Indicates the format of the path parameter(s). - /// The streams of type :$DATA in the specified file. + /// An enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreamsTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { @@ -70,59 +70,77 @@ public static IEnumerable EnumerateAlternateDataStreams - #region Internal Methods - /// [AlphaFS] Enumerates the streams of type :$DATA from the specified file or directory. /// The transaction. /// The path to the file or directory to enumerate streams of. /// Indicates the format of the path parameter(s). - /// The streams of type :$DATA in the specified file or directory. + /// An enumeration of instances. internal static IEnumerable EnumerateAlternateDataStreamsCore(KernelTransaction transaction, 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)))) - { - var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars | GetFullPathOptions.CheckAdditional); - using (var safeHandle = null == transaction + using (var safeHandle = 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(); + var reachedEOF = lastError == Win32Errors.ERROR_HANDLE_EOF; - // 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)) + if (!NativeMethods.IsValidHandle(safeHandle, false)) { - var lastError = Marshal.GetLastWin32Error(); - var reachedEOF = lastError == Win32Errors.ERROR_HANDLE_EOF; + if (reachedEOF) + yield break; + NativeError.ThrowException(lastError, pathLp); + } - if (!NativeMethods.IsValidHandle(safeHandle, false)) - { - if (reachedEOF) - yield break; - NativeError.ThrowException(lastError, pathLp); - } + while (true) + { + yield return new AlternateDataStreamInfo(pathLp, buffer.PtrToStructure(0)); + var success = NativeMethods.FindNextStreamW(safeHandle, buffer); - while (true) + lastError = Marshal.GetLastWin32Error(); + if (!success) { - yield return new AlternateDataStreamInfo(pathLp, buffer.PtrToStructure(0)); - - var success = NativeMethods.FindNextStreamW(safeHandle, buffer); - - lastError = Marshal.GetLastWin32Error(); - if (!success) - { - if (lastError == Win32Errors.ERROR_HANDLE_EOF) - break; - - NativeError.ThrowException(lastError, pathLp); - } + if (lastError == Win32Errors.ERROR_HANDLE_EOF) + break; + + NativeError.ThrowException(lastError, pathLp); } } } } - #endregion // Internal Methods + + internal static SafeFindFileHandle FindFirstStreamNative(KernelTransaction transaction, string pathLp, SafeGlobalMemoryBufferHandle buffer) + { + var safeHandle = 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(); + + if (lastError == Win32Errors.ERROR_HANDLE_EOF) + return null; + + if (!NativeMethods.IsValidHandle(safeHandle, false)) + NativeError.ThrowException(lastError, pathLp); + + return safeHandle; + } + } } } diff --git a/AlphaFS/Filesystem/File Class/File.GetSize.cs b/AlphaFS/Filesystem/File Class/File.GetSize.cs index d2011a56b..208bbade3 100644 --- a/AlphaFS/Filesystem/File Class/File.GetSize.cs +++ b/AlphaFS/Filesystem/File Class/File.GetSize.cs @@ -19,9 +19,11 @@ * THE SOFTWARE. */ +using System.Collections.ObjectModel; using Microsoft.Win32.SafeHandles; using System.Diagnostics.CodeAnalysis; using System.IO; +using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; @@ -30,37 +32,62 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class File { - #region GetSize + /// [AlphaFS] Retrieves the size of the specified file. + /// The path to the file. + /// The file size, in bytes. + [SecurityCritical] + public static long GetSize(string path) + { + return GetSizeCore(null, null, path, false, PathFormat.RelativePath); + } + - /// [AlphaFS] Retrieves the file size, in bytes to store a specified file. + /// [AlphaFS] Retrieves the size of the specified file. /// The path to the file. /// Indicates the format of the path parameter(s). /// The file size, in bytes. [SecurityCritical] public static long GetSize(string path, PathFormat pathFormat) { - return GetSizeCore(null, null, path, pathFormat); + return GetSizeCore(null, null, path, false, pathFormat); } - /// [AlphaFS] Retrieves the file size, in bytes to store a specified file. + + /// [AlphaFS] Retrieves the size of the specified file. /// The path to the file. + /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// The file size, in bytes. [SecurityCritical] - public static long GetSize(string path) + public static long GetSize(string path, bool sizeOfAllStreams) { - return GetSizeCore(null, null, path, PathFormat.RelativePath); + return GetSizeCore(null, null, path, sizeOfAllStreams, PathFormat.RelativePath); } - /// [AlphaFS] Retrieves the file size, in bytes to store a specified file. - /// The to the file. + + /// [AlphaFS] Retrieves the size of the specified file. + /// The path to the file. + /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. + /// Indicates the format of the path parameter(s). /// The file size, in bytes. [SecurityCritical] - public static long GetSize(SafeFileHandle handle) + public static long GetSize(string path, bool sizeOfAllStreams, PathFormat pathFormat) + { + return GetSizeCore(null, null, path, sizeOfAllStreams, pathFormat); + } + + + /// [AlphaFS] Retrieves the size of the specified file. + /// The transaction. + /// The path to the file. + /// The number of bytes of disk storage used to store the specified file. + [SecurityCritical] + public static long GetSizeTransacted(KernelTransaction transaction, string path) { - return GetSizeCore(null, handle, null, PathFormat.LongFullPath); + return GetSizeCore(transaction, null, path, false, PathFormat.RelativePath); } - /// [AlphaFS] Retrieves the file size, in bytes to store a specified file. + + /// [AlphaFS] Retrieves the size of the specified file. /// The transaction. /// The path to the file. /// Indicates the format of the path parameter(s). @@ -68,24 +95,48 @@ public static long GetSize(SafeFileHandle handle) [SecurityCritical] public static long GetSizeTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { - return GetSizeCore(transaction, null, path, pathFormat); + return GetSizeCore(transaction, null, path, false, pathFormat); } - /// [AlphaFS] Retrieves the file size, in bytes to store a specified file. + + /// [AlphaFS] Retrieves the size of the specified file. /// The transaction. /// The path to the file. + /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// The number of bytes of disk storage used to store the specified file. [SecurityCritical] - public static long GetSizeTransacted(KernelTransaction transaction, string path) + public static long GetSizeTransacted(KernelTransaction transaction, string path, bool sizeOfAllStreams) { - return GetSizeCore(transaction, null, path, PathFormat.RelativePath); + return GetSizeCore(transaction, null, path, sizeOfAllStreams, PathFormat.RelativePath); } - #endregion // GetSize - #region Internal Methods + /// [AlphaFS] Retrieves the size of the specified file. + /// The transaction. + /// The path to the file. + /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. + /// Indicates the format of the path parameter(s). + /// The number of bytes of disk storage used to store the specified file. + [SecurityCritical] + public static long GetSizeTransacted(KernelTransaction transaction, string path, bool sizeOfAllStreams, PathFormat pathFormat) + { + return GetSizeCore(transaction, null, path, sizeOfAllStreams, pathFormat); + } + - /// Retrieves the file size, in bytes to store a specified file. + /// [AlphaFS] Retrieves the size of the specified file. + /// The to the file. + /// The file size, in bytes. + [SecurityCritical] + public static long GetSize(SafeFileHandle handle) + { + return GetSizeCore(null, handle, null, false, PathFormat.LongFullPath); + } + + + + + /// Retrieves the size of the specified file. /// Use either or , not both. /// /// @@ -94,25 +145,33 @@ public static long GetSizeTransacted(KernelTransaction transaction, string path) /// The transaction. /// The to the file. /// The path to the file. + /// true to retrieve the size of all alternate data streams, false to get the size of the first stream. /// Indicates the format of the path parameter(s). [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] - internal static long GetSizeCore(KernelTransaction transaction, SafeFileHandle safeHandle, string path, PathFormat pathFormat) + internal static long GetSizeCore(KernelTransaction transaction, SafeFileHandle safeHandle, string path, bool sizeOfAllStreams, PathFormat pathFormat) { + var pathLp = path; + var callerHandle = null != safeHandle; if (!callerHandle) { - var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); + pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); safeHandle = CreateFileCore(transaction, pathLp, ExtendedFileAttributes.Normal, null, FileMode.Open, FileSystemRights.ReadData, FileShare.Read, true, false, PathFormat.LongFullPath); } + if (sizeOfAllStreams) + return GetSizeAllStreamsCore(transaction, pathLp, pathFormat); + + long fileSize; try { var success = NativeMethods.GetFileSizeEx(safeHandle, out fileSize); + var lastError = Marshal.GetLastWin32Error(); if (!success && lastError != Win32Errors.ERROR_SUCCESS) @@ -124,10 +183,65 @@ internal static long GetSizeCore(KernelTransaction transaction, SafeFileHandle s if (!callerHandle && null != safeHandle && !safeHandle.IsClosed) safeHandle.Close(); } + return fileSize; } - #endregion // Internal Methods + + /// Retrieves the size of all alternate datastreams. + /// The number of bytes of disk storage used to store the specified file. + /// + /// The transaction. + /// The path to the file. + /// Indicates the format of the path parameter(s). + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] + [SecurityCritical] + internal static long GetSizeAllStreamsCore(KernelTransaction transaction, string path, PathFormat pathFormat) + { + var pathLp = pathFormat == PathFormat.LongFullPath ? path : Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); + + var streamSizes = new Collection(); + + using (var buffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(NativeMethods.WIN32_FIND_STREAM_DATA)))) + using (var safeHandle = 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(); + var reachedEOF = lastError == Win32Errors.ERROR_HANDLE_EOF; + + + if (!NativeMethods.IsValidHandle(safeHandle, false)) + { + if (!reachedEOF) + NativeError.ThrowException(lastError, pathLp); + } + + + while (true) + { + streamSizes.Add(buffer.PtrToStructure(0).StreamSize); + + var success = NativeMethods.FindNextStreamW(safeHandle, buffer); + + lastError = Marshal.GetLastWin32Error(); + if (!success) + { + if (lastError == Win32Errors.ERROR_HANDLE_EOF) + break; + + NativeError.ThrowException(lastError, pathLp); + } + } + } + + + return streamSizes.Sum(); + } } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 76da24d6d..2b5e7697d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,12 +9,13 @@ Version 2.2.2 (2018-XX-XX) - Issue #434: `Directory.Move` operation worked in v2.0.1, but now fails in v.2.2.1 (Thx warrenlbrown) - Issue #436: `Directory.GetFiles()` with relative path (Thx stellarbear) - Issue #437: Fixed `PathTooLongException` for boundary case of directory name length in `Path.NormalizePath` (Thx okrushelnitsky) -- Issue #441: InvalidOperationException on Directory.EnumerateFileSystemEntries() (Thx CyberSinh) +- Issue #441: `InvalidOperationException` on `Directory.EnumerateFileSystemEntries()` (Thx CyberSinh) - Issue #444: Exception when moving or renaming a folder after updating from 2.1.3 to 2.2.1 (Thx mlaily) ### Improvements - Issue #149: Split unit-tests. +- Issue #451: Add overloaded method for `File.GetSize` to retrieve the size of all streams. - Because of bug fixes, the correct source-/destination folder is now shown in exceptions thrown from Directory/File.Copy/Move methods, instead of always showing the source folder path. - Improved some unit tests that would fail when a removable drive is already removed but there's still a cached reference. From 17ea90afad4b2b521fb55c7591b1e259e204a17e Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 4 Jun 2018 12:25:41 +0200 Subject: [PATCH 080/133] Relocated some files. --- AlphaFS/AlphaFS.csproj | 7 +++---- .../StreamAttributes.cs | 0 .../StreamId.cs | 0 3 files changed, 3 insertions(+), 4 deletions(-) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/StreamAttributes.cs (100%) rename AlphaFS/Filesystem/{Structures And Enumerations => Structures, Enumerations}/StreamId.cs (100%) diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index f5923cf61..fbdc4d201 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -392,9 +392,8 @@ - - - + + @@ -736,7 +735,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Filesystem/Structures And Enumerations/StreamAttributes.cs b/AlphaFS/Filesystem/Structures, Enumerations/StreamAttributes.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/StreamAttributes.cs rename to AlphaFS/Filesystem/Structures, Enumerations/StreamAttributes.cs diff --git a/AlphaFS/Filesystem/Structures And Enumerations/StreamId.cs b/AlphaFS/Filesystem/Structures, Enumerations/StreamId.cs similarity index 100% rename from AlphaFS/Filesystem/Structures And Enumerations/StreamId.cs rename to AlphaFS/Filesystem/Structures, Enumerations/StreamId.cs From 03dbdf7eedc663d7f9da5688c1779d48798d175d Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 5 Jun 2018 21:15:31 +0200 Subject: [PATCH 081/133] Renamed unit tests. --- ...Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs} | 2 +- ...vice.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs} | 4 ++-- ...aFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs} | 2 +- ...AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs | 3 +++ .../AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs | 3 +++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 6 +++--- 6 files changed, 13 insertions(+), 7 deletions(-) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs => AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs} (96%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs => AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs} (96%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs => AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs} (96%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs similarity index 96% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs index 45ff1ef41..7ba58e0d3 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromDevicePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetPhysicalDiskInfo_FromDevicePath_Success() + public void AlphaFS_Device_GetPhysicalDiskInfo_DevicePathFromSystemDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs similarity index 96% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs index f6ef2dbed..33aebd6bd 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs @@ -30,10 +30,10 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetPhysicalDiskInfo_FromLogicalDrive_Success() + public void AlphaFS_Device_GetPhysicalDiskInfo_LogicalDriveFromSystemDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); - + var driveCount = 0; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs similarity index 96% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs index 6a34bce2e..1045f2136 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_FromVolume.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetPhysicalDiskInfo_FromVolume_Success() + public void AlphaFS_Device_GetPhysicalDiskInfo_VolumeFromSystemDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs index 2817c8189..41bcd07cb 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs @@ -54,6 +54,9 @@ public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrive_Success() Assert.IsNotNull(storageAdapterInfo); gotDisk = true; + + + Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index 14730ce13..a5c4e1828 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -62,6 +62,9 @@ public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() if (drive.DriveType == System.IO.DriveType.CDRom) Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.CDRom, storageDeviceInfo.DeviceType); + + + Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index fabd21055..f730f7669 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -144,9 +144,9 @@ AssemblyVersionInfo.cs - - - + + + From b2bd3bbc233667f60137ae13844a816b83fccd8a Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 6 Jun 2018 01:28:53 +0200 Subject: [PATCH 082/133] -Fixed some code analysis issues; -Renamed some unit tests; --- ...e.GetStorageAdapterInfo_FromLogicalDrive.cs | 8 ++++---- ...ce.GetStorageDeviceInfo_FromLogicalDrive.cs | 12 ++++++------ ...GetStoragePartitionInfo_FromLogicalDrive.cs | 8 ++++---- ...DefineDosDevice_SymbolicLinkDriveMapping.cs | 4 ++-- ...ory.GetFileSystemEntryInfo_LogicalDrives.cs | 12 ++++++------ AlphaFS/AlphaFS.csproj | 6 +++--- AlphaFS/Device/Device.EnumerateDevices.cs | 2 ++ .../PhysicalDiskInfo/PhysicalDiskInfo.cs | 3 ++- AlphaFS/Filesystem/File Class/File.GetSize.cs | 1 + .../Filesystem/Link Stream/BackupStreamInfo.cs | 8 ++++---- ...TREAM_ATTRIBUTES.cs => STREAM_ATTRIBUTE.cs} | 4 ++-- .../Filesystem/Native Other/WIN32_STREAM_ID.cs | 2 +- AlphaFS/Filesystem/Shell32.cs | 2 ++ ...{StreamAttributes.cs => StreamAttribute.cs} | 18 +++++++++++------- .../Structures, Enumerations/StreamId.cs | 7 ++++++- 15 files changed, 56 insertions(+), 41 deletions(-) rename AlphaFS/Filesystem/Native Other/{STREAM_ATTRIBUTES.cs => STREAM_ATTRIBUTE.cs} (91%) rename AlphaFS/Filesystem/Structures, Enumerations/{StreamAttributes.cs => StreamAttribute.cs} (72%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs index 41bcd07cb..00be7b496 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs @@ -39,14 +39,14 @@ public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrive_Success() var driveCount = 0; - foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) + foreach (var driveInfo in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { - if (drive.DriveType == System.IO.DriveType.NoRootDirectory || drive.DriveType == System.IO.DriveType.Network) + if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory || driveInfo.DriveType == System.IO.DriveType.Network) continue; - var storageAdapterInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageAdapterInfo(drive.Name); + var storageAdapterInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageAdapterInfo(driveInfo.Name); - Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, drive.Name, storageAdapterInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageAdapterInfo.ToString()); UnitTestConstants.Dump(storageAdapterInfo, -28); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index a5c4e1828..098920df1 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -38,14 +38,14 @@ public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() var driveCount = 0; - foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) + foreach (var driveInfo in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { - if (drive.DriveType == System.IO.DriveType.NoRootDirectory || drive.DriveType == System.IO.DriveType.Network) + if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory || driveInfo.DriveType == System.IO.DriveType.Network) continue; - var storageDeviceInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageDeviceInfo(drive.Name); + var storageDeviceInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageDeviceInfo(driveInfo.Name); - Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, drive.Name, storageDeviceInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageDeviceInfo.ToString()); UnitTestConstants.Dump(storageDeviceInfo, -17); @@ -53,14 +53,14 @@ public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() Assert.IsNotNull(storageDeviceInfo); - if (drive.DriveType == System.IO.DriveType.Fixed) + if (driveInfo.DriveType == System.IO.DriveType.Fixed) { gotDisk = true; Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.Disk, storageDeviceInfo.DeviceType); } - if (drive.DriveType == System.IO.DriveType.CDRom) + if (driveInfo.DriveType == System.IO.DriveType.CDRom) Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.CDRom, storageDeviceInfo.DeviceType); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs index bbb3660ee..128d78b7c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs @@ -38,14 +38,14 @@ public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrive_Success() var driveCount = 0; - foreach (var drive in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) + foreach (var driveInfo in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { - if (drive.DriveType == System.IO.DriveType.NoRootDirectory || drive.DriveType == System.IO.DriveType.Network) + if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory || driveInfo.DriveType == System.IO.DriveType.Network) continue; - var storagePartitionInfo = Alphaleonis.Win32.Filesystem.Device.GetStoragePartitionInfo(drive.Name); + var storagePartitionInfo = Alphaleonis.Win32.Filesystem.Device.GetStoragePartitionInfo(driveInfo.Name); - Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, drive.Name, storagePartitionInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storagePartitionInfo.ToString()); UnitTestConstants.Dump(storagePartitionInfo, -23); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs index e91e8f49c..8240b4d65 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs @@ -38,8 +38,7 @@ public void AlphaFS_Volume_DefineDosDevice_SymbolicLinkDriveMapping_Local_Succes } - [TestMethod] - public void AlphaFS_Volume_DefineDosDevice_SymbolicLinkDriveMapping(bool isNetwork) + private void AlphaFS_Volume_DefineDosDevice_SymbolicLinkDriveMapping(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { @@ -68,6 +67,7 @@ public void AlphaFS_Volume_DefineDosDevice_SymbolicLinkDriveMapping(bool isNetwo } } + Console.WriteLine(); } } diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs index 8027d3a46..64668c97f 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs @@ -41,15 +41,15 @@ private void AlphaFS_Directory_GetFileSystemEntryInfo_LogicalDrives() { UnitTestConstants.PrintUnitTestHeader(false); - var drives = Alphaleonis.Win32.Filesystem.Directory.EnumerateLogicalDrives().ToList(); + var drives = Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives().ToArray(); - foreach (var drive in drives) + foreach (var driveInfo in drives) { - Console.WriteLine("Input Logical Drive: [{0}]", drive.Name); + Console.WriteLine("Input Logical Drive: [{0}]", driveInfo.Name); try { - var fsei = Alphaleonis.Win32.Filesystem.Directory.GetFileSystemEntryInfo(drive.Name); + var fsei = Alphaleonis.Win32.Filesystem.Directory.GetFileSystemEntryInfo(driveInfo.Name); UnitTestConstants.Dump(fsei, -19); @@ -58,7 +58,7 @@ private void AlphaFS_Directory_GetFileSystemEntryInfo_LogicalDrives() // Fixed local drives should have these attributes. - if (new Alphaleonis.Win32.Filesystem.DriveInfo(drive.Name).DriveType == System.IO.DriveType.Fixed) + 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."); @@ -66,7 +66,7 @@ private void AlphaFS_Directory_GetFileSystemEntryInfo_LogicalDrives() Assert.AreEqual(".", fsei.FileName, "The file names are not equal, but are expected to be."); - Assert.AreEqual(drive.Name, fsei.FullPath, "The full paths 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) { diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 763a6eb15..b5311e256 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -372,7 +372,7 @@ - + @@ -544,7 +544,7 @@ - + @@ -735,7 +735,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Device.EnumerateDevices.cs index d07ce7e1b..e37a61fed 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Device.EnumerateDevices.cs @@ -22,6 +22,7 @@ using Alphaleonis.Win32.Network; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; @@ -178,6 +179,7 @@ private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetDeviceInterfaceD } + [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "lastError")] private static string GetDeviceBusReportedDeviceDescription(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData) { if (!OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows7)) diff --git a/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs index 7332bb794..94e91d8a2 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs @@ -103,10 +103,11 @@ public PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) #region Methods - /// Checks if the volume or logical drive or is located on the physical disk. + /// Checks if the volume or logical drive is located on the physical disk. /// A drive path such as: "C", "C:" or "C:\". /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// + /// true if the volume or logical drive is located on the physical disk, false otherwise.. public bool ContainsVolume(string devicePath) { bool isDrive; diff --git a/AlphaFS/Filesystem/File Class/File.GetSize.cs b/AlphaFS/Filesystem/File Class/File.GetSize.cs index 215d5da7f..1d0e2dd2c 100644 --- a/AlphaFS/Filesystem/File Class/File.GetSize.cs +++ b/AlphaFS/Filesystem/File Class/File.GetSize.cs @@ -212,6 +212,7 @@ internal static long FindAllStreamsCore(KernelTransaction transaction, string pa } + [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "lastError")] [SecurityCritical] internal static SafeFindFileHandle FindFirstStreamNative(KernelTransaction transaction, string pathLp, SafeGlobalMemoryBufferHandle buffer) { diff --git a/AlphaFS/Filesystem/Link Stream/BackupStreamInfo.cs b/AlphaFS/Filesystem/Link Stream/BackupStreamInfo.cs index 887e05955..d3900d8e0 100644 --- a/AlphaFS/Filesystem/Link Stream/BackupStreamInfo.cs +++ b/AlphaFS/Filesystem/Link Stream/BackupStreamInfo.cs @@ -30,7 +30,7 @@ public sealed class BackupStreamInfo private readonly long _streamSize; private readonly string _streamName; private readonly StreamId _streamId; - private readonly StreamAttributes _streamAttributes; + private readonly StreamAttribute _streamAttribute; #endregion // Fields @@ -44,7 +44,7 @@ internal BackupStreamInfo(NativeMethods.WIN32_STREAM_ID streamId, string name) { _streamName = name; _streamSize = (long) streamId.Size; - _streamAttributes = (StreamAttributes) streamId.dwStreamAttributes; + _streamAttribute = (StreamAttribute) streamId.dwStreamAttribute; _streamId = (StreamId) streamId.dwStreamId; } @@ -79,9 +79,9 @@ public StreamId StreamType /// Gets the attributes of the data to facilitate cross-operating system transfer. /// Attributes of the data to facilitate cross-operating system transfer. - public StreamAttributes Attributes + public StreamAttribute Attribute { - get { return _streamAttributes; } + get { return _streamAttribute; } } #endregion // Public Properties diff --git a/AlphaFS/Filesystem/Native Other/STREAM_ATTRIBUTES.cs b/AlphaFS/Filesystem/Native Other/STREAM_ATTRIBUTE.cs similarity index 91% rename from AlphaFS/Filesystem/Native Other/STREAM_ATTRIBUTES.cs rename to AlphaFS/Filesystem/Native Other/STREAM_ATTRIBUTE.cs index 5eda92b46..d36794e98 100644 --- a/AlphaFS/Filesystem/Native Other/STREAM_ATTRIBUTES.cs +++ b/AlphaFS/Filesystem/Native Other/STREAM_ATTRIBUTE.cs @@ -23,8 +23,8 @@ namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { - /// WIN32_STREAM_ID Attributes of data to facilitate cross-operating system transfer. - internal enum STREAM_ATTRIBUTES + /// WIN32_STREAM_ID structure attributes of data to facilitate cross-operating system transfer. This member can be one or more of the following values. + internal enum STREAM_ATTRIBUTE { /// This backup stream has no special attributes. NONE = 0, diff --git a/AlphaFS/Filesystem/Native Other/WIN32_STREAM_ID.cs b/AlphaFS/Filesystem/Native Other/WIN32_STREAM_ID.cs index 22b84ce0f..0b921eb09 100644 --- a/AlphaFS/Filesystem/Native Other/WIN32_STREAM_ID.cs +++ b/AlphaFS/Filesystem/Native Other/WIN32_STREAM_ID.cs @@ -37,7 +37,7 @@ internal struct WIN32_STREAM_ID /// Attributes of data to facilitate cross-operating system transfer. [MarshalAs(UnmanagedType.U4)] - public readonly STREAM_ATTRIBUTES dwStreamAttributes; + public readonly STREAM_ATTRIBUTE dwStreamAttribute; /// Size of data, in bytes. [MarshalAs(UnmanagedType.U8)] diff --git a/AlphaFS/Filesystem/Shell32.cs b/AlphaFS/Filesystem/Shell32.cs index aaed8c737..c730d527d 100644 --- a/AlphaFS/Filesystem/Shell32.cs +++ b/AlphaFS/Filesystem/Shell32.cs @@ -302,6 +302,8 @@ public enum FileAttributes /// SHFILEINFO structure, contains information about a file system object. + [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] + [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct FileInfo { diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StreamAttributes.cs b/AlphaFS/Filesystem/Structures, Enumerations/StreamAttribute.cs similarity index 72% rename from AlphaFS/Filesystem/Structures, Enumerations/StreamAttributes.cs rename to AlphaFS/Filesystem/Structures, Enumerations/StreamAttribute.cs index 32fa3e96f..8e2cb8ec7 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StreamAttributes.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StreamAttribute.cs @@ -19,24 +19,28 @@ * THE SOFTWARE. */ +using System.Diagnostics.CodeAnalysis; + namespace Alphaleonis.Win32.Filesystem { - /// WIN32_STREAM_ID Attributes of data to facilitate cross-operating system transfer. - public enum StreamAttributes + /// Attributes of data to facilitate cross-operating system transfer. This member can be one or more of the following values. + [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] + [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] + public enum StreamAttribute { /// This backup stream has no special attributes. - None = NativeMethods.STREAM_ATTRIBUTES.NONE, + None = NativeMethods.STREAM_ATTRIBUTE.NONE, /// Attribute set if the stream contains data that is modified when read. Allows the backup application to know that verification of data will fail. - ModifiedWhenRead = NativeMethods.STREAM_ATTRIBUTES.STREAM_MODIFIED_WHEN_READ, + ModifiedWhenRead = NativeMethods.STREAM_ATTRIBUTE.STREAM_MODIFIED_WHEN_READ, /// The backup stream contains security information. This attribute applies only to backup stream of type . - ContainsSecurity = NativeMethods.STREAM_ATTRIBUTES.STREAM_CONTAINS_SECURITY, + ContainsSecurity = NativeMethods.STREAM_ATTRIBUTE.STREAM_CONTAINS_SECURITY, /// Reserved. - ContainsProperties = NativeMethods.STREAM_ATTRIBUTES.STREAM_CONTAINS_PROPERTIES, + ContainsProperties = NativeMethods.STREAM_ATTRIBUTE.STREAM_CONTAINS_PROPERTIES, /// The backup stream is part of a sparse file stream. This attribute applies only to backup stream of type , , and . - SparseAttribute = NativeMethods.STREAM_ATTRIBUTES.STREAM_SPARSE_ATTRIBUTE + SparseAttribute = NativeMethods.STREAM_ATTRIBUTE.STREAM_SPARSE_ATTRIBUTE } } diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StreamId.cs b/AlphaFS/Filesystem/Structures, Enumerations/StreamId.cs index d6672d946..b3258120c 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StreamId.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/StreamId.cs @@ -19,9 +19,11 @@ * THE SOFTWARE. */ +using System.Diagnostics.CodeAnalysis; + namespace Alphaleonis.Win32.Filesystem { - /// The type of the data contained in the backup stream. + /// The type of the data contained in the backup stream. This member can be one of the following values. public enum StreamId { /// This indicates an error. @@ -33,6 +35,8 @@ public enum StreamId /// Extended attribute data. This corresponds to the NTFS $EA stream type. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ea")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ea")] BackupEaData = NativeMethods.STREAM_ID.BACKUP_EA_DATA, @@ -66,6 +70,7 @@ public enum StreamId /// Transactional NTFS (TxF) data stream. /// Windows Server 2003 and Windows XP: This value is not supported. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Txfs")] BackupTxfsData = NativeMethods.STREAM_ID.BACKUP_TXFS_DATA } } From a20d85f2ceeab095ab90e3b789626c65e0ebdbdb Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 6 Jun 2018 19:57:23 +0200 Subject: [PATCH 083/133] -Improved PhysicalDiskInfo code; -Improved UnitTestConstants.Dump method; --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 8 +-- ...sicalDiskInfo_DevicePathFromSystemDrive.cs | 11 ++-- ...calDiskInfo_LogicalDriveFromSystemDrive.cs | 6 +- ...tPhysicalDiskInfo_VolumeFromSystemDrive.cs | 6 +- ....GetStorageAdapterInfo_FromLogicalDrive.cs | 2 +- ...e.GetStorageDeviceInfo_FromLogicalDrive.cs | 2 +- ...etStoragePartitionInfo_FromLogicalDrive.cs | 6 +- AlphaFS/Device/Device.OpenPhysicalDrive.cs | 6 +- .../Device.EnumeratePhysicalDisks.cs | 1 + .../Device.GetPhysicalDiskInfo.cs | 33 ++++++----- .../Device.GetStorageAdapterInfo.cs | 36 +++--------- .../Device.GetStorageDeviceInfo.cs | 38 +++++++------ .../Device.GetStoragePartitionInfo.cs | 22 ++++---- .../PhysicalDiskInfo/PhysicalDiskInfo.cs | 20 +++---- AlphaFS/Device/StorageAdapterInfo.cs | 11 +--- AlphaFS/Device/StorageDeviceInfo.cs | 11 +--- AlphaFS/Device/StorageGptPartitionInfo.cs | 19 ++----- AlphaFS/Device/StorageMbrPartitionInfo.cs | 19 ++----- AlphaFS/Device/StoragePartitionInfo.cs | 56 ++++++++----------- .../Volume/Volume.EnumerateVolumePathNames.cs | 2 +- .../Volume/Volume.GetVolumeDisplayName.cs | 2 +- 21 files changed, 133 insertions(+), 184 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index c641bc6a2..f67e52ff1 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -43,13 +43,13 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Local_Success() { Console.WriteLine("#{0:000}\tPhysical Disk: [{1}]\t\t{2}\t\t{3}", ++pDriveCount, pDisk.StorageDeviceInfo.DeviceNumber, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); - UnitTestConstants.Dump(pDisk, -24); + UnitTestConstants.Dump(pDisk); - UnitTestConstants.Dump(pDisk.StorageAdapterInfo, -28, true); + UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); - UnitTestConstants.Dump(pDisk.StorageDeviceInfo, -17, true); + UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); - UnitTestConstants.Dump(pDisk.StoragePartitionInfo, -17, true); + UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs index 7ba58e0d3..d0d10e6d7 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs @@ -20,6 +20,7 @@ */ using System; +using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -47,11 +48,13 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_DevicePathFromSystemDrive_Success Console.WriteLine("#{0:000}\tInput Device Path: [{1}]\t\t{2}\t\t{3}", ++deviceCount, devicePath, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); - UnitTestConstants.Dump(pDisk, -24); + UnitTestConstants.Dump(pDisk); - UnitTestConstants.Dump(pDisk.StorageAdapterInfo, -28, true); + UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); - UnitTestConstants.Dump(pDisk.StorageDeviceInfo, -17, true); + UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + + UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); Console.WriteLine(); @@ -59,7 +62,7 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_DevicePathFromSystemDrive_Success Assert.IsNotNull(pDisk.VolumeGuids); - Assert.IsTrue(pDisk.VolumeGuids.Contains(sourceVolume)); + Assert.IsTrue(pDisk.VolumeGuids.ToList().Contains(sourceVolume, StringComparer.OrdinalIgnoreCase)); Assert.IsNotNull(pDisk.LogicalDrives); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs index 33aebd6bd..7376794c0 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs @@ -45,11 +45,11 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_LogicalDriveFromSystemDrive_Succe Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}\t\t{3}", ++driveCount, sourceDrive, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); - UnitTestConstants.Dump(pDisk, -24); + UnitTestConstants.Dump(pDisk); - UnitTestConstants.Dump(pDisk.StorageAdapterInfo, -28, true); + UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); - UnitTestConstants.Dump(pDisk.StorageDeviceInfo, -17, true); + UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs index 1045f2136..3e92968f8 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs @@ -50,11 +50,11 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_VolumeFromSystemDrive_Success() Console.WriteLine("#{0:000}\tInput Volume: [{1}]\t\t{2}\t\t{3}", ++volumeCount, sourceVolume, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); - UnitTestConstants.Dump(pDisk, -24); + UnitTestConstants.Dump(pDisk); - UnitTestConstants.Dump(pDisk.StorageAdapterInfo, -28, true); + UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); - UnitTestConstants.Dump(pDisk.StorageDeviceInfo, -17, true); + UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs index 00be7b496..90cf74af0 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs @@ -48,7 +48,7 @@ public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrive_Success() Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageAdapterInfo.ToString()); - UnitTestConstants.Dump(storageAdapterInfo, -28); + UnitTestConstants.Dump(storageAdapterInfo); Assert.IsNotNull(storageAdapterInfo); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index 098920df1..1c97d0ab1 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -47,7 +47,7 @@ public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageDeviceInfo.ToString()); - UnitTestConstants.Dump(storageDeviceInfo, -17); + UnitTestConstants.Dump(storageDeviceInfo); Assert.IsNotNull(storageDeviceInfo); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs index 128d78b7c..e1bd16880 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs @@ -47,7 +47,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrive_Success() Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storagePartitionInfo.ToString()); - UnitTestConstants.Dump(storagePartitionInfo, -23); + UnitTestConstants.Dump(storagePartitionInfo); Assert.IsNotNull(storagePartitionInfo); @@ -58,7 +58,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrive_Success() gotDisk = true; foreach (var partition in storagePartitionInfo.GptPartitionInfo) - UnitTestConstants.Dump(partition, -23, true); + UnitTestConstants.Dump(partition, true); } @@ -67,7 +67,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrive_Success() gotDisk = true; foreach (var partition in storagePartitionInfo.MbrPartitionInfo) - UnitTestConstants.Dump(partition, -23, true); + UnitTestConstants.Dump(partition, true); } diff --git a/AlphaFS/Device/Device.OpenPhysicalDrive.cs b/AlphaFS/Device/Device.OpenPhysicalDrive.cs index 3468e687c..1d7a0bcca 100644 --- a/AlphaFS/Device/Device.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/Device.OpenPhysicalDrive.cs @@ -36,9 +36,9 @@ public static partial class Device /// /// /// - /// A disk path such as: "\\.\PhysicalDrive0" - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\. + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// /// If no elevated access is needed to access the physical disk or volume/logical drive, specify 0 for this parameter. diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs index 606ba6f7e..b7b3f2140 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs @@ -144,6 +144,7 @@ private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, Phy foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber)) { var volumeDriveNumber = pVolume.StorageDeviceInfo.DeviceNumber; + var volumePartitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs index 5beeb168e..0382882c7 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs @@ -31,17 +31,17 @@ public static partial class Device { /// [AlphaFS] Retrieves the physical disk on the Computer that is related to the logical drive name, volume GUID or . /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks and associated volumes and logical drives. + /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks, associated volumes and logical drives. /// Instead, use method and property and/or . /// /// A instance that represents the physical disk on the Computer or null on error/no data available. - /// - /// - /// + /// + /// + /// /// - /// A disk path such as: "\\.\PhysicalDrive0"s - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A disk path such as: \\.\PhysicalDrive0s + /// A drive path such as: C, C: or C:\. + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// [SecurityCritical] @@ -92,15 +92,15 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. /// /// A instance that represents the physical disk on the Computer or null on error/no data available. - /// - /// - /// - /// + /// + /// + /// + /// /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// - /// A disk path such as: "\\.\PhysicalDrive0" - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\. + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// /// A instance. @@ -139,14 +139,13 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string if (isElevated) { - //GetDriveStuff(@"\\.\C:"); - - using (var safeHandle = OpenPhysicalDisk(devicePath, FileSystemRights.Read)) { pDiskInfo.StorageAdapterInfo = GetStorageAdapterInfoNative(safeHandle, devicePath); storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, devicePath, storageDeviceInfo); + + pDiskInfo.StoragePartitionInfo = GetStoragePartitionInfoNative(safeHandle, devicePath); } } diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs index daa285940..84473d088 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs @@ -33,39 +33,17 @@ public static partial class Device /// Calling this method requires an elevated state. /// /// A instance that represent the storage device on the Computer that is related to . - /// - /// - /// - /// + /// + /// + /// + /// /// - /// A disk path such as: "\\.\PhysicalDrive0" - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\. + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) - { - return GetStorageAdapterInfoCore(devicePath); - } - - - - - /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . - /// Calling this method requires an elevated state. - /// - /// A instance that represent the storage device on the Computer that is related to . - /// - /// - /// - /// - /// - /// A disk path such as: "\\.\PhysicalDrive0"s - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". - /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". - /// - internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath) { string logicalDrive; diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs index aef3295a5..26211d9d6 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs @@ -30,17 +30,20 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Device { /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . - /// Properties of the returned instance are meaningless unless this method is called from an elevated state. + /// + /// When this method is called from a non-elevated state, only the properties and are useful. + /// The remaining properties are meaningless and can only be obtained by calling the method from an elevated state. + /// /// /// A instance that represent the storage device on the Computer that is related to . - /// - /// - /// - /// + /// + /// + /// + /// /// - /// A disk path such as: "\\.\PhysicalDrive0" - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\. + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) @@ -52,18 +55,21 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . - /// Properties of the returned instance are meaningless unless this method is called from an elevated state. + /// + /// When this method is called from a non-elevated state, only the properties and are useful. + /// The remaining properties are meaningless and can only be obtained by calling the method from an elevated state. + /// /// /// A instance that represent the storage device on the Computer that is related to . - /// - /// - /// - /// + /// + /// + /// + /// /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// - /// A disk path such as: "\\.\PhysicalDrive0"s - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A disk path such as: \\.\PhysicalDrive0s + /// A drive path such as: C, C: or C:\. + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". /// internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, string devicePath) diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs index ffccc129c..81b451058 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs @@ -30,16 +30,19 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { - + /// Retrieves information about the partitions on a disk and the features of each partition. + /// A instance that represent the partition info on the Computer that is related to . + /// + /// + /// + /// + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\. + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. + /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) - { - return GetStoragePartitionInfoCore(devicePath); - } - - - - - internal static StoragePartitionInfo GetStoragePartitionInfoCore(string devicePath) { string logicalDrive; @@ -55,7 +58,6 @@ internal static StoragePartitionInfo GetStoragePartitionInfoCore(string devicePa } - /// Retrieves information about the number of partitions on a disk and the features of each partition. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandle, string pathToDevice) { diff --git a/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs index 94e91d8a2..71ceb9637 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs @@ -20,7 +20,7 @@ */ using System; -using System.Collections.ObjectModel; +using System.Collections.Generic; using System.Linq; using System.Security; @@ -56,15 +56,15 @@ public PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) /// The path to the device. /// A string that represents the path to the device. - /// A drive path such as: "C:", "D:\", - /// a volume path such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\" + /// A drive path such as: C:, D:\, + /// a volume path such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// or a string. /// public string DevicePath { get; internal set; } /// The logical drives that are located on the physical disk. - public Collection LogicalDrives { get; internal set; } + public ICollection LogicalDrives { get; internal set; } /// The "FriendlyName" of the physical disk. @@ -72,14 +72,14 @@ public PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) /// The partition index numbers that are located on the physical disk. - public Collection PartitionIndexes { get; internal set; } + public ICollection PartitionIndexes { get; internal set; } /// Encapsulates the physical device location (PDO) information provided by a device's firmware to Windows. public string PhysicalDeviceObjectName { get; internal set; } - /// The storage device adapter information. + /// The storage device adapter information. Retrieving this information requires an elevated state. public StorageAdapterInfo StorageAdapterInfo { get; internal set; } @@ -92,11 +92,11 @@ public PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) /// A collection of volume GUID strings of volumes that are located on the physical disk. - public Collection VolumeGuids { get; internal set; } + public ICollection VolumeGuids { get; internal set; } ///// A collection of volume label strings of volumes that are located on the physical disk. - //public Collection VolumeLabels { get; internal set; } + //public ICollection VolumeLabels { get; internal set; } #endregion // Properties @@ -104,8 +104,8 @@ public PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) #region Methods /// Checks if the volume or logical drive is located on the physical disk. - /// A drive path such as: "C", "C:" or "C:\". - /// A volume such as: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A drive path such as: C, C: or C:\. + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. /// /// true if the volume or logical drive is located on the physical disk, false otherwise.. public bool ContainsVolume(string devicePath) diff --git a/AlphaFS/Device/StorageAdapterInfo.cs b/AlphaFS/Device/StorageAdapterInfo.cs index 3a29b2ff0..1c705bfc3 100644 --- a/AlphaFS/Device/StorageAdapterInfo.cs +++ b/AlphaFS/Device/StorageAdapterInfo.cs @@ -94,23 +94,16 @@ internal StorageAdapterInfo(NativeMethods.STORAGE_ADAPTER_DESCRIPTOR adapter) : /// Specifies the maximum number of bytes the storage adapter can transfer in a single operation. public int MaximumTransferBytes { get; internal set; } - - /// Specifies the maximum number of bytes the storage adapter can transfer in a single operation, formatted as a unit size. - public string MaximumTransferBytesUnitSize - { - get { return Utils.UnitSizeToText(MaximumTransferBytes); } - } - #endregion // Properties #region Methods - /// Returns storage device as: "BusType MaximumTransferBytesUnitSize". + /// Returns storage device as: "BusType MaximumTransferBytes". /// A string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "{0} {1}", (BusType.ToString() + " " + (null != BusVersion ? BusVersion.ToString() : string.Empty)).Trim(), MaximumTransferBytesUnitSize); + return BusType == StorageBusType.Unknown ? StorageBusType.Unknown.ToString() : string.Format(CultureInfo.CurrentCulture, "{0} {1}", (BusType.ToString() + " " ).Trim(), Utils.UnitSizeToText(MaximumTransferBytes)); } diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/StorageDeviceInfo.cs index c0d4326c5..c8d29e48c 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/StorageDeviceInfo.cs @@ -48,9 +48,9 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() { DeviceType = device.DeviceType; - DeviceNumber = (int) device.DeviceNumber; + DeviceNumber = device.DeviceNumber; - PartitionNumber = (int) device.PartitionNumber; + PartitionNumber = device.PartitionNumber; } #endregion // Constructors @@ -99,13 +99,6 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public long TotalSize { get; internal set; } - /// The total size of the physical disk, formatted as a unit size. - public string TotalSizeUnitSize - { - get { return Utils.UnitSizeToText(TotalSize); } - } - - /// The Vendor ID of the physical disk. public string VendorId { get; internal set; } diff --git a/AlphaFS/Device/StorageGptPartitionInfo.cs b/AlphaFS/Device/StorageGptPartitionInfo.cs index cae041620..786164356 100644 --- a/AlphaFS/Device/StorageGptPartitionInfo.cs +++ b/AlphaFS/Device/StorageGptPartitionInfo.cs @@ -106,15 +106,15 @@ internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio #region Properties /// The Extensible Firmware Interface (EFI) attributes of the partition. - public EfiPartitionAttributes Attributes { get; internal set; } + public EfiPartitionAttributes Attributes { get; private set; } /// The description of the partition. - public string Description { get; internal set; } + public string Description { get; private set; } /// The GUID of the partition. - public Guid PartitionId { get; internal set; } + public Guid PartitionId { get; private set; } /// The starting offset of the partition. @@ -138,23 +138,16 @@ internal set } - /// The starting offset of the partition, formatted as a unit size. - public string PartitionLengthUnitSize - { - get { return Utils.UnitSizeToText(PartitionLength); } - } - - /// The storage partition number, starting at 1. - public int PartitionNumber { get; internal set; } + public int PartitionNumber { get; private set; } /// The the partition type. Each partition type that the EFI specification supports is identified by its own GUID, which is published by the developer of the partition. - public PartitionType PartitionType { get; internal set; } + public PartitionType PartitionType { get; private set; } /// The rewritable status of the storage partition. - public bool RewritePartition { get; internal set; } + public bool RewritePartition { get; private set; } /// The starting offset of the partition. diff --git a/AlphaFS/Device/StorageMbrPartitionInfo.cs b/AlphaFS/Device/StorageMbrPartitionInfo.cs index 7a38006e1..511a431a1 100644 --- a/AlphaFS/Device/StorageMbrPartitionInfo.cs +++ b/AlphaFS/Device/StorageMbrPartitionInfo.cs @@ -79,15 +79,15 @@ internal StorageMbrPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio #region Properties /// true if the partition is a boot partition. - public bool BootIndicator { get; internal set; } + public bool BootIndicator { get; private set; } /// The type of the partition. - public DiskPartitionType DiskPartitionType { get; internal set; } + public DiskPartitionType DiskPartitionType { get; private set; } /// The number of hidden sectors to be allocated when the partition table is created. - public int HiddenSectors { get; internal set; } + public int HiddenSectors { get; private set; } /// The starting offset of the partition. @@ -111,23 +111,16 @@ internal set } - /// The starting offset of the partition, formatted as a unit size. - public string PartitionLengthUnitSize - { - get { return Utils.UnitSizeToText(PartitionLength); } - } - - /// The storage partition number, starting at 1. - public int PartitionNumber { get; internal set; } + public int PartitionNumber { get; private set; } /// true if the partition is of a recognized type. - public bool RecognizedPartition { get; internal set; } + public bool RecognizedPartition { get; private set; } /// The rewritable status of the storage partition. - public bool RewritePartition { get; internal set; } + public bool RewritePartition { get; private set; } /// The starting offset of the partition. diff --git a/AlphaFS/Device/StoragePartitionInfo.cs b/AlphaFS/Device/StoragePartitionInfo.cs index e22e2c65d..88ecbd47d 100644 --- a/AlphaFS/Device/StoragePartitionInfo.cs +++ b/AlphaFS/Device/StoragePartitionInfo.cs @@ -20,8 +20,10 @@ */ using System; +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -118,21 +120,21 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods /// The GUID of the disk. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] - public Guid GptDiskId { get; internal set; } + public Guid GptDiskId { get; private set; } /// The device number of the storage partition, starting at 0. - public int DeviceNumber { get; internal set; } + public int DeviceNumber { get; private set; } /// The maximum number of partitions that can be defined in the usable block. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] - public int GptMaxPartitionCount { get; internal set; } + public int GptMaxPartitionCount { get; private set; } /// Contains GUID partition table (GPT) partition information. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] - public Collection GptPartitionInfo { get; internal set; } + public ICollection GptPartitionInfo { get; private set; } /// The starting byte offset of the first usable block. @@ -176,61 +178,47 @@ internal set // } // } //} - - ///// (Only applicable to GPT partition) The size of the usable blocks on the disk in bytes, formatted as a unit size. - //public string GptUsableLengthUnitSize - //{ - // get { return Utils.UnitSizeToText(GptUsableLength); } - //} - /// Contains partition information specific to master boot record (MBR) disks. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr")] - public Collection MbrPartitionInfo { get; internal set; } + public ICollection MbrPartitionInfo { get; private set; } /// The MBR signature of the drive. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr")] - public long MbrSignature { get; internal set; } + public long MbrSignature { get; private set; } /// The media type of the storage partition. - public StorageMediaType MediaType { get; internal set; } + public StorageMediaType MediaType { get; private set; } /// The number of partitions on the drive. - public int PartitionCount { get; internal set; } + public int PartitionCount { get; private set; } /// The format of the partition. For a list of values, see . - public PartitionStyle PartitionStyle { get; internal set; } + public PartitionStyle PartitionStyle { get; private set; } /// The total size of the storage partition. - public long TotalSize { get; internal set; } - - - /// The total size of the storage partition, formatted as a unit size. - public string TotalSizeUnitSize - { - get { return Utils.UnitSizeToText(TotalSize); } - } - + public long TotalSize { get; private set; } #endregion // Properties - //#region Methods + #region Methods - ///// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". - ///// A string that represents this instance. - //public override string ToString() - //{ - // return string.Format(CultureInfo.CurrentCulture, "{0}:{1} {2} {3}", + /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". + /// A string that represents this instance. + public override string ToString() + { + return string.Format(CultureInfo.CurrentCulture, "{0}:{1} {2}", - // DeviceNumber.ToString(CultureInfo.InvariantCulture), PartitionNumber.ToString(CultureInfo.InvariantCulture), PartitionStyle.ToString(), TotalSizeUnitSize).Trim(); - //} + DeviceNumber.ToString(CultureInfo.InvariantCulture), "?".ToString(CultureInfo.InvariantCulture), PartitionStyle.ToString()).Trim(); + //DeviceNumber.ToString(CultureInfo.InvariantCulture), PartitionNumber.ToString(CultureInfo.InvariantCulture), PartitionStyle.ToString()).Trim(); + } ///// Determines whether the specified Object is equal to the current Object. @@ -281,6 +269,6 @@ public string TotalSizeUnitSize // return !(left == right); //} - //#endregion // Methods + #endregion // Methods } } diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs index 27b0babcb..4677c17fd 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs @@ -33,7 +33,7 @@ public static partial class Volume /// An enumerable collection of containing the path names for the specified volume. /// /// - /// A volume path: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. [SecurityCritical] public static IEnumerable EnumerateVolumePathNames(string volumeGuid) { diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs index 379cb3008..229a351d7 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs @@ -30,7 +30,7 @@ public static partial class Volume { /// [AlphaFS] Gets the shortest display name for the specified . /// This method basically returns the shortest string returned by - /// A volume path: "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". + /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. /// /// The shortest display name for the specified volume found, or null if no display names were found. /// From 709b4060b3107246a98dc0863a9e2d7b3120e619 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 7 Jun 2018 12:41:55 +0200 Subject: [PATCH 084/133] Some code improvement. --- .../AlphaFS_Device.EnumerateDevices.cs | 4 +- AlphaFS.UnitTest/UnitTest Utility/Dump.cs | 55 +++++------ AlphaFS/AlphaFS.csproj | 12 +-- AlphaFS/Device/Device.OpenPhysicalDrive.cs | 2 +- AlphaFS/Device/Device.ValidateDevicePath.cs | 2 + .../Device.EnumeratePhysicalDisks.cs | 2 +- .../Device.GetPhysicalDiskInfo.cs | 4 +- .../Device.GetStorageAdapterInfo.cs | 8 +- .../Device.GetStorageDeviceInfo.cs | 10 +- .../Device.GetStoragePartitionInfo.cs | 94 ++++++++++--------- .../{ => Storage}/StorageAdapterInfo.cs | 4 +- .../Device/{ => Storage}/StorageDeviceInfo.cs | 4 +- .../{ => Storage}/StorageGptPartitionInfo.cs | 12 +-- .../{ => Storage}/StorageMbrPartitionInfo.cs | 8 +- .../{ => Storage}/StoragePartitionInfo.cs | 27 ++++-- 15 files changed, 128 insertions(+), 120 deletions(-) rename AlphaFS/Device/{ => Storage}/StorageAdapterInfo.cs (97%) rename AlphaFS/Device/{ => Storage}/StorageDeviceInfo.cs (97%) rename AlphaFS/Device/{ => Storage}/StorageGptPartitionInfo.cs (97%) rename AlphaFS/Device/{ => Storage}/StorageMbrPartitionInfo.cs (95%) rename AlphaFS/Device/{ => Storage}/StoragePartitionInfo.cs (92%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs index a6f18bea4..a93b64440 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs @@ -45,14 +45,14 @@ private void AlphaFS_Device_EnumerateDevices() { UnitTestConstants.PrintUnitTestHeader(false); - var tempPath = Environment.MachineName; + var hostName = Environment.MachineName; var classCnt = 0; foreach (var deviceClass in EnumMemberToList()) { Console.WriteLine("#{0:000}\tClass: [{1}]", ++classCnt, deviceClass); - foreach (var device in Alphaleonis.Win32.Filesystem.Device.EnumerateDevices(tempPath, deviceClass)) + foreach (var device in Alphaleonis.Win32.Filesystem.Device.EnumerateDevices(hostName, deviceClass)) UnitTestConstants.Dump(device); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/UnitTest Utility/Dump.cs b/AlphaFS.UnitTest/UnitTest Utility/Dump.cs index 150d9849b..20b1712e6 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/Dump.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/Dump.cs @@ -52,54 +52,45 @@ public static void Dump(object obj, bool indent = false) foreach (var descriptor in allProperties) - { - string propValue; - - try - { - propValue = Write(descriptor.GetValue(obj)); - } - catch (Exception ex) - { - // Please do tell, oneliner preferably. - propValue = ex.Message.Replace(Environment.NewLine, " "); - } - - if (null == propValue) - propValue = "NULL"; - - Console.WriteLine(template, indent ? "\t" : string.Empty, ++count, descriptor.Name, propValue); - } + Console.WriteLine(template, indent ? "\t" : string.Empty, ++count, descriptor.Name, Write(descriptor.GetValue(obj)) ?? "NULL"); } private static string Write(object value) { - if (null == value) - return null; + try + { + if (null == value) + return null; - if (value is string) - return value as string; + if (value is string) + return value as string; - long number; - if (long.TryParse(value.ToString(), out number)) - return value.ToString(); + long number; + if (long.TryParse(value.ToString(), out number)) + return value.ToString(); - var objectType = value as IEnumerable; + var objectType = value as IEnumerable; - if (null == objectType) - return value.ToString(); + if (null == objectType) + return value.ToString(); - var sb = new StringBuilder(); + var sb = new StringBuilder(); - foreach (var objectValue in objectType) - sb.Append(objectValue + ", "); + foreach (var objectValue in objectType) + sb.Append(objectValue + ", "); - return sb.ToString().TrimEnd(',', ' '); + return sb.ToString().TrimEnd(',', ' '); + } + catch (Exception ex) + { + // Please do tell, oneliner preferably. + return ex.Message.Replace(Environment.NewLine, " "); + } } } } diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 271e8aa3f..8dcf0b944 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -197,9 +197,9 @@ True - - - + + + @@ -207,8 +207,8 @@ - - + + @@ -735,7 +735,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.OpenPhysicalDrive.cs b/AlphaFS/Device/Device.OpenPhysicalDrive.cs index 1d7a0bcca..869da114e 100644 --- a/AlphaFS/Device/Device.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/Device.OpenPhysicalDrive.cs @@ -39,7 +39,7 @@ public static partial class Device /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\. /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. /// /// If no elevated access is needed to access the physical disk or volume/logical drive, specify 0 for this parameter. [SecurityCritical] diff --git a/AlphaFS/Device/Device.ValidateDevicePath.cs b/AlphaFS/Device/Device.ValidateDevicePath.cs index 780e0f59d..0b239c58f 100644 --- a/AlphaFS/Device/Device.ValidateDevicePath.cs +++ b/AlphaFS/Device/Device.ValidateDevicePath.cs @@ -25,6 +25,8 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Device { + /// Determines the type of device path. + /// The final device path with a . internal static string ValidateDevicePath(string devicePath, out bool isDrive, out bool isVolume, out bool isDeviceInfo) { if (Utils.IsNullOrWhiteSpace(devicePath)) diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs index b7b3f2140..59d56ac78 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs @@ -148,7 +148,7 @@ private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, Phy var volumePartitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; - PopulateVolumeDetails(pDiskInfo, pVolume.StorageDeviceInfo.PartitionNumber, pVolume.DevicePath); + PopulateVolumeDetails(pDiskInfo, volumePartitionNumber, pVolume.DevicePath); // Get logical drive from volume matching DeviceNumber and PartitionNumber. diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs index 0382882c7..469593f39 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs @@ -42,7 +42,7 @@ public static partial class Device /// A disk path such as: \\.\PhysicalDrive0s /// A drive path such as: C, C: or C:\. /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. /// [SecurityCritical] public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) @@ -101,7 +101,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\. /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. /// /// A instance. /// A instance. diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs index 84473d088..fa1b39e84 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs @@ -41,13 +41,13 @@ public static partial class Device /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\. /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. /// public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) { - string logicalDrive; + string unused; - var pathToDevice = GetDevicePath(devicePath, out logicalDrive); + var pathToDevice = GetDevicePath(devicePath, out unused); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; @@ -94,7 +94,7 @@ private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle saf safeHandleRetry = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); - isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; + isRetry = NativeMethods.IsValidHandle(safeHandleRetry, false); } diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs index 26211d9d6..715d8bd82 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs @@ -44,7 +44,7 @@ public static partial class Device /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\. /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. /// public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { @@ -70,13 +70,13 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) /// A disk path such as: \\.\PhysicalDrive0s /// A drive path such as: C, C: or C:\. /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. /// internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, string devicePath) { - string logicalDrive; + string unused; - var pathToDevice = GetDevicePath(devicePath, out logicalDrive); + var pathToDevice = GetDevicePath(devicePath, out unused); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; @@ -164,7 +164,7 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH safeHandleRetry = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); - isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; + isRetry = NativeMethods.IsValidHandle(safeHandleRetry, false); } diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs index 81b451058..edb921e5f 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs @@ -40,13 +40,13 @@ public static partial class Device /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\. /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: "\\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}". + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. /// public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) { - string logicalDrive; + string unused; - var pathToDevice = GetDevicePath(devicePath, out logicalDrive); + var pathToDevice = GetDevicePath(devicePath, out unused); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; @@ -69,7 +69,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle // Get storage partition info. - using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, pathToDevice, NativeMethods.DefaultFileBufferSize / 8)) + using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, pathToDevice, NativeMethods.DefaultFileBufferSize / 4)) { if (null == safeBuffer) { @@ -87,7 +87,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandleRetry = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); - isRetry = null != safeHandleRetry && !safeHandleRetry.IsClosed && !safeHandleRetry.IsInvalid; + isRetry = NativeMethods.IsValidHandle(safeHandleRetry, false); } @@ -100,77 +100,81 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle if (isRetry && !safeHandleRetry.IsClosed) safeHandleRetry.Close(); - - - var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 - var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 + var drive = safeBuffer.PtrToStructure(); + + // Sanity check. + if (drive.PartitionCount <= 256) + { + var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 + var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 + var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; + + for (var i = 0; i <= drive.PartitionCount - 1; i++) - var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; - - - for (var i = 0; i <= drive.PartitionCount - 1; i++) + partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); - partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); + var disk = GetDiskGeometryExNative(safeHandle, pathToDevice); - var disk = GetDiskGeometryExNative(safeHandle, pathToDevice); + return new StoragePartitionInfo(disk, drive, partitions); + } - return new StoragePartitionInfo(disk, drive, partitions); + return null; } } - private static StoragePartitionInfo GetStoragePartitionInfoNative0(SafeFileHandle safeHandle, string pathForException) - { - var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 - var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 - var partitionCount = 1; + //private static StoragePartitionInfo GetStoragePartitionInfoNative0(SafeFileHandle safeHandle, string pathForException) + //{ + // var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 + // var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 + // var partitionCount = 1; - var bufferSize = driveStructureSize + partitionCount * partitionStructureSize; + // var bufferSize = driveStructureSize + partitionCount * partitionStructureSize; - while (true) - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) - { - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + // while (true) + // using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) + // { + // var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); - var lastError = Marshal.GetLastWin32Error(); + // var lastError = Marshal.GetLastWin32Error(); - if (success) - { - var drive = safeBuffer.PtrToStructure(); + // if (success) + // { + // var drive = safeBuffer.PtrToStructure(); - var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; + // var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; - for (partitionCount = 0; partitionCount <= drive.PartitionCount - 1; partitionCount++) + // for (partitionCount = 0; partitionCount <= drive.PartitionCount - 1; partitionCount++) - partitions[partitionCount] = safeBuffer.PtrToStructure(driveStructureSize + partitionCount * partitionStructureSize); + // partitions[partitionCount] = safeBuffer.PtrToStructure(driveStructureSize + partitionCount * partitionStructureSize); - var disk = GetDiskGeometryExNative(safeHandle, pathForException); + // var disk = GetDiskGeometryExNative(safeHandle, pathForException); - return new StoragePartitionInfo(disk, drive, partitions); - } + // return new StoragePartitionInfo(disk, drive, partitions); + // } - if (lastError == Win32Errors.ERROR_NOT_READY || + // if (lastError == Win32Errors.ERROR_NOT_READY || - // Dynamic disk. - lastError == Win32Errors.ERROR_INVALID_FUNCTION || + // // Dynamic disk. + // lastError == Win32Errors.ERROR_INVALID_FUNCTION || - // Request device number from a DeviceGuid.Image device. - lastError == Win32Errors.ERROR_NOT_SUPPORTED) + // // Request device number from a DeviceGuid.Image device. + // lastError == Win32Errors.ERROR_NOT_SUPPORTED) - return null; + // return null; - bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); - } - } + // bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); + // } + //} /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). diff --git a/AlphaFS/Device/StorageAdapterInfo.cs b/AlphaFS/Device/Storage/StorageAdapterInfo.cs similarity index 97% rename from AlphaFS/Device/StorageAdapterInfo.cs rename to AlphaFS/Device/Storage/StorageAdapterInfo.cs index 1c705bfc3..7de51a8ad 100644 --- a/AlphaFS/Device/StorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/StorageAdapterInfo.cs @@ -26,14 +26,14 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides access to adapter information of a storage device. + /// [AlphaFS] Provides access to adapter information of a storage device. [Serializable] [SecurityCritical] public sealed class StorageAdapterInfo { #region Constructors - /// Initializes a StorageAdapterInfo instance. + /// [AlphaFS] Initializes a StorageAdapterInfo instance. public StorageAdapterInfo() { BusType = StorageBusType.Unknown; diff --git a/AlphaFS/Device/StorageDeviceInfo.cs b/AlphaFS/Device/Storage/StorageDeviceInfo.cs similarity index 97% rename from AlphaFS/Device/StorageDeviceInfo.cs rename to AlphaFS/Device/Storage/StorageDeviceInfo.cs index c8d29e48c..96e10bd87 100644 --- a/AlphaFS/Device/StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/StorageDeviceInfo.cs @@ -26,14 +26,14 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides access to information of a storage device. + /// [AlphaFS] Provides access to information of a storage device. [Serializable] [SecurityCritical] public sealed class StorageDeviceInfo { #region Constructors - /// Initializes a StorageDeviceInfo instance. + /// [AlphaFS] Initializes a StorageDeviceInfo instance. public StorageDeviceInfo() { DeviceType = StorageDeviceType.Unknown; diff --git a/AlphaFS/Device/StorageGptPartitionInfo.cs b/AlphaFS/Device/Storage/StorageGptPartitionInfo.cs similarity index 97% rename from AlphaFS/Device/StorageGptPartitionInfo.cs rename to AlphaFS/Device/Storage/StorageGptPartitionInfo.cs index 786164356..1f6c73337 100644 --- a/AlphaFS/Device/StorageGptPartitionInfo.cs +++ b/AlphaFS/Device/Storage/StorageGptPartitionInfo.cs @@ -26,7 +26,7 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides access to GPT partition information of a storage device. + /// [AlphaFS] Provides access to GPT partition information of a storage device. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt"), Serializable] [SecurityCritical] public sealed class StorageGptPartitionInfo @@ -41,7 +41,7 @@ public sealed class StorageGptPartitionInfo #region Constructors - /// Initializes a StorageGptPartitionInfo instance. + /// [AlphaFS] Initializes a StorageGptPartitionInfo instance. public StorageGptPartitionInfo() { PartitionNumber = -1; @@ -64,10 +64,10 @@ internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio Description = gptPartition.Name.Trim(); PartitionId = gptPartition.PartitionId; - - - - + + + + // Convert the native enum since it is of type ulong. var attrs = gptPartition.Attributes; diff --git a/AlphaFS/Device/StorageMbrPartitionInfo.cs b/AlphaFS/Device/Storage/StorageMbrPartitionInfo.cs similarity index 95% rename from AlphaFS/Device/StorageMbrPartitionInfo.cs rename to AlphaFS/Device/Storage/StorageMbrPartitionInfo.cs index 511a431a1..47c3c6eee 100644 --- a/AlphaFS/Device/StorageMbrPartitionInfo.cs +++ b/AlphaFS/Device/Storage/StorageMbrPartitionInfo.cs @@ -26,7 +26,7 @@ namespace Alphaleonis.Win32.Filesystem { - /// Provides access to MBR partition information of a storage device. + /// [AlphaFS] Provides access to MBR partition information of a storage device. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr"), Serializable] [SecurityCritical] public sealed class StorageMbrPartitionInfo @@ -41,7 +41,7 @@ public sealed class StorageMbrPartitionInfo #region Constructors - /// Initializes a StorageMbrPartitionInfo instance. + /// [AlphaFS] Initializes a StorageMbrPartitionInfo instance. public StorageMbrPartitionInfo() { HiddenSectors = -1; @@ -88,7 +88,7 @@ internal StorageMbrPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio /// The number of hidden sectors to be allocated when the partition table is created. public int HiddenSectors { get; private set; } - + /// The starting offset of the partition. public long PartitionLength @@ -152,7 +152,7 @@ internal set /// A string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "BootIndicator {0}, Type: {1}, RecognizedPartition: {2}", BootIndicator.ToString(), DiskPartitionType.ToString(), RecognizedPartition.ToString()).Trim(); + return string.Format(CultureInfo.CurrentCulture, "BootIndicator: {0}, Type: {1}, RecognizedPartition: {2}", BootIndicator.ToString(), DiskPartitionType.ToString(), RecognizedPartition.ToString()).Trim(); } diff --git a/AlphaFS/Device/StoragePartitionInfo.cs b/AlphaFS/Device/Storage/StoragePartitionInfo.cs similarity index 92% rename from AlphaFS/Device/StoragePartitionInfo.cs rename to AlphaFS/Device/Storage/StoragePartitionInfo.cs index 88ecbd47d..82b3f9d92 100644 --- a/AlphaFS/Device/StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/StoragePartitionInfo.cs @@ -24,11 +24,12 @@ using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { - /// Provides access to partition information of a storage device. + /// [AlphaFS] Provides access to partition information of a storage device. [Serializable] [SecurityCritical] public sealed class StoragePartitionInfo @@ -42,7 +43,7 @@ public sealed class StoragePartitionInfo #region Constructors - /// Initializes a StoragePartitionInfo instance. + /// [AlphaFS] Initializes a StoragePartitionInfo instance. public StoragePartitionInfo() { DeviceNumber = -1; @@ -80,7 +81,7 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods GptPartitionInfo = new Collection(); var partitionTypes = Utils.EnumToArray(); - + for (var i = 0; i <= PartitionCount - 1; i++) GptPartitionInfo.Add(new StorageGptPartitionInfo(partitions[i], partitionTypes)); @@ -88,6 +89,11 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods case PartitionStyle.Mbr: + + if (null == MbrPartitionInfo) + MbrPartitionInfo = new Collection(); + + for (var i = 0; i <= PartitionCount - 1; i++) { var partition = partitions[i]; @@ -97,10 +103,7 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods if (partition.Mbr.PartitionType == (NativeMethods.DiskPartitionType) DiskPartitionType.UnusedEntry) continue; - - - if (null == MbrPartitionInfo) - MbrPartitionInfo = new Collection(); + MbrPartitionInfo.Add(new StorageMbrPartitionInfo(partition)); } @@ -111,6 +114,10 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods break; } + + + IsOnDynamicDisk = null != GptPartitionInfo && GptPartitionInfo.Any(partition => partition.PartitionType == PartitionType.LdmData) || + null != MbrPartitionInfo && MbrPartitionInfo.Any(partition => partition.DiskPartitionType == DiskPartitionType.Ldm); } #endregion // Constructors @@ -157,7 +164,7 @@ internal set } } } - + ///// The size of the usable blocks on the disk, in bytes. //public long GptUsableLength @@ -180,6 +187,10 @@ internal set //} + /// true if the partition is on a dynamic disk. + public bool IsOnDynamicDisk { get; private set; } + + /// Contains partition information specific to master boot record (MBR) disks. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr")] public ICollection MbrPartitionInfo { get; private set; } From 1e9585ec6a9cb74f9af615fe3f50c2429c70ca03 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 7 Jun 2018 13:55:59 +0200 Subject: [PATCH 085/133] Fixed failing unit tests. --- AlphaFS.UnitTest/UnitTest Utility/Dump.cs | 46 +++++++++++------------ 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/AlphaFS.UnitTest/UnitTest Utility/Dump.cs b/AlphaFS.UnitTest/UnitTest Utility/Dump.cs index 20b1712e6..c420d5574 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/Dump.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/Dump.cs @@ -52,45 +52,43 @@ public static void Dump(object obj, bool indent = false) foreach (var descriptor in allProperties) - - Console.WriteLine(template, indent ? "\t" : string.Empty, ++count, descriptor.Name, Write(descriptor.GetValue(obj)) ?? "NULL"); + 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) { - try - { - if (null == value) - return null; + if (null == value) + return null; - if (value is string) - return value as string; + if (value is string) + return value as string; - long number; - if (long.TryParse(value.ToString(), out number)) - return value.ToString(); + long number; + if (long.TryParse(value.ToString(), out number)) + return value.ToString(); - var objectType = value as IEnumerable; + var objectType = value as IEnumerable; - if (null == objectType) - return value.ToString(); + if (null == objectType) + return value.ToString(); - var sb = new StringBuilder(); + var sb = new StringBuilder(); - foreach (var objectValue in objectType) - sb.Append(objectValue + ", "); + foreach (var objectValue in objectType) + sb.Append(objectValue + ", "); - return sb.ToString().TrimEnd(',', ' '); - } - catch (Exception ex) - { - // Please do tell, oneliner preferably. - return ex.Message.Replace(Environment.NewLine, " "); - } + return sb.ToString().TrimEnd(',', ' '); } } } From b8d721829f8c234c4bc6984144b47a79bd41c57f Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 7 Jun 2018 19:46:45 +0200 Subject: [PATCH 086/133] -Introduced Alphaleonis.Win32.Device namespace; -(#455) Moved class DeviceInfo from Alphaleonis.Win32.Filesystem to Alphaleonis.Win32.Device namespace; -Documentation fixes. --- AlphaFS.Doc/AlphaFS.Doc.shfbproj | 14 +- ...m_FilePortionIsLocked_ThrowsIOException.cs | 1 - ...aFS_BackupFileStream_InitializeInstance.cs | 1 - ...egmentAlreadyUnlocked_ThrowsIOException.cs | 1 - .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 2 +- ...sicalDiskInfo_DevicePathFromSystemDrive.cs | 4 +- ...calDiskInfo_LogicalDriveFromSystemDrive.cs | 2 +- ...tPhysicalDiskInfo_VolumeFromSystemDrive.cs | 5 +- ....GetStorageAdapterInfo_FromLogicalDrive.cs | 2 +- ...e.GetStorageDeviceInfo_FromLogicalDrive.cs | 2 +- ...etStoragePartitionInfo_FromLogicalDrive.cs | 2 +- ...ume.DefineDosDevice_RegularDriveMapping.cs | 1 - .../AlphaFS_Device.EnumerateDevices.cs | 2 +- .../AlphaFS_File.GetHash.cs | 1 - ...thSameNameAsDirectory_ThrowsIOException.cs | 1 - ..._Directory.Move_FileToMappedDriveLetter.cs | 1 - .../UnitTest Utility/UnitTestAssert.cs | 1 - AlphaFS.sln | 1 + AlphaFS/AlphaFS.csproj | 57 +++--- .../{DeviceInfo.cs => Device.DeviceInfo.cs} | 16 +- .../{Device.cs => Device.FileSystemHelper.cs} | 39 +--- AlphaFS/Device/Device.Local.cs | 28 +++ .../DriveInfo.EnumerateLogicalDrives.cs | 2 +- .../DriveInfo/DriveInfo.GetFreeDriveLetter.cs | 4 +- AlphaFS/Device/DriveInfo/DriveInfo.cs | 12 +- .../FilesystemHelper.Compression.cs} | 9 +- ...lesystemHelper.CreateDirectoryJunction.cs} | 5 +- ...lesystemHelper.DeleteDirectoryJunction.cs} | 5 +- .../FilesystemHelper.GetDevicePath.cs} | 7 +- .../FilesystemHelper.GetLinkTarget.cs} | 9 +- .../FilesystemHelper.OpenPhysicalDrive.cs} | 14 +- .../FilesystemHelper.ValidateDevicePath.cs} | 5 +- ...teDevices.cs => Local.EnumerateDevices.cs} | 43 +++-- ...eIoData.cs => Local.InvokeDeviceIoData.cs} | 11 +- .../Device.PhysicalDiskInfo.cs} | 44 +++-- .../Local.EnumeratePhysicalDisks.cs} | 13 +- .../Local.GetPhysicalDiskInfo.cs} | 46 ++--- ...erInfo.cs => Device.StorageAdapterInfo.cs} | 9 +- ...iceInfo.cs => Device.StorageDeviceInfo.cs} | 9 +- ...o.cs => Device.StorageGptPartitionInfo.cs} | 10 +- ...o.cs => Device.StorageMbrPartitionInfo.cs} | 10 +- ...Info.cs => Device.StoragePartitionInfo.cs} | 19 +- .../Local.GetDeviceIoData.cs} | 9 +- .../Local.GetStorageAdapterInfo.cs} | 24 +-- .../Local.GetStorageDeviceInfo.cs} | 47 +++-- .../Local.GetStoragePartitionInfo.cs} | 36 ++-- .../Local.GetVolumeDiskExtents.cs} | 7 +- AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs | 8 +- AlphaFS/Device/Volume/Volume.DriveType.cs | 6 +- .../Volume.EnumerateVolumeMountPoints.cs | 8 +- .../Volume/Volume.EnumerateVolumePathNames.cs | 6 +- .../Device/Volume/Volume.EnumerateVolumes.cs | 8 +- .../Device/Volume/Volume.GetDriveFormat.cs | 2 +- .../Volume.GetDriveNameForNtDeviceName.cs | 2 +- .../Volume/Volume.GetVolumeDeviceName.cs | 2 +- .../Volume/Volume.GetVolumeDisplayName.cs | 2 +- AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs | 2 +- .../Volume.GetVolumeGuidForNtDeviceName.cs | 7 +- AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs | 4 +- .../Device/Volume/Volume.GetVolumePathName.cs | 4 +- AlphaFS/Device/Volume/Volume.IsReady.cs | 2 +- AlphaFS/Device/Volume/Volume.IsSameVolume.cs | 2 +- AlphaFS/Device/Volume/Volume.IsVolume.cs | 4 +- .../Device/Volume/Volume.QueryDosDevice.cs | 4 +- AlphaFS/Device/Volume/Volume.VolumeLabel.cs | 4 +- AlphaFS/Device/Volume/VolumeInfo.cs | 6 +- AlphaFS/Filesystem/ByHandleFileInfo.cs | 4 +- .../{Device => Filesystem}/ChangeErrorMode.cs | 0 AlphaFS/Filesystem/CopyMoveResult.cs | 2 +- .../Directory Class/Directory.Compress.cs | 4 +- .../Directory Class/Directory.Copy.cs | 68 +++---- .../Directory.CreateDirectory.cs | 68 +++---- .../Directory.CreateJunction.cs | 2 +- .../Directory.CreateSymbolicLink.cs | 44 +++-- .../Directory Class/Directory.Delete.cs | 18 +- .../Directory.DeleteJunction.cs | 56 ++---- .../Directory.DisableCompression.cs | 8 +- .../Directory.EnableCompression.cs | 8 +- .../Directory.EnumerateDirectories.cs | 144 +++++++-------- ...ectory.EnumerateFileIdBothDirectoryInfo.cs | 24 +-- .../Directory.EnumerateFileSystemEntries.cs | 128 +++++++------- ...Directory.EnumerateFileSystemEntryInfos.cs | 66 +++---- .../Directory.EnumerateFiles.cs | 144 +++++++-------- .../Directory.EnumerateLogicalDrives.cs | 4 +- .../Directory Class/Directory.ExistsDrive.cs | 8 +- .../Directory.ExistsJunction.cs | 55 +++--- .../Directory.GetAccessControl.cs | 12 +- .../Directory.GetChangeTime.cs | 20 +-- .../Directory.GetCreationTime.cs | 16 +- .../Directory.GetDirectories.cs | 12 +- .../Directory.GetFileIdInfo.cs | 8 +- .../Directory.GetFileInfoByHandle.cs | 10 +- .../Directory.GetFileSystemEntries.cs | 12 +- .../Directory Class/Directory.GetFiles.cs | 12 +- .../Directory.GetLastAccessTime.cs | 16 +- .../Directory.GetLastWriteTime.cs | 16 +- .../Directory.GetLogicalDrives.cs | 4 +- .../Directory.GetProperties.cs | 18 +- .../Directory Class/Directory.Move.cs | 24 +-- .../DirectoryInfo.Compression.cs | 4 +- .../DirectoryInfo.CopyTo.cs | 28 +-- .../DirectoryInfo.CreateJunction.cs | 72 +++----- .../DirectoryInfo.DeleteJunction.cs | 12 +- .../DirectoryInfo.Encryption.cs | 4 +- ...ctoryInfo.EnumerateAlternateDataStreams.cs | 4 +- .../DirectoryInfo.EnumerateDirectories.cs | 20 +-- .../DirectoryInfo.EnumerateFileSystemInfos.cs | 20 +-- .../DirectoryInfo.EnumerateFiles.cs | 20 +-- .../DirectoryInfo.GetAccessControl.cs | 4 +- .../DirectoryInfo.GetDirectories.cs | 6 +- .../DirectoryInfo.GetFileId.cs | 2 +- .../DirectoryInfo.GetFileSystemInfos.cs | 6 +- .../DirectoryInfo.GetFiles.cs | 6 +- .../DirectoryInfo.MoveTo.cs | 10 +- .../DirectoryInfo.ToString.cs | 2 +- .../{Device => Filesystem}/DiskSpaceInfo.cs | 6 +- .../Filesystem/File Class/File.AppendText.cs | 18 +- .../Filesystem/File Class/File.Compress.cs | 8 +- AlphaFS/Filesystem/File Class/File.Copy.cs | 64 +++---- AlphaFS/Filesystem/File Class/File.Create.cs | 38 ++-- .../File Class/File.CreateSymbolicLink.cs | 63 +++---- .../Filesystem/File Class/File.CreateText.cs | 12 +- .../Filesystem/File Class/File.Decompress.cs | 8 +- .../File.EnumerateAlternateDataStreams.cs | 10 +- .../File Class/File.EnumerateHardlinks.cs | 22 +-- .../File Class/File.GetAccessControl.cs | 16 +- .../File Class/File.GetChangeTime.cs | 24 +-- .../File Class/File.GetCompressedSize.cs | 2 +- .../File Class/File.GetFileIdInfo.cs | 12 +- .../File Class/File.GetFileInfoByHandle.cs | 16 +- .../File Class/File.GetLinkTargetInfo.cs | 2 +- AlphaFS/Filesystem/File Class/File.GetSize.cs | 2 +- AlphaFS/Filesystem/File Class/File.Move.cs | 24 +-- AlphaFS/Filesystem/File Class/File.Open.cs | 15 +- .../File Class/File.OpenBackupRead.cs | 8 +- .../Filesystem/File Class/File.OpenRead.cs | 8 +- .../Filesystem/File Class/File.OpenText.cs | 16 +- .../Filesystem/File Class/File.OpenWrite.cs | 8 +- .../File Class/File.ReadAllBytes.cs | 10 +- .../File Class/File.ReadAllLines.cs | 2 +- .../File Class/File.SetAccessControl.cs | 2 +- AlphaFS/Filesystem/File Class/File.cs | 1 - .../FileInfo Class/FileInfo.AppendText.cs | 4 +- .../FileInfo Class/FileInfo.Compress.cs | 2 +- .../FileInfo Class/FileInfo.CopyToMoveTo.cs | 42 ++--- .../FileInfo Class/FileInfo.Create.cs | 2 +- .../FileInfo Class/FileInfo.CreateText.cs | 2 +- .../FileInfo Class/FileInfo.Decompress.cs | 2 +- .../FileInfo.EnumerateAlternateDataStreams.cs | 4 +- .../FileInfo.GetAccessControl.cs | 9 +- .../FileInfo Class/FileInfo.GetFileId.cs | 2 +- .../FileInfo Class/FileInfo.Open.cs | 10 +- .../FileInfo Class/FileInfo.OpenRead.cs | 2 +- .../FileInfo Class/FileInfo.OpenText.cs | 4 +- .../FileInfo Class/FileInfo.OpenWrite.cs | 2 +- .../FileInfo Class/FileInfo.Replace.cs | 8 +- AlphaFS/Filesystem/FileSystemEntryInfo.cs | 2 +- AlphaFS/Filesystem/FileSystemInfo.cs | 6 +- AlphaFS/Filesystem/FindFileSystemEntryInfo.cs | 4 +- AlphaFS/Filesystem/KernelTransaction.cs | 2 +- .../Link Stream/AlternateDataStreamInfo.cs | 29 ++- .../Link Stream/BackupFileStream.cs | 14 +- .../NativeMethods.DiskManagement.cs | 2 +- .../Native Methods/NativeMethods.ErrorMode.cs | 60 +++++++ .../NativeMethods.FileManagement.cs | 5 +- .../Native Methods/NativeMethods.Shell32.cs | 2 +- .../Native Methods/NativeMethods.Utilities.cs | 166 ------------------ .../NativeMethods.VolumeManagement.cs | 4 +- AlphaFS/Filesystem/Native Other/FILETIME.cs | 7 +- .../Native Other/WIN32_FILE_ATTRIBUTE_DATA.cs | 2 +- .../Path.AddTrailingDirectorySeparator.cs | 4 +- .../Path.GetFinalPathNameByHandle.cs | 10 +- .../Filesystem/Path Class/Path.GetFullPath.cs | 14 +- .../Path.GetInvalidFileNameChars.cs | 2 +- .../Path Class/Path.GetInvalidPathChars.cs | 2 +- .../Filesystem/Path Class/Path.GetLongPath.cs | 4 +- .../Filesystem/Path Class/Path.GetPathRoot.cs | 4 +- .../Path Class/Path.GetRandomFileName.cs | 2 +- .../Path Class/Path.GetShort83Path.cs | 4 +- AlphaFS/Filesystem/Path Class/Path.Helpers.cs | 2 +- .../Filesystem/Path Class/Path.IsLongPath.cs | 2 +- .../Filesystem/Path Class/Path.IsUncPath.cs | 4 +- .../Filesystem/Path Class/Path.LocalToUnc.cs | 20 +-- .../Path.RemoveTrailingDirectorySeparator.cs | 4 +- AlphaFS/Filesystem/Shell32.cs | 22 +-- AlphaFS/Filesystem/Shell32Info.cs | 2 +- .../DirectoryEnumerationFilters.cs | 2 +- .../Structures, Enumerations/FileIdInfo.cs | 16 +- .../FinalPathFormats.cs | 2 +- .../PartitionType..cs | 51 +++--- .../Structures, Enumerations/PathFormat.cs | 6 +- AlphaFS/GlobalSuppressions.cs | 2 + AlphaFS/Network/DfsInfo.cs | 2 +- AlphaFS/Network/DfsStorageInfo.cs | 2 +- .../Host Class/Host.DFS.EnumerateDfsLinks.cs | 2 +- .../Host Class/Host.DFS.EnumerateDfsRoot.cs | 6 +- .../Host.DFS.EnumerateDomainDfsRoot.cs | 6 +- .../Host Class/Host.DFS.GetDfsClientInfo.cs | 4 +- .../Network/Host Class/Host.DFS.GetDfsInfo.cs | 4 +- .../Host.EnumerateNetworkConnections.cs | 8 +- .../Host Class/Host.EnumerateNetworks.cs | 12 +- AlphaFS/Network/Host Class/Host.GetNetwork.cs | 2 +- .../Host Class/Host.GetNetworkConnection.cs | 2 +- .../Host Class/Host.SMB.EnumerateDrives.cs | 8 +- .../Host.SMB.EnumerateOpenConnections.cs | 8 +- .../Host.SMB.EnumerateOpenResources.cs | 6 +- .../Host Class/Host.SMB.EnumerateSessions.cs | 10 +- .../Host Class/Host.SMB.EnumerateShares.cs | 45 ++--- .../Host Class/Host.SMB.GetNetStatistics.cs | 10 +- .../Host Class/Host.SMB.GetShareInfo.cs | 10 +- .../Host Class/Host.WNet.DriveConnection.cs | 2 +- AlphaFS/Network/Host Class/Host.cs | 2 +- AlphaFS/Network/NetworkConnectionInfo.cs | 6 +- AlphaFS/Network/NetworkInfo.cs | 4 +- AlphaFS/Network/OpenConnectionInfo.cs | 2 +- AlphaFS/Network/OpenResourceInfo.cs | 2 +- AlphaFS/Network/ServerStatisticsInfo.cs | 8 +- AlphaFS/Network/SessionInfo.cs | 2 +- AlphaFS/Network/ShareInfo.cs | 2 +- AlphaFS/Network/WorkstationStatisticsInfo.cs | 4 +- AlphaFS/Resources.resx | 6 +- .../SafeNativeMemoryBufferHandle.cs | 8 +- AlphaFS/Security/CRC/Crc32.cs | 2 +- AlphaFS/Security/CRC/Crc64.cs | 6 +- AlphaFS/Security/InternalPrivilegeEnabler.cs | 2 +- AlphaFS/Security/Privilege.cs | 6 +- AlphaFS/Security/ProcessContext.cs | 2 +- AlphaFS/Security/SecurityAttributes.cs | 2 +- AlphaFS/Utils.cs | 142 +++++++++++++++ CHANGELOG.md | 7 +- 230 files changed, 1651 insertions(+), 1642 deletions(-) rename AlphaFS/Device/{DeviceInfo.cs => Device.DeviceInfo.cs} (85%) rename AlphaFS/Device/{Device.cs => Device.FileSystemHelper.cs} (58%) create mode 100644 AlphaFS/Device/Device.Local.cs rename AlphaFS/Device/{Device.Compression.cs => FileSystemHelper/FilesystemHelper.Compression.cs} (80%) rename AlphaFS/Device/{Junctions, Links/Device.CreateDirectoryJunction.cs => FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs} (96%) rename AlphaFS/Device/{Junctions, Links/Device.DeleteDirectoryJunction.cs => FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs} (94%) rename AlphaFS/Device/{Device.GetDevicePath.cs => FileSystemHelper/FilesystemHelper.GetDevicePath.cs} (90%) rename AlphaFS/Device/{Junctions, Links/Device.GetLinkTarget.cs => FileSystemHelper/FilesystemHelper.GetLinkTarget.cs} (94%) rename AlphaFS/Device/{Device.OpenPhysicalDrive.cs => FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs} (91%) rename AlphaFS/Device/{Device.ValidateDevicePath.cs => FileSystemHelper/FilesystemHelper.ValidateDevicePath.cs} (95%) rename AlphaFS/Device/{Device.EnumerateDevices.cs => Local.EnumerateDevices.cs} (84%) rename AlphaFS/Device/{Device.InvokeDeviceIoData.cs => Local.InvokeDeviceIoData.cs} (84%) rename AlphaFS/Device/{PhysicalDiskInfo/PhysicalDiskInfo.cs => PhysicalDisk/Device.PhysicalDiskInfo.cs} (76%) rename AlphaFS/Device/{PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs => PhysicalDisk/Local.EnumeratePhysicalDisks.cs} (92%) rename AlphaFS/Device/{PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs => PhysicalDisk/Local.GetPhysicalDiskInfo.cs} (74%) rename AlphaFS/Device/Storage/{StorageAdapterInfo.cs => Device.StorageAdapterInfo.cs} (95%) rename AlphaFS/Device/Storage/{StorageDeviceInfo.cs => Device.StorageDeviceInfo.cs} (95%) rename AlphaFS/Device/Storage/{StorageGptPartitionInfo.cs => Device.StorageGptPartitionInfo.cs} (95%) rename AlphaFS/Device/Storage/{StorageMbrPartitionInfo.cs => Device.StorageMbrPartitionInfo.cs} (94%) rename AlphaFS/Device/Storage/{StoragePartitionInfo.cs => Device.StoragePartitionInfo.cs} (93%) rename AlphaFS/Device/{Device.GetDeviceIoData.cs => Storage/Local.GetDeviceIoData.cs} (90%) rename AlphaFS/Device/{PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs => Storage/Local.GetStorageAdapterInfo.cs} (82%) rename AlphaFS/Device/{PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs => Storage/Local.GetStorageDeviceInfo.cs} (86%) rename AlphaFS/Device/{PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs => Storage/Local.GetStoragePartitionInfo.cs} (86%) rename AlphaFS/Device/{Device.GetVolumeDiskExtents.cs => Storage/Local.GetVolumeDiskExtents.cs} (91%) rename AlphaFS/{Device => Filesystem}/ChangeErrorMode.cs (100%) rename AlphaFS/{Device => Filesystem}/DiskSpaceInfo.cs (98%) create mode 100644 AlphaFS/Filesystem/Native Methods/NativeMethods.ErrorMode.cs delete mode 100644 AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs diff --git a/AlphaFS.Doc/AlphaFS.Doc.shfbproj b/AlphaFS.Doc/AlphaFS.Doc.shfbproj index 65553abdc..f34370faf 100644 --- a/AlphaFS.Doc/AlphaFS.Doc.shfbproj +++ b/AlphaFS.Doc/AlphaFS.Doc.shfbproj @@ -39,8 +39,8 @@ Standard 2.2 - - + + https://github.com/alphaleonis/AlphaFS/ False @@ -49,11 +49,11 @@ The Filesystem namespace contains classes to access and work with the local filesystem. Many of the classes in this namespace are replicas of the ones available in the System.IO namespace, but with added functionality. All methods in this namespace accept long windows unicode paths (i.e. paths starting with <c>\\?\</c>). Additional classes and methods are provided to provide more advanced functionality than that of System.IO. - This namespace contains classes directly related to security such as authentication, authorization and privilege tokens that may be needed for some file operations. For an example the SE_SECURITY_NAME privilege needs to be held to be able to modify the SACL of any file. - - This namespace contains general classes related to the Win32 Api. - This namespace contains network related classes. - +This namespace contains classes directly related to security such as authentication, authorization and privilege tokens that may be needed for some file operations. For an example the SE_SECURITY_NAME privilege needs to be held to be able to modify the SACL of any file. + +This namespace contains general classes related to the Win32 Api. +The Network namespace contains network related classes. +The Device namespace contains device related classes. HtmlHelp1, Website diff --git a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_AlphaFS_BackupFileStream_FilePortionIsLocked_ThrowsIOException.cs b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_AlphaFS_BackupFileStream_FilePortionIsLocked_ThrowsIOException.cs index 009490ccc..262147aff 100644 --- a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_AlphaFS_BackupFileStream_FilePortionIsLocked_ThrowsIOException.cs +++ b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_AlphaFS_BackupFileStream_FilePortionIsLocked_ThrowsIOException.cs @@ -21,7 +21,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Globalization; namespace AlphaFS.UnitTest { diff --git a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs index 99889108c..695215841 100644 --- a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs +++ b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs @@ -21,7 +21,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Globalization; namespace AlphaFS.UnitTest { diff --git a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_SegmentAlreadyUnlocked_ThrowsIOException.cs b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_SegmentAlreadyUnlocked_ThrowsIOException.cs index aba55d5d8..6b9d3609d 100644 --- a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_SegmentAlreadyUnlocked_ThrowsIOException.cs +++ b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_SegmentAlreadyUnlocked_ThrowsIOException.cs @@ -21,7 +21,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Globalization; namespace AlphaFS.UnitTest { diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index f67e52ff1..a6305d445 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -37,7 +37,7 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Local_Success() var pDriveCount = 0; - var pDrives = Alphaleonis.Win32.Filesystem.Device.EnumeratePhysicalDisks().OrderBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber).ThenBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.PartitionNumber).ToArray(); + var pDrives = Alphaleonis.Win32.Device.Local.EnumeratePhysicalDisks().OrderBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber).ThenBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.PartitionNumber).ToArray(); foreach (var pDisk in pDrives) { diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs index d0d10e6d7..88c7d5c0c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs @@ -40,9 +40,9 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_DevicePathFromSystemDrive_Success var sourceDrive = UnitTestConstants.SysDrive; var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - var devicePath = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDiskInfo(sourceDrive).DevicePath; + var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; - var pDisk = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDiskInfo(devicePath); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); Console.WriteLine("#{0:000}\tInput Device Path: [{1}]\t\t{2}\t\t{3}", ++deviceCount, devicePath, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs index 7376794c0..1be331c85 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs @@ -40,7 +40,7 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_LogicalDriveFromSystemDrive_Succe // Use lowercase drive letter because .Contains() is case sensitive by default. var sourceDrive = UnitTestConstants.SysDrive.ToLowerInvariant() + System.IO.Path.DirectorySeparatorChar; - var pDisk = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDiskInfo(sourceDrive); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive); Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}\t\t{3}", ++driveCount, sourceDrive, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs index 3e92968f8..63622b837 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs @@ -40,11 +40,10 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_VolumeFromSystemDrive_Success() // Use lowercase drive letter because .Contains() is case sensitive by default. var sourceDrive = UnitTestConstants.SysDrive.ToLowerInvariant(); - // Use uppercase volume guid because .Contains() is case sensitive by default. - var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive).ToUpperInvariant(); + var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - var pDisk = Alphaleonis.Win32.Filesystem.Device.GetPhysicalDiskInfo(sourceVolume); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); Console.WriteLine("#{0:000}\tInput Volume: [{1}]\t\t{2}\t\t{3}", ++volumeCount, sourceVolume, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs index 90cf74af0..18f7bb424 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs @@ -44,7 +44,7 @@ public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrive_Success() if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory || driveInfo.DriveType == System.IO.DriveType.Network) continue; - var storageAdapterInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageAdapterInfo(driveInfo.Name); + var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(driveInfo.Name); Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageAdapterInfo.ToString()); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index 1c97d0ab1..1a635ee57 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -43,7 +43,7 @@ public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory || driveInfo.DriveType == System.IO.DriveType.Network) continue; - var storageDeviceInfo = Alphaleonis.Win32.Filesystem.Device.GetStorageDeviceInfo(driveInfo.Name); + var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(driveInfo.Name); Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageDeviceInfo.ToString()); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs index e1bd16880..f64bd2072 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs @@ -43,7 +43,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrive_Success() if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory || driveInfo.DriveType == System.IO.DriveType.Network) continue; - var storagePartitionInfo = Alphaleonis.Win32.Filesystem.Device.GetStoragePartitionInfo(driveInfo.Name); + var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(driveInfo.Name); Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storagePartitionInfo.ToString()); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs index ea2ef14a2..20c4cd928 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_RegularDriveMapping.cs @@ -21,7 +21,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Globalization; namespace AlphaFS.UnitTest { diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs index a93b64440..bececdf49 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs @@ -52,7 +52,7 @@ private void AlphaFS_Device_EnumerateDevices() { Console.WriteLine("#{0:000}\tClass: [{1}]", ++classCnt, deviceClass); - foreach (var device in Alphaleonis.Win32.Filesystem.Device.EnumerateDevices(hostName, deviceClass)) + foreach (var device in Alphaleonis.Win32.Device.Local.EnumerateDevices(hostName, deviceClass)) UnitTestConstants.Dump(device); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File.GetHash.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File.GetHash.cs index de7da0206..f3977fffe 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File.GetHash.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_File.GetHash.cs @@ -21,7 +21,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Globalization; namespace AlphaFS.UnitTest { diff --git a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_FileExistsWithSameNameAsDirectory_ThrowsIOException.cs b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_FileExistsWithSameNameAsDirectory_ThrowsIOException.cs index 397dae9c8..c829c95b7 100644 --- a/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_FileExistsWithSameNameAsDirectory_ThrowsIOException.cs +++ b/AlphaFS.UnitTest/AlphaFS Junctions, Links/AlphaFS_Directory.CreateJunction_FileExistsWithSameNameAsDirectory_ThrowsIOException.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest diff --git a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_FileToMappedDriveLetter.cs b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_FileToMappedDriveLetter.cs index f368a8862..3a235e37c 100644 --- a/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_FileToMappedDriveLetter.cs +++ b/AlphaFS.UnitTest/Directory Class/Directory.Move/AlphaFS_Directory.Move_FileToMappedDriveLetter.cs @@ -21,7 +21,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Globalization; namespace AlphaFS.UnitTest { diff --git a/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs b/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs index 5b07797dc..9f62a698f 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs @@ -20,7 +20,6 @@ */ using System; -using System.Globalization; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/AlphaFS.sln b/AlphaFS.sln index 1623affa5..d475c8ee2 100644 --- a/AlphaFS.sln +++ b/AlphaFS.sln @@ -11,6 +11,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution AlphaFS.vsmdi = AlphaFS.vsmdi BuildRelease.proj = BuildRelease.proj CHANGELOG.md = CHANGELOG.md + AlphaFS\Device\Filesystem\Device.Filesystem.cs = AlphaFS\Device\Filesystem\Device.Filesystem.cs LICENSE.md = LICENSE.md README.md = README.md EndProjectSection diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 8dcf0b944..72c7b1ae4 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -196,31 +196,32 @@ True - - - - + + + + + - - - - - - - - - - - - - - + + + + + + + + + + + + + + - - - + + + @@ -249,7 +250,7 @@ - + @@ -325,6 +326,7 @@ + @@ -433,10 +435,10 @@ - - + + - + @@ -505,7 +507,6 @@ - @@ -554,7 +555,7 @@ - + @@ -735,7 +736,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/DeviceInfo.cs b/AlphaFS/Device/Device.DeviceInfo.cs similarity index 85% rename from AlphaFS/Device/DeviceInfo.cs rename to AlphaFS/Device/Device.DeviceInfo.cs index c697eec47..497fbd387 100644 --- a/AlphaFS/Device/DeviceInfo.cs +++ b/AlphaFS/Device/Device.DeviceInfo.cs @@ -22,24 +22,30 @@ using Alphaleonis.Win32.Network; using System; using System.Security; +using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - /// Provides access to information of a device. + /// [AlphaFS] Provides access to information of a device. [Serializable] [SecurityCritical] public sealed class DeviceInfo { #region Constructors - /// Initializes a DeviceInfo class. + /// [AlphaFS] Initializes a DeviceInfo class. [SecurityCritical] public DeviceInfo() { HostName = Host.GetUncName(); } - /// Initializes a DeviceInfo class. + /// [AlphaFS] Initializes a DeviceInfo class from a local or remote host. + /// + /// 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 + /// /// The DNS or NetBIOS name of the remote server. null refers to the local host. [SecurityCritical] public DeviceInfo(string host) @@ -76,7 +82,7 @@ public DeviceInfo(string host) public string DeviceDescription { get; internal set; } - /// The device interface path. + /// The device interface path string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} public string DevicePath { get; internal set; } diff --git a/AlphaFS/Device/Device.cs b/AlphaFS/Device/Device.FileSystemHelper.cs similarity index 58% rename from AlphaFS/Device/Device.cs rename to AlphaFS/Device/Device.FileSystemHelper.cs index 5939c8c59..467325dd8 100644 --- a/AlphaFS/Device/Device.cs +++ b/AlphaFS/Device/Device.FileSystemHelper.cs @@ -19,49 +19,16 @@ * THE SOFTWARE. */ -using System.Globalization; -using System.Runtime.InteropServices; -using System.Security; - -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// [AlphaFS] Provides static methods to retrieve device resource information from a local or remote host. - public static partial class Device + internal static partial class FileSystemHelper { /// MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384 private const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384; + /// REPARSE_DATA_BUFFER_HEADER_SIZE = 8 private const int REPARSE_DATA_BUFFER_HEADER_SIZE = 8; - - - [SecurityCritical] - private static int GetDoubledBufferSizeOrThrowException(SafeHandle safeBuffer, int lastError, int bufferSize, string pathForException) - { - if (null != safeBuffer && !safeBuffer.IsClosed) - safeBuffer.Close(); - - - switch ((uint) lastError) - { - case Win32Errors.ERROR_MORE_DATA: - case Win32Errors.ERROR_INSUFFICIENT_BUFFER: - case Win32Errors.ERROR_INVALID_PARAMETER: - - if (bufferSize == 0) - bufferSize = NativeMethods.DefaultFileBufferSize / 32; // 128 - - 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; - } } } diff --git a/AlphaFS/Device/Device.Local.cs b/AlphaFS/Device/Device.Local.cs new file mode 100644 index 000000000..0f7a84500 --- /dev/null +++ b/AlphaFS/Device/Device.Local.cs @@ -0,0 +1,28 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Device +{ + /// [AlphaFS] Provides static methods to retrieve device resource information from the local host. + public static partial class Local + { + } +} diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs index b6780b0ef..de0c2b535 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Filesystem public sealed partial class DriveInfo { /// Enumerates the drive names of all logical drives on the Computer. - /// An IEnumerable of type that represents the logical drives on the Computer. + /// Returns an collection of logical drives on the Computer. /// Retrieve logical drives as known by the Environment. /// Retrieve only when accessible (IsReady) logical drives. [SecurityCritical] diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs index fa4ea3368..a473b596d 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs @@ -28,7 +28,7 @@ namespace Alphaleonis.Win32.Filesystem public sealed partial class DriveInfo { /// [AlphaFS] Gets the first available drive letter on the local system. - /// A drive letter as . When no drive letters are available, an exception is thrown. + /// Returns a drive letter as . When no drive letters are available, an exception is thrown. /// The letters "A" and "B" are reserved for floppy drives and will never be returned by this function. public static char GetFreeDriveLetter() { @@ -38,7 +38,7 @@ public static char GetFreeDriveLetter() /// [AlphaFS] Gets an available drive letter on the local system. /// When true get the last available drive letter. When false gets the first available drive letter. - /// A drive letter as . When no drive letters are available, an exception is thrown. + /// Returns a drive letter as . When no drive letters are available, an exception is thrown. /// The letters "A" and "B" are reserved for floppy drives and will never be returned by this function. /// No drive letters available. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.cs index 3c00f1be3..40937f71c 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.cs @@ -148,7 +148,7 @@ public bool IsReady /// Gets the name of the drive. /// The name of the drive. - /// This property is the name assigned to the drive, such as: "C:\" or "D:\". + /// This property is the name assigned to the drive, such as: C:\ or "D:\". public string Name { get { return _name; } @@ -156,7 +156,7 @@ public string Name /// Gets the root directory of a drive. - /// A DirectoryInfo object that contains the root directory of the drive. + /// Returns a DirectoryInfo object that contains the root directory of the drive. public DirectoryInfo RootDirectory { get { return (DirectoryInfo) GetDeviceInfo(2, 0); } @@ -257,7 +257,7 @@ public bool IsVolume /// [AlphaFS] Contains information about a file system volume. - /// A object that contains file system volume information of the drive. + /// Returns a object that contains file system volume information of the drive. public VolumeInfo VolumeInfo { get { return (VolumeInfo) GetDeviceInfo(0, 0); } @@ -271,7 +271,7 @@ public VolumeInfo VolumeInfo #region .NET /// Retrieves the names of the logical drives on the Computer in the form "drive letter:\". - /// An array of type that represents the logical drives on the Computer. + /// Returns an of instances on the Computer. [SecurityCritical] public static DriveInfo[] GetDrives() { @@ -291,7 +291,9 @@ public override string ToString() /// [AlphaFS] Retrieves the names of the logical drives on the Computer in the form "drive letter:\". - /// An array of type that represents the logical drives on the Computer. + /// Returns an of instances on the Computer. + /// Retrieve logical drives as known by the Environment. + /// Retrieve only when accessible (IsReady) logical drives. [SecurityCritical] public static DriveInfo[] GetDrives(bool fromEnvironment, bool isReady) { diff --git a/AlphaFS/Device/Device.Compression.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.Compression.cs similarity index 80% rename from AlphaFS/Device/Device.Compression.cs rename to AlphaFS/Device/FileSystemHelper/FilesystemHelper.Compression.cs index 49bed62a2..cbbda71e0 100644 --- a/AlphaFS/Device/Device.Compression.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.Compression.cs @@ -22,10 +22,11 @@ using System.IO; using System.Security; using System.Security.AccessControl; +using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + internal static partial class FileSystemHelper { /// [AlphaFS] Sets the NTFS compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. /// The transaction. @@ -35,9 +36,9 @@ public static partial class Device [SecurityCritical] internal static void ToggleCompressionCore(KernelTransaction transaction, string path, bool compress, PathFormat pathFormat) { - using (var safeHandle = File.CreateFileCore(transaction, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.Modify, FileShare.None, true, false, pathFormat)) + using (var safeHandle = Win32.Filesystem.File.CreateFileCore(transaction, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.Modify, FileShare.None, true, false, pathFormat)) - using (InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.FSCTL_SET_COMPRESSION, compress ? 1 : 0, path)) { } + using (Local.InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.FSCTL_SET_COMPRESSION, compress ? 1 : 0, path)) { } } } } diff --git a/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs similarity index 96% rename from AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs rename to AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs index 3ca4b556b..2c46668cf 100644 --- a/AlphaFS/Device/Junctions, Links/Device.CreateDirectoryJunction.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs @@ -24,11 +24,12 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; +using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] - public static partial class Device + internal static partial class FileSystemHelper { /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). internal static void CreateDirectoryJunction(SafeFileHandle safeHandle, string directoryPath) diff --git a/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs similarity index 94% rename from AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs rename to AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs index c0ba5274f..ff95bd5be 100644 --- a/AlphaFS/Device/Junctions, Links/Device.DeleteDirectoryJunction.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs @@ -22,10 +22,11 @@ using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; +using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + internal static partial class FileSystemHelper { /// [AlphaFS] Deletes an NTFS directory junction. internal static void DeleteDirectoryJunction(SafeFileHandle safeHandle) diff --git a/AlphaFS/Device/Device.GetDevicePath.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs similarity index 90% rename from AlphaFS/Device/Device.GetDevicePath.cs rename to AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs index f9b87ece0..fe55ba76e 100644 --- a/AlphaFS/Device/Device.GetDevicePath.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs @@ -20,12 +20,13 @@ */ using System.Globalization; +using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + internal static partial class FileSystemHelper { - private static string GetDevicePath(string devicePath, out string logicalDrive) + internal static string GetDevicePath(string devicePath, out string logicalDrive) { bool isDrive; bool isVolume; diff --git a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs similarity index 94% rename from AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs rename to AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs index 55a68e2ed..a88d3b20e 100644 --- a/AlphaFS/Device/Junctions, Links/Device.GetLinkTarget.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs @@ -25,10 +25,11 @@ using System.Runtime.InteropServices; using System.Security; using System.Text; +using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + internal static partial class FileSystemHelper { /// [AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system. /// @@ -88,7 +89,7 @@ internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, stri [SecurityCritical] private static SafeGlobalMemoryBufferHandle GetLinkTargetData(SafeFileHandle safeHandle, string reparsePath) { - NativeMethods.IsValidHandle(safeHandle); + Utils.IsValidHandle(safeHandle); var bufferSize = MAXIMUM_REPARSE_DATA_BUFFER_SIZE; @@ -104,7 +105,7 @@ private static SafeGlobalMemoryBufferHandle GetLinkTargetData(SafeFileHandle saf if (success) return safeBuffer; - bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, reparsePath); + bufferSize = Utils.GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, reparsePath); } } } diff --git a/AlphaFS/Device/Device.OpenPhysicalDrive.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs similarity index 91% rename from AlphaFS/Device/Device.OpenPhysicalDrive.cs rename to AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs index 869da114e..853e3e32f 100644 --- a/AlphaFS/Device/Device.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs @@ -24,22 +24,24 @@ using System.IO; using System.Security; using System.Security.AccessControl; +using Alphaleonis.Win32.Filesystem; +using File = Alphaleonis.Win32.Filesystem.File; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + internal static partial class FileSystemHelper { /// Opens a physical disk or volume/logical drive for read access. - /// A instance. + /// Returns a instance. /// /// /// /// /// /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\. - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// /// If no elevated access is needed to access the physical disk or volume/logical drive, specify 0 for this parameter. [SecurityCritical] diff --git a/AlphaFS/Device/Device.ValidateDevicePath.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.ValidateDevicePath.cs similarity index 95% rename from AlphaFS/Device/Device.ValidateDevicePath.cs rename to AlphaFS/Device/FileSystemHelper/FilesystemHelper.ValidateDevicePath.cs index 0b239c58f..aea027637 100644 --- a/AlphaFS/Device/Device.ValidateDevicePath.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.ValidateDevicePath.cs @@ -20,10 +20,11 @@ */ using System; +using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + internal static partial class FileSystemHelper { /// Determines the type of device path. /// The final device path with a . diff --git a/AlphaFS/Device/Device.EnumerateDevices.cs b/AlphaFS/Device/Local.EnumerateDevices.cs similarity index 84% rename from AlphaFS/Device/Device.EnumerateDevices.cs rename to AlphaFS/Device/Local.EnumerateDevices.cs index e37a61fed..afd8e302f 100644 --- a/AlphaFS/Device/Device.EnumerateDevices.cs +++ b/AlphaFS/Device/Local.EnumerateDevices.cs @@ -26,13 +26,15 @@ using System.Runtime.InteropServices; using System.Security; using System.Text; +using Alphaleonis.Win32.Filesystem; +using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + public static partial class Local { /// [AlphaFS] Enumerates all available devices on the local host. - /// instances of type from the local host. + /// Returns an collection from the local host. /// One of the devices. [SecurityCritical] public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) @@ -42,7 +44,12 @@ public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) /// [AlphaFS] Enumerates all available devices of type on the local or remote host. - /// instances of type for the specified . + /// Returns an collection for the specified . + /// + /// 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 + /// /// The name of the local or remote host on which the device resides. null refers to the local host. /// One of the devices. [SecurityCritical] @@ -52,27 +59,27 @@ public static IEnumerable EnumerateDevices(string hostName, DeviceGu } - - - /// [AlphaFS] Enumerates all available devices on the local or remote host. + /// [AlphaFS] Enumerates all available devices of type on the local or remote host. + /// Returns an collection for the specified . + /// + /// 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 + /// + /// The name of the local or remote host on which the device resides. null refers to the local host. + /// One of the devices. + /// true to retrieve all device properties. [SecurityCritical] internal static IEnumerable 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); + Utils.IsValidHandle(safeMachineHandle, lastError); var classGuid = new Guid(Utils.GetEnumDescription(deviceGuid)); @@ -83,7 +90,7 @@ internal static IEnumerable EnumerateDevicesCore(string hostName, De using (safeMachineHandle) using (var safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref classGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_PRESENT | NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_DEVICEINTERFACE, IntPtr.Zero, hostName, IntPtr.Zero)) { - NativeMethods.IsValidHandle(safeHandle, Marshal.GetLastWin32Error()); + Utils.IsValidHandle(safeHandle, Marshal.GetLastWin32Error()); uint memberInterfaceIndex = 0; var interfaceStructSize = (uint) Marshal.SizeOf(typeof(NativeMethods.SP_DEVICE_INTERFACE_DATA)); @@ -162,7 +169,7 @@ private static string GetDeviceInstanceId(SafeCmConnectMachineHandle safeMachine /// Builds a Device Interface Detail Data structure. - /// An initialized NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA instance. + /// Returns an initialized NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA instance. [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) { @@ -237,7 +244,7 @@ private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMet return null; - bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, property.ToString()); + bufferSize = Utils.GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, property.ToString()); } } diff --git a/AlphaFS/Device/Device.InvokeDeviceIoData.cs b/AlphaFS/Device/Local.InvokeDeviceIoData.cs similarity index 84% rename from AlphaFS/Device/Device.InvokeDeviceIoData.cs rename to AlphaFS/Device/Local.InvokeDeviceIoData.cs index ad1d36677..94bad5199 100644 --- a/AlphaFS/Device/Device.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Local.InvokeDeviceIoData.cs @@ -23,18 +23,19 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; +using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + public static partial class Local { /// Invokes InvokeIoControl with the specified input and specified size. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] - private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string pathForException, int size = -1) + internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string pathForException, int size = -1) { - NativeMethods.IsValidHandle(safeHandle); + Utils.IsValidHandle(safeHandle); var bufferSize = size > -1 ? size : Marshal.SizeOf(anyObject); @@ -65,7 +66,7 @@ private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle return null; } - bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); + bufferSize = Utils.GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); } } } diff --git a/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs similarity index 76% rename from AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs rename to AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs index 71ceb9637..9a5b6a3e2 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs @@ -23,24 +23,26 @@ using System.Collections.Generic; using System.Linq; using System.Security; +using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - /// Provides access to information of a physical disk. + /// [AlphaFS] Provides access to information of a physical disk. [Serializable] [SecurityCritical] public sealed class PhysicalDiskInfo { #region Constructors - /// Initializes a PhysicalDiskInfo instance. + /// [AlphaFS] Initializes an empty PhysicalDiskInfo instance. public PhysicalDiskInfo() { } - /// Initializes a PhysicalDiskInfo instance. - public PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) + /// [AlphaFS] Initializes a PhysicalDiskInfo instance. + /// An initialized instance. + internal PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) { CopyTo(physicalDiskInfo, this); } @@ -55,23 +57,23 @@ public PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) /// The path to the device. - /// A string that represents the path to the device. + /// Returns a string that represents the path to the device. /// A drive path such as: C:, D:\, /// a volume path such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// or a string. + /// or a string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string. /// public string DevicePath { get; internal set; } - /// The logical drives that are located on the physical disk. + /// An of logical drives that are located on the physical disk. public ICollection LogicalDrives { get; internal set; } /// The "FriendlyName" of the physical disk. public string Name { get; internal set; } - - /// The partition index numbers that are located on the physical disk. + + /// An of partition index numbers that are located on the physical disk. public ICollection PartitionIndexes { get; internal set; } @@ -91,11 +93,11 @@ public PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) public StoragePartitionInfo StoragePartitionInfo { get; internal set; } - /// A collection of volume GUID strings of volumes that are located on the physical disk. + /// An of volume strings of volumes that are located on the physical disk. public ICollection VolumeGuids { get; internal set; } - ///// A collection of volume label strings of volumes that are located on the physical disk. + ///// An of volume label strings of volumes that are located on the physical disk. //public ICollection VolumeLabels { get; internal set; } #endregion // Properties @@ -104,17 +106,23 @@ public PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) #region Methods /// Checks if the volume or logical drive is located on the physical disk. - /// A drive path such as: C, C: or C:\. - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// - /// true if the volume or logical drive is located on the physical disk, false otherwise.. + /// true if the volume or logical drive is located on the physical disk; otherwise, false. + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// public bool ContainsVolume(string devicePath) { bool isDrive; bool isVolume; bool isDeviceInfo; - devicePath = Device.ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + devicePath = FileSystemHelper.ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); if (isDrive && null != LogicalDrives) @@ -130,7 +138,7 @@ public bool ContainsVolume(string devicePath) /// Returns the "FriendlyName" of the physical disk. - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return Name ?? DevicePath; @@ -158,7 +166,7 @@ public override bool Equals(object obj) /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { return null != DevicePath ? DevicePath.GetHashCode() : 0; diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs similarity index 92% rename from AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs rename to AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 59d56ac78..0382fa6cd 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -24,13 +24,16 @@ using System.IO; using System.Linq; using System.Security; +using Alphaleonis.Win32.Filesystem; +using DriveInfo = Alphaleonis.Win32.Filesystem.DriveInfo; +using Path = Alphaleonis.Win32.Filesystem.Path; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + public static partial class Local { /// [AlphaFS] Enumerates the physical disks on the Computer, populated with volume- and logical drive information. - /// An collection that represents the physical disks on the Computer. + /// Returns an collection that represents the physical disks on the Computer. [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() { @@ -41,7 +44,7 @@ public static IEnumerable EnumeratePhysicalDisks() /// [AlphaFS] Enumerates the physical disks on the Computer, populated with volume- and logical drive information. - /// An collection that represents the physical disks on the Computer. + /// Returns an collection that represents the physical disks on the Computer. [SecurityCritical] internal static IEnumerable EnumeratePhysicalDisksCore(bool isElevated) { @@ -100,7 +103,7 @@ private static void PopulateVolumeDetails(PhysicalDiskInfo pDiskInfo, int partit pDiskInfo.PartitionIndexes.Add(partitionNumber); - // Add device volume GUIDs. + // Add device volume s. if (null == pDiskInfo.VolumeGuids) pDiskInfo.VolumeGuids = new Collection(); diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs similarity index 74% rename from AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs rename to AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index 469593f39..79ed01a7e 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -25,24 +25,25 @@ using System.Security; using System.Security.AccessControl; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + public static partial class Local { - /// [AlphaFS] Retrieves the physical disk on the Computer that is related to the logical drive name, volume GUID or . - /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks, associated volumes and logical drives. - /// Instead, use method and property and/or . - /// - /// A instance that represents the physical disk on the Computer or null on error/no data available. + /// [AlphaFS] Retrieves the physical disk on the Computer that is related to the logical drive name, volume or . + /// Returns a instance that represents the physical disk on the Computer or null on error/no data available. + /// + /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. + /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks, associated volumes and logical drives. + /// Instead, use method and property and/or . + /// /// /// /// /// - /// A disk path such as: \\.\PhysicalDrive0s - /// A drive path such as: C, C: or C:\. - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// [SecurityCritical] public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) @@ -53,7 +54,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) var isElevated = Security.ProcessContext.IsElevatedProcess; - devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + devicePath = FileSystemHelper.ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, devicePath); @@ -65,7 +66,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) // Use logical drive path. if (isDrive) - GetDevicePath(devicePath, out devicePath); + FileSystemHelper.GetDevicePath(devicePath, out devicePath); var pDiskInfo = isDeviceInfo @@ -88,10 +89,13 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) } - /// [AlphaFS] Retrieves the physical disk on the Computer that is related to the logical drive name, volume GUID or . - /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// + /// [AlphaFS] Retrieves the physical disk on the Computer that is related to the logical drive name, volume or . /// A instance that represents the physical disk on the Computer or null on error/no data available. + /// + /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. + /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks, associated volumes and logical drives. + /// Instead, use method and property and/or . + /// /// /// /// @@ -99,9 +103,9 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\. - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// /// A instance. /// A instance. @@ -139,7 +143,7 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string if (isElevated) { - using (var safeHandle = OpenPhysicalDisk(devicePath, FileSystemRights.Read)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(devicePath, FileSystemRights.Read)) { pDiskInfo.StorageAdapterInfo = GetStorageAdapterInfoNative(safeHandle, devicePath); diff --git a/AlphaFS/Device/Storage/StorageAdapterInfo.cs b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs similarity index 95% rename from AlphaFS/Device/Storage/StorageAdapterInfo.cs rename to AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs index 7de51a8ad..f8a1fd6e2 100644 --- a/AlphaFS/Device/Storage/StorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs @@ -23,8 +23,9 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; +using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// [AlphaFS] Provides access to adapter information of a storage device. [Serializable] @@ -33,7 +34,7 @@ public sealed class StorageAdapterInfo { #region Constructors - /// [AlphaFS] Initializes a StorageAdapterInfo instance. + /// [AlphaFS] Initializes an empty StorageAdapterInfo instance. public StorageAdapterInfo() { BusType = StorageBusType.Unknown; @@ -100,7 +101,7 @@ internal StorageAdapterInfo(NativeMethods.STORAGE_ADAPTER_DESCRIPTOR adapter) : #region Methods /// Returns storage device as: "BusType MaximumTransferBytes". - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return BusType == StorageBusType.Unknown ? StorageBusType.Unknown.ToString() : string.Format(CultureInfo.CurrentCulture, "{0} {1}", (BusType.ToString() + " " ).Trim(), Utils.UnitSizeToText(MaximumTransferBytes)); @@ -129,7 +130,7 @@ public override bool Equals(object obj) /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { unchecked diff --git a/AlphaFS/Device/Storage/StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs similarity index 95% rename from AlphaFS/Device/Storage/StorageDeviceInfo.cs rename to AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 96e10bd87..b9705ea1f 100644 --- a/AlphaFS/Device/Storage/StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -23,8 +23,9 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; +using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// [AlphaFS] Provides access to information of a storage device. [Serializable] @@ -33,7 +34,7 @@ public sealed class StorageDeviceInfo { #region Constructors - /// [AlphaFS] Initializes a StorageDeviceInfo instance. + /// [AlphaFS] Initializes an empty StorageDeviceInfo instance. public StorageDeviceInfo() { DeviceType = StorageDeviceType.Unknown; @@ -108,7 +109,7 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() #region Methods /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "{0} {1}:{2} {3}", DeviceType.ToString(), DeviceNumber.ToString(CultureInfo.InvariantCulture), PartitionNumber.ToString(CultureInfo.InvariantCulture), (VendorId + " " + ProductId + " " + ProductRevision).Trim()).Trim(); @@ -135,7 +136,7 @@ public override bool Equals(object obj) /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { unchecked diff --git a/AlphaFS/Device/Storage/StorageGptPartitionInfo.cs b/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs similarity index 95% rename from AlphaFS/Device/Storage/StorageGptPartitionInfo.cs rename to AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs index 1f6c73337..859a87a08 100644 --- a/AlphaFS/Device/Storage/StorageGptPartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs @@ -23,8 +23,10 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; +using Alphaleonis.Win32.Filesystem; +using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// [AlphaFS] Provides access to GPT partition information of a storage device. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt"), Serializable] @@ -41,7 +43,7 @@ public sealed class StorageGptPartitionInfo #region Constructors - /// [AlphaFS] Initializes a StorageGptPartitionInfo instance. + /// [AlphaFS] Initializes an empty StorageGptPartitionInfo instance. public StorageGptPartitionInfo() { PartitionNumber = -1; @@ -176,7 +178,7 @@ internal set #region Methods /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "{0} {1}", Description, Attributes.ToString()).Trim(); @@ -202,7 +204,7 @@ public override bool Equals(object obj) /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { unchecked diff --git a/AlphaFS/Device/Storage/StorageMbrPartitionInfo.cs b/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs similarity index 94% rename from AlphaFS/Device/Storage/StorageMbrPartitionInfo.cs rename to AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs index 47c3c6eee..2f9549886 100644 --- a/AlphaFS/Device/Storage/StorageMbrPartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs @@ -23,8 +23,10 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; +using Alphaleonis.Win32.Filesystem; +using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// [AlphaFS] Provides access to MBR partition information of a storage device. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr"), Serializable] @@ -41,7 +43,7 @@ public sealed class StorageMbrPartitionInfo #region Constructors - /// [AlphaFS] Initializes a StorageMbrPartitionInfo instance. + /// [AlphaFS] Initializes an empty StorageMbrPartitionInfo instance. public StorageMbrPartitionInfo() { HiddenSectors = -1; @@ -149,7 +151,7 @@ internal set #region Methods /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "BootIndicator: {0}, Type: {1}, RecognizedPartition: {2}", BootIndicator.ToString(), DiskPartitionType.ToString(), RecognizedPartition.ToString()).Trim(); @@ -175,7 +177,7 @@ public override bool Equals(object obj) /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { unchecked diff --git a/AlphaFS/Device/Storage/StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs similarity index 93% rename from AlphaFS/Device/Storage/StoragePartitionInfo.cs rename to AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index 82b3f9d92..8a76a1d9b 100644 --- a/AlphaFS/Device/Storage/StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -26,8 +26,10 @@ using System.Globalization; using System.Linq; using System.Security; +using Alphaleonis.Win32.Filesystem; +using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// [AlphaFS] Provides access to partition information of a storage device. [Serializable] @@ -43,7 +45,7 @@ public sealed class StoragePartitionInfo #region Constructors - /// [AlphaFS] Initializes a StoragePartitionInfo instance. + /// [AlphaFS] Initializes an empty StoragePartitionInfo instance. public StoragePartitionInfo() { DeviceNumber = -1; @@ -108,7 +110,7 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods MbrPartitionInfo.Add(new StorageMbrPartitionInfo(partition)); } - + // Update to reflect the real number of used partition entries. PartitionCount = MbrPartitionInfo.Count; @@ -116,7 +118,10 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods } - IsOnDynamicDisk = null != GptPartitionInfo && GptPartitionInfo.Any(partition => partition.PartitionType == PartitionType.LdmData) || + IsOnDynamicDisk = null != GptPartitionInfo && GptPartitionInfo.Any(partition => + + partition.PartitionType == PartitionType.LdmData || partition.PartitionType == PartitionType.LdmMetadata) || + null != MbrPartitionInfo && MbrPartitionInfo.Any(partition => partition.DiskPartitionType == DiskPartitionType.Ldm); } @@ -209,7 +214,7 @@ internal set public int PartitionCount { get; private set; } - /// The format of the partition. For a list of values, see . + /// The format of the partition. For a list of values, see . public PartitionStyle PartitionStyle { get; private set; } @@ -222,7 +227,7 @@ internal set #region Methods /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "{0}:{1} {2}", @@ -251,7 +256,7 @@ public override string ToString() ///// Serves as a hash function for a particular type. - ///// A hash code for the current Object. + ///// Returns a hash code for the current Object. //public override int GetHashCode() //{ // unchecked diff --git a/AlphaFS/Device/Device.GetDeviceIoData.cs b/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs similarity index 90% rename from AlphaFS/Device/Device.GetDeviceIoData.cs rename to AlphaFS/Device/Storage/Local.GetDeviceIoData.cs index b4175ada3..6ddd49176 100644 --- a/AlphaFS/Device/Device.GetDeviceIoData.cs +++ b/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs @@ -23,17 +23,18 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; +using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + public static partial class Local { [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) { - NativeMethods.IsValidHandle(safeHandle); + Utils.IsValidHandle(safeHandle); var bufferSize = size > -1 ? size : Marshal.SizeOf(typeof(T)); @@ -64,7 +65,7 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa return null; } - bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); + bufferSize = Utils.GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); } } } diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs similarity index 82% rename from AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs rename to AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index fa1b39e84..c737e3864 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -24,36 +24,38 @@ using System.Globalization; using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; +using Alphaleonis.Win32.Filesystem; +using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + public static partial class Local { - /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume or . /// Calling this method requires an elevated state. /// - /// A instance that represent the storage device on the Computer that is related to . + /// Returns a instance that represent the storage device on the Computer that is related to . /// /// /// /// /// /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\. - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) { string unused; - var pathToDevice = GetDevicePath(devicePath, out unused); + var pathToDevice = FileSystemHelper.GetDevicePath(devicePath, out unused); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; - using (var safeHandle = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read)) return GetStorageAdapterInfoNative(safeHandle, devicePath); } @@ -92,9 +94,9 @@ private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle saf pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - safeHandleRetry = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); + safeHandleRetry = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); - isRetry = NativeMethods.IsValidHandle(safeHandleRetry, false); + isRetry = Utils.IsValidHandle(safeHandleRetry, false); } diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs similarity index 86% rename from AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs rename to AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index 715d8bd82..5c2ac804b 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -24,27 +24,28 @@ using System.Globalization; using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; +using Alphaleonis.Win32.Filesystem; +using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + public static partial class Local { - /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . - /// + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume or . + /// Returns a instance that represent the storage device on the Computer that is related to . + /// /// When this method is called from a non-elevated state, only the properties and are useful. /// The remaining properties are meaningless and can only be obtained by calling the method from an elevated state. - /// - /// - /// A instance that represent the storage device on the Computer that is related to . + /// /// /// /// /// /// /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\. - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { @@ -54,29 +55,27 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) - /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume GUID or . - /// + /// Returns a instance that represent the storage device on the Computer that is related to . + /// /// When this method is called from a non-elevated state, only the properties and are useful. /// The remaining properties are meaningless and can only be obtained by calling the method from an elevated state. - /// - /// - /// A instance that represent the storage device on the Computer that is related to . + /// /// /// /// /// /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// - /// A disk path such as: \\.\PhysicalDrive0s - /// A drive path such as: C, C: or C:\. - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, string devicePath) { string unused; - var pathToDevice = GetDevicePath(devicePath, out unused); + var pathToDevice = FileSystemHelper.GetDevicePath(devicePath, out unused); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; @@ -89,7 +88,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri // Get storage device info. - using (var safeHandle = OpenPhysicalDisk(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) { var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); @@ -118,7 +117,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri if (null != storageDeviceInfo && isElevated) { - using (var safeHandle = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read)) storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, pathToDevice, storageDeviceInfo); } @@ -162,9 +161,9 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - safeHandleRetry = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); + safeHandleRetry = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); - isRetry = NativeMethods.IsValidHandle(safeHandleRetry, false); + isRetry = Utils.IsValidHandle(safeHandleRetry, false); } diff --git a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs similarity index 86% rename from AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs rename to AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index edb921e5f..e746faead 100644 --- a/AlphaFS/Device/PhysicalDiskInfo/Device.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -25,34 +25,36 @@ using System.Runtime.InteropServices; using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; +using Alphaleonis.Win32.Filesystem; +using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + public static partial class Local { - /// Retrieves information about the partitions on a disk and the features of each partition. - /// A instance that represent the partition info on the Computer that is related to . + /// [AlphaFS] Retrieves information about the partitions on a disk and the features of each partition. + /// Returns a instance that represent the partition info on the Computer that is related to . /// /// /// /// /// /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\. - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) { string unused; - var pathToDevice = GetDevicePath(devicePath, out unused); + var pathToDevice = FileSystemHelper.GetDevicePath(devicePath, out unused); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; - using (var safeHandle = OpenPhysicalDisk(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) return GetStoragePartitionInfoNative(safeHandle, devicePath); } @@ -85,9 +87,9 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - safeHandleRetry = OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); + safeHandleRetry = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); - isRetry = NativeMethods.IsValidHandle(safeHandleRetry, false); + isRetry = Utils.IsValidHandle(safeHandleRetry, false); } @@ -102,23 +104,23 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandleRetry.Close(); - var drive = safeBuffer.PtrToStructure(); + var layout = safeBuffer.PtrToStructure(); // Sanity check. - if (drive.PartitionCount <= 256) + if (layout.PartitionCount <= 256) { var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 - var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; + var partitions = new NativeMethods.PARTITION_INFORMATION_EX[layout.PartitionCount]; - for (var i = 0; i <= drive.PartitionCount - 1; i++) + for (var i = 0; i <= layout.PartitionCount - 1; i++) partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); var disk = GetDiskGeometryExNative(safeHandle, pathToDevice); - return new StoragePartitionInfo(disk, drive, partitions); + return new StoragePartitionInfo(disk, layout, partitions); } return null; @@ -230,7 +232,7 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHa return new NativeMethods.DISK_GEOMETRY_EX(); - bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); + bufferSize = Utils.GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); } } } diff --git a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs b/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs similarity index 91% rename from AlphaFS/Device/Device.GetVolumeDiskExtents.cs rename to AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs index 41e09a79b..375900541 100644 --- a/AlphaFS/Device/Device.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs @@ -22,10 +22,11 @@ using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; +using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { - public static partial class Device + public static partial class Local { /// Retrieves the physical location of a specified volume on one or more disks. private static NativeMethods.VOLUME_DISK_EXTENTS? GetVolumeDiskExtents(SafeFileHandle safeHandle, string pathForException) @@ -58,7 +59,7 @@ public static partial class Device } - bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); + bufferSize = Utils.GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); } } } diff --git a/AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs b/AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs index fb35794b3..85237fdaf 100644 --- a/AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs +++ b/AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs @@ -31,9 +31,9 @@ public static partial class Volume /// /// The calling application must have FILE_LIST_DIRECTORY access rights for this directory. /// - /// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". + /// A path to a drive. For example: C:\, \\server\share, or \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// - /// A class instance. + /// Returns a class instance. [SecurityCritical] public static DiskSpaceInfo GetDiskFreeSpace(string drivePath) { @@ -47,13 +47,13 @@ public static DiskSpaceInfo GetDiskFreeSpace(string drivePath) /// /// The calling application must have FILE_LIST_DIRECTORY access rights for this directory. /// - /// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". + /// A path to a drive. For example: C:\, \\server\share, or \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// /// /// null gets both size- and disk cluster information. true Get only disk cluster information, /// false Get only size information. /// - /// A class instance. + /// Returns a class instance. [SecurityCritical] public static DiskSpaceInfo GetDiskFreeSpace(string drivePath, bool? spaceInfoType) { diff --git a/AlphaFS/Device/Volume/Volume.DriveType.cs b/AlphaFS/Device/Volume/Volume.DriveType.cs index 024f43a4b..8dfb8b23e 100644 --- a/AlphaFS/Device/Volume/Volume.DriveType.cs +++ b/AlphaFS/Device/Volume/Volume.DriveType.cs @@ -28,7 +28,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Volume { /// [AlphaFS] Determines the disk , based on the root of the current directory. - /// A enum value. + /// Returns a enum value. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public static DriveType GetCurrentDriveType() @@ -38,8 +38,8 @@ public static DriveType GetCurrentDriveType() /// [AlphaFS] Determines the disk . - /// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\" - /// A enum value. + /// A path to a drive. For example: C:\, \\server\share, or \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// Returns a enum value. [SecurityCritical] public static DriveType GetDriveType(string drivePath) { diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs index 44eda1b85..4a1800053 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs @@ -29,11 +29,11 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { - /// [AlphaFS] Returns an enumerable collection of of all mounted folders (volume mount points) on the specified volume. + /// [AlphaFS] Returns an collection of all mounted folders (volume mount points) on the specified volume. /// /// /// A containing the volume . - /// An enumerable collection of of all volume mount points on the specified volume. + /// Returns an collection of all volume mount points on the specified volume. [SecurityCritical] public static IEnumerable EnumerateVolumeMountPoints(string volumeGuid) { @@ -56,7 +56,7 @@ public static IEnumerable EnumerateVolumeMountPoints(string volumeGuid) { var lastError = Marshal.GetLastWin32Error(); - if (!NativeMethods.IsValidHandle(handle, false)) + if (!Utils.IsValidHandle(handle, false)) { switch ((uint)lastError) { @@ -79,7 +79,7 @@ public static IEnumerable EnumerateVolumeMountPoints(string volumeGuid) 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)) + if (!Utils.IsValidHandle(handle, lastError, volumeGuid, throwException)) yield break; yield return buffer.ToString(); diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs index 4677c17fd..570bef8ec 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs @@ -29,11 +29,11 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { - /// [AlphaFS] Returns an enumerable collection of drive letters and mounted folder paths for the specified volume. - /// An enumerable collection of containing the path names for the specified volume. + /// [AlphaFS] Returns an collection of drive letters and mounted folder paths for the specified volume. + /// RReturns an collection of path names for the specified volume. /// /// - /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. + /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ [SecurityCritical] public static IEnumerable EnumerateVolumePathNames(string volumeGuid) { diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs index 3c029cdcb..454b8ca8e 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs @@ -28,8 +28,8 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { - /// [AlphaFS] Returns an enumerable collection of volumes on the computer. - /// An enumerable collection of volume names on the computer. + /// [AlphaFS] Returns an collection of volumes on the Computer. + /// Returns an collection of volume names on the Computer. [SecurityCritical] public static IEnumerable EnumerateVolumes() { @@ -42,7 +42,7 @@ public static IEnumerable EnumerateVolumes() var throwException = lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_NO_MORE_FILES && lastError != Win32Errors.ERROR_MORE_DATA; - if (!NativeMethods.IsValidHandle(handle, lastError, string.Empty, throwException)) + if (!Utils.IsValidHandle(handle, lastError, string.Empty, throwException)) yield break; yield return buffer.ToString(); @@ -54,7 +54,7 @@ public static IEnumerable EnumerateVolumes() throwException = lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_NO_MORE_FILES && lastError != Win32Errors.ERROR_MORE_DATA; - if (!NativeMethods.IsValidHandle(handle, lastError, string.Empty, throwException)) + if (!Utils.IsValidHandle(handle, lastError, string.Empty, throwException)) yield break; yield return buffer.ToString(); diff --git a/AlphaFS/Device/Volume/Volume.GetDriveFormat.cs b/AlphaFS/Device/Volume/Volume.GetDriveFormat.cs index 51c5ca4e0..8288ad323 100644 --- a/AlphaFS/Device/Volume/Volume.GetDriveFormat.cs +++ b/AlphaFS/Device/Volume/Volume.GetDriveFormat.cs @@ -29,7 +29,7 @@ public static partial class Volume /// [AlphaFS] Gets the name of the file system, such as: "NTFS" or "FAT32". /// Use DriveFormat to determine what formatting a drive uses. /// - /// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". + /// A path to a drive. For example: C:\, \\server\share, or \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// /// The name of the file system on the specified drive or null on failure or if not available. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] diff --git a/AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs b/AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs index e6c139d4b..54e433f1e 100644 --- a/AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs +++ b/AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { - /// [AlphaFS] Gets the drive letter from an MS-DOS device name. For example: "\Device\HarddiskVolume2" returns "C:\". + /// [AlphaFS] Gets the drive letter from an MS-DOS device name. For example: \Device\HarddiskVolume2 returns C:\ /// An MS-DOS device name. /// The drive letter from an MS-DOS device name. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Nt")] diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs index 39da2a14b..8a63ff6f7 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs @@ -28,7 +28,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Volume { /// [AlphaFS] Retrieves the Win32 Device name from the Volume name. - /// The Win32 Device name from the Volume name, for example: "\Device\HarddiskVolume2", or null on error or if unavailable. + /// The Win32 Device name from the Volume name, for example: \Device\HarddiskVolume2, or null on error or if unavailable. /// This is the same method as . /// /// diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs index 229a351d7..777d175bf 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs @@ -30,7 +30,7 @@ public static partial class Volume { /// [AlphaFS] Gets the shortest display name for the specified . /// This method basically returns the shortest string returned by - /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. + /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// /// The shortest display name for the specified volume found, or null if no display names were found. /// diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs b/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs index 47c92d20d..fd8349353 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { - /// [AlphaFS] Retrieves a volume path for the volume that is associated with the specified volume mount point (drive letter, volume GUID path, or mounted folder). + /// [AlphaFS] Retrieves a volume path for the volume that is associated with the specified volume mount point (drive letter, volume path, or mounted folder). /// The unique volume name of the form: "\\?\Volume{GUID}\". /// SMB does not support volume management functions. /// Mount points aren't supported by ReFS volumes. diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeGuidForNtDeviceName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeGuidForNtDeviceName.cs index 398248904..a801bb52b 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeGuidForNtDeviceName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeGuidForNtDeviceName.cs @@ -27,12 +27,11 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { - /// [AlphaFS] - /// Tranlates DosDevicePath to a Volume GUID. For example: "\Device\HarddiskVolumeX\path\filename.ext" can translate to: "\path\ - /// filename.ext" or: "\\?\Volume{GUID}\path\filename.ext". + /// [AlphaFS] Tranlates DosDevicePath to a volume . + /// For example: \Device\HarddiskVolumeX\path\filename.ext can translate to: \path\filename.ext or: \\?\Volume{GUID}\path\filename.ext /// /// A DosDevicePath, for example: \Device\HarddiskVolumeX\path\filename.ext. - /// A translated dos path. + /// Returns a translated dos path. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Nt")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nt")] public static string GetVolumeGuidForNtDeviceName(string dosDevice) diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs b/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs index 4396aa012..dcbd618f7 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs @@ -28,7 +28,7 @@ public static partial class Volume { /// [AlphaFS] Retrieves information about the file system and volume associated with the specified root file or directorystream. /// A path that contains the root directory. - /// A instance describing the volume associatied with the specified root directory. + /// Returns a instance describing the volume associatied with the specified root directory. [SecurityCritical] public static VolumeInfo GetVolumeInfo(string volumePath) { @@ -38,7 +38,7 @@ public static VolumeInfo GetVolumeInfo(string volumePath) /// [AlphaFS] Retrieves information about the file system and volume associated with the specified root file or directorystream. /// An instance to a handle. - /// A instance describing the volume associatied with the specified root directory. + /// Returns a instance describing the volume associatied with the specified root directory. [SecurityCritical] public static VolumeInfo GetVolumeInfo(SafeFileHandle volumeHandle) { diff --git a/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs b/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs index 0a13d8c2a..605a8dc4a 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs @@ -30,10 +30,10 @@ public static partial class Volume { /// [AlphaFS] Retrieves the volume mount point where the specified path is mounted. /// - /// The path to the volume, for example: "C:\Windows". + /// The path to the volume, for example: C:\Windows. /// /// Returns the nearest volume root path for a given directory. - /// The volume path name, for example: "C:\Windows" returns: "C:\". + /// The volume path name, for example: C:\Windows returns: C:\ /// [SecurityCritical] public static string GetVolumePathName(string path) diff --git a/AlphaFS/Device/Volume/Volume.IsReady.cs b/AlphaFS/Device/Volume/Volume.IsReady.cs index e976334b1..f4301c2a4 100644 --- a/AlphaFS/Device/Volume/Volume.IsReady.cs +++ b/AlphaFS/Device/Volume/Volume.IsReady.cs @@ -27,7 +27,7 @@ public static partial class Volume { /// [AlphaFS] Gets a value indicating whether a drive is ready. /// - /// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". + /// A path to a drive. For example: C:\, \\server\share, or \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// /// true if is ready; otherwise, false. [SecurityCritical] diff --git a/AlphaFS/Device/Volume/Volume.IsSameVolume.cs b/AlphaFS/Device/Volume/Volume.IsSameVolume.cs index 56e805c86..b9a062b99 100644 --- a/AlphaFS/Device/Volume/Volume.IsSameVolume.cs +++ b/AlphaFS/Device/Volume/Volume.IsSameVolume.cs @@ -30,7 +30,7 @@ public static partial class Volume /// [AlphaFS] Determines whether the volume of two file system objects is the same, by comparing their serial numbers. /// The first filesystem object with full path information. /// The second file system object with full path information. - /// true if both filesytem objects reside on the same volume, false otherwise. + /// true if both filesytem objects reside on the same volume; otherwise, false. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] public static bool IsSameVolume(string path1, string path2) diff --git a/AlphaFS/Device/Volume/Volume.IsVolume.cs b/AlphaFS/Device/Volume/Volume.IsVolume.cs index 8e29d1067..9c0533b46 100644 --- a/AlphaFS/Device/Volume/Volume.IsVolume.cs +++ b/AlphaFS/Device/Volume/Volume.IsVolume.cs @@ -27,9 +27,9 @@ public static partial class Volume { /// [AlphaFS] Determines whether the specified volume name is a defined volume on the current computer. /// - /// A path to a volume. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". + /// A path to a volume. For example: C:\, \\server\share, or \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// - /// true on success, false otherwise. + /// true on success; otherwise, false. [SecurityCritical] public static bool IsVolume(string volumeMountPoint) { diff --git a/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs b/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs index 6592253c0..b3eb53f91 100644 --- a/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs +++ b/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs @@ -32,7 +32,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Volume { /// [AlphaFS] Retrieves a sorted list of all existing MS-DOS device names. - /// An sorted list of all existing MS-DOS device names. + /// Returns an sorted collection of all existing MS-DOS device names. [SecurityCritical] public static IEnumerable QueryAllDosDevices() { @@ -64,7 +64,7 @@ public static string QueryDosDevice(string deviceName) /// [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. - /// An sorted list of all existing MS-DOS device names or the . + /// Returns an sorted collection of all existing MS-DOS device names or the . /// /// /// An MS-DOS device name string specifying the target of the query, such as: "C:", "D:" or "\\?\Volume{GUID}". diff --git a/AlphaFS/Device/Volume/Volume.VolumeLabel.cs b/AlphaFS/Device/Volume/Volume.VolumeLabel.cs index 3be4de8b0..a523b4621 100644 --- a/AlphaFS/Device/Volume/Volume.VolumeLabel.cs +++ b/AlphaFS/Device/Volume/Volume.VolumeLabel.cs @@ -51,7 +51,7 @@ public static void DeleteVolumeLabel(string rootPathName) /// [AlphaFS] Retrieve the label of a file system volume. /// - /// A path to a volume. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\". + /// A path to a volume. For example: C:\, \\server\share, or \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// /// The the label of the file system volume. This function can return string.Empty since a volume label is generally not mandatory. [SecurityCritical] @@ -81,7 +81,7 @@ public static void SetCurrentVolumeLabel(string volumeName) /// [AlphaFS] Sets the label of a file system volume. /// - /// A path to a volume. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\" + /// A path to a volume. For example: C:\, \\server\share, or \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// If this parameter is null, the function uses the current drive. /// /// diff --git a/AlphaFS/Device/Volume/VolumeInfo.cs b/AlphaFS/Device/Volume/VolumeInfo.cs index 0e718079e..a914c8a1b 100644 --- a/AlphaFS/Device/Volume/VolumeInfo.cs +++ b/AlphaFS/Device/Volume/VolumeInfo.cs @@ -99,7 +99,7 @@ public VolumeInfo(string driveName, bool refresh, bool continueOnException) : th [SecurityCritical] public VolumeInfo(SafeFileHandle volumeHandle) { - NativeMethods.IsValidHandle(volumeHandle); + Utils.IsValidHandle(volumeHandle); _volumeHandle = volumeHandle; } @@ -122,7 +122,7 @@ public VolumeInfo(SafeFileHandle volumeHandle, bool refresh, bool continueOnExce /// Returns the full path of the volume. - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return Guid; @@ -177,7 +177,7 @@ public bool DirectAccess public string FullPath { get; private set; } - /// The volume GUID. + /// The volume . [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public string Guid { diff --git a/AlphaFS/Filesystem/ByHandleFileInfo.cs b/AlphaFS/Filesystem/ByHandleFileInfo.cs index 461810f67..76e375d43 100644 --- a/AlphaFS/Filesystem/ByHandleFileInfo.cs +++ b/AlphaFS/Filesystem/ByHandleFileInfo.cs @@ -37,8 +37,8 @@ internal ByHandleFileInfo(NativeMethods.BY_HANDLE_FILE_INFORMATION fibh) LastWriteTimeUtc = DateTime.FromFileTimeUtc(fibh.ftLastWriteTime); Attributes = fibh.dwFileAttributes; - FileIndex = NativeMethods.ToLong(fibh.nFileIndexHigh, fibh.nFileIndexLow); - FileSize = NativeMethods.ToLong(fibh.nFileSizeHigh, fibh.nFileSizeLow); + FileIndex = Utils.ToLong(fibh.nFileIndexHigh, fibh.nFileIndexLow); + FileSize = Utils.ToLong(fibh.nFileSizeHigh, fibh.nFileSizeLow); NumberOfLinks = (int) fibh.nNumberOfLinks; VolumeSerialNumber = fibh.dwVolumeSerialNumber; } diff --git a/AlphaFS/Device/ChangeErrorMode.cs b/AlphaFS/Filesystem/ChangeErrorMode.cs similarity index 100% rename from AlphaFS/Device/ChangeErrorMode.cs rename to AlphaFS/Filesystem/ChangeErrorMode.cs diff --git a/AlphaFS/Filesystem/CopyMoveResult.cs b/AlphaFS/Filesystem/CopyMoveResult.cs index 2fabf885e..6ee1e425b 100644 --- a/AlphaFS/Filesystem/CopyMoveResult.cs +++ b/AlphaFS/Filesystem/CopyMoveResult.cs @@ -61,7 +61,7 @@ private CopyMoveResult(string source, string destination) /// Indicates the full path to the destination file or directory. /// >When true the action is a Copy, Move otherwise. /// When true indicates the sources is a directory; file otherwise. - /// true if original Timestamps must be preserved, false otherwise. This parameter is ignored for move operations. + /// true if original Timestamps must be preserved; otherwise, false. This parameter is ignored for move operations. /// When true indicates the Move action used a fallback of Copy + Delete actions. public CopyMoveResult(string source, string destination, bool isCopy, bool isFolder, bool preserveDates, bool emulatedMove) : this(source, destination) { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Compress.cs b/AlphaFS/Filesystem/Directory Class/Directory.Compress.cs index 49287a7e9..401863f9b 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Compress.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Compress.cs @@ -343,10 +343,10 @@ internal static void CompressDecompressCore(KernelTransaction transaction, strin // Traverse the source folder, processing files and folders. foreach (var fsei in EnumerateFileSystemEntryInfosCore(null, transaction, pathLp, searchPattern, null, options | DirectoryEnumerationOptions.AsLongPath, filters, PathFormat.LongFullPath)) - Device.ToggleCompressionCore(transaction, fsei, compress, PathFormat.LongFullPath); + Device.FileSystemHelper.ToggleCompressionCore(transaction, fsei, compress, PathFormat.LongFullPath); // Compress the root directory, the given path. - Device.ToggleCompressionCore(transaction, pathLp, compress, PathFormat.LongFullPath); + Device.FileSystemHelper.ToggleCompressionCore(transaction, pathLp, compress, PathFormat.LongFullPath); } } } diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs index 76766f3ac..e1f81a1f2 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs @@ -33,7 +33,7 @@ public static partial class Directory /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. @@ -54,7 +54,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath) /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. @@ -76,7 +76,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Pat /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. @@ -98,7 +98,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, boo /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. @@ -121,7 +121,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, boo /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. @@ -143,7 +143,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is not allowed. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. @@ -166,7 +166,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. @@ -189,7 +189,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. @@ -215,7 +215,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -238,7 +238,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -262,7 +262,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -277,7 +277,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates) { @@ -286,7 +286,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -301,7 +301,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) @@ -314,7 +314,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -340,7 +340,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -367,7 +367,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -382,7 +382,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] @@ -394,7 +394,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -409,7 +409,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). @@ -422,7 +422,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -446,7 +446,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -471,7 +471,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -487,7 +487,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates) { @@ -496,7 +496,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copies a directory and its contents to a new location, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -512,7 +512,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) @@ -525,7 +525,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -552,7 +552,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -580,7 +580,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -596,7 +596,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] @@ -608,7 +608,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copies a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -624,7 +624,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// The source directory path. /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). @@ -642,7 +642,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// [AlphaFS] Copy/move a Non-/Transacted file or directory including its children to a new location, or can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// - /// A class with the status of the Copy or Move action. + /// Returns a class with the status of the Copy or Move action. /// /// Option is recommended for very large file transfers. /// You cannot use the Move method to overwrite an existing file, unless contains . @@ -658,7 +658,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// The transaction. /// The source directory path. /// The destination directory path. - /// true if original Timestamps must be preserved, false otherwise. This parameter is ignored for move operations. + /// true if original Timestamps must be preserved; otherwise, false. This parameter is ignored for move operations. /// that specify how the directory is to be copied. This parameter can be null. /// that specify how the directory is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the file has been copied/moved. This parameter can be null. diff --git a/AlphaFS/Filesystem/Directory Class/Directory.CreateDirectory.cs b/AlphaFS/Filesystem/Directory Class/Directory.CreateDirectory.cs index 7643aa14e..1f211390d 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.CreateDirectory.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.CreateDirectory.cs @@ -35,7 +35,7 @@ public static partial class Directory #region .NET /// Creates all directories and subdirectories in the specified path unless they already exist. - /// 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 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. /// /// /// @@ -51,7 +51,7 @@ public static DirectoryInfo CreateDirectory(string path) /// Creates all the directories in the specified path, unless the already exist, applying the specified Windows security. - /// 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 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. /// /// /// @@ -71,7 +71,7 @@ public static DirectoryInfo CreateDirectory(string path, DirectorySecurity direc /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -89,7 +89,7 @@ public static DirectoryInfo CreateDirectory(string path, PathFormat pathFormat) /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -106,7 +106,7 @@ public static DirectoryInfo CreateDirectory(string path, bool compress) } /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -125,7 +125,7 @@ public static DirectoryInfo CreateDirectory(string path, bool compress, PathForm /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -144,7 +144,7 @@ public static DirectoryInfo CreateDirectory(string path, DirectorySecurity direc /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -163,7 +163,7 @@ public static DirectoryInfo CreateDirectory(string path, DirectorySecurity direc /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -183,7 +183,7 @@ public static DirectoryInfo CreateDirectory(string path, DirectorySecurity direc /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. - /// 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 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. /// /// /// @@ -201,7 +201,7 @@ public static DirectoryInfo CreateDirectory(string path, string templatePath) /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. - /// 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 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. /// /// /// @@ -220,7 +220,7 @@ public static DirectoryInfo CreateDirectory(string path, string templatePath, Pa /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. - /// 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 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. /// /// /// @@ -239,7 +239,7 @@ public static DirectoryInfo CreateDirectory(string path, string templatePath, bo /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. - /// 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 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. /// /// /// @@ -259,7 +259,7 @@ public static DirectoryInfo CreateDirectory(string path, string templatePath, bo /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. - /// 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 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. /// /// /// @@ -278,7 +278,7 @@ public static DirectoryInfo CreateDirectory(string path, string templatePath, Di /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. - /// 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 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. /// /// /// @@ -298,7 +298,7 @@ public static DirectoryInfo CreateDirectory(string path, string templatePath, Di /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. - /// 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 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. /// /// /// @@ -318,7 +318,7 @@ public static DirectoryInfo CreateDirectory(string path, string templatePath, Di /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. - /// 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 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. /// /// /// @@ -341,7 +341,7 @@ public static DirectoryInfo CreateDirectory(string path, string templatePath, Di #region Transactional /// [AlphaFS] Creates all directories and subdirectories in the specified path unless they already exist. - /// 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 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. /// /// /// @@ -358,7 +358,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -377,7 +377,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -396,7 +396,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -416,7 +416,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates all the directories in the specified path, unless the already exist, applying the specified Windows security. - /// 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 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. /// /// /// @@ -435,7 +435,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -455,7 +455,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -475,7 +475,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates all the directories in the specified path, applying the specified Windows security. - /// 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 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. /// /// /// @@ -496,7 +496,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. - /// 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 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. /// /// /// @@ -514,7 +514,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact } /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. - /// 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 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. /// /// /// @@ -534,7 +534,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. - /// 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 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. /// /// /// @@ -554,7 +554,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates a new directory, with the attributes of a specified template directory. - /// 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 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. /// /// /// @@ -575,7 +575,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. - /// 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 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. /// /// /// @@ -595,7 +595,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. - /// 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 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. /// /// /// @@ -616,7 +616,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. - /// 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 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. /// /// /// @@ -637,7 +637,7 @@ public static DirectoryInfo CreateDirectoryTransacted(KernelTransaction transact /// [AlphaFS] Creates all the directories in the specified path of a specified template directory and applies the specified Windows security. - /// 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 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. /// /// /// @@ -762,7 +762,7 @@ internal static DirectoryInfo CreateDirectoryCore(KernelTransaction transaction, case Win32Errors.ERROR_DIRECTORY: - // MSDN: .NET 3.5+: NotSupportedException: path contains a colon character (:) that is not part of a drive label ("C:\"). + // 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)); @@ -781,7 +781,7 @@ internal static DirectoryInfo CreateDirectoryCore(KernelTransaction transaction, } else if (compress) - Device.ToggleCompressionCore(transaction, folderLp, true, pathFormat); + Device.FileSystemHelper.ToggleCompressionCore(transaction, folderLp, true, pathFormat); } diff --git a/AlphaFS/Filesystem/Directory Class/Directory.CreateJunction.cs b/AlphaFS/Filesystem/Directory Class/Directory.CreateJunction.cs index 6b83de1e6..b56eaf40a 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.CreateJunction.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.CreateJunction.cs @@ -439,7 +439,7 @@ internal static string CreateJunctionCore(KernelTransaction transaction, string CreateDirectoryCore(transaction, junctionPath, null, null, false, pathFormat); using (var safeHandle = OpenDirectoryJunction(transaction, junctionPath, pathFormat)) - Device.CreateDirectoryJunction(safeHandle, directoryPath); + Device.FileSystemHelper.CreateDirectoryJunction(safeHandle, directoryPath); // Copy the target date and time stamps to the directory junction. diff --git a/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs b/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs index 775890600..d4831786a 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs @@ -29,13 +29,12 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Directory { /// [AlphaFS] Creates a symbolic link to a directory (similar to CMD command: "MKLINK /D"). - ///   /// - /// Symbolic links can point to a non-existent target. - /// When creating a symbolic link, the operating system does not check to see if the target exists. - /// Symbolic links are reparse points. - /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. - /// See to run this method in an elevated state. + /// Symbolic links can point to a non-existent target. + /// When creating a symbolic link, the operating system does not check to see if the target exists. + /// Symbolic links are reparse points. + /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. + /// See to run this method from an elevated state. /// /// /// @@ -52,13 +51,12 @@ public static void CreateSymbolicLink(string symlinkDirectoryName, string target /// [AlphaFS] Creates a symbolic link to a directory (similar to CMD command: "MKLINK /D"). - ///   /// - /// Symbolic links can point to a non-existent target. - /// When creating a symbolic link, the operating system does not check to see if the target exists. - /// Symbolic links are reparse points. - /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. - /// See to run this method in an elevated state. + /// Symbolic links can point to a non-existent target. + /// When creating a symbolic link, the operating system does not check to see if the target exists. + /// Symbolic links are reparse points. + /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. + /// See to run this method from an elevated state. /// /// /// @@ -76,13 +74,12 @@ public static void CreateSymbolicLink(string symlinkDirectoryName, string target /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK /D") to a directory as a transacted operation. - ///   /// - /// Symbolic links can point to a non-existent target. - /// When creating a symbolic link, the operating system does not check to see if the target exists. - /// Symbolic links are reparse points. - /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. - /// See to run this method in an elevated state. + /// Symbolic links can point to a non-existent target. + /// When creating a symbolic link, the operating system does not check to see if the target exists. + /// Symbolic links are reparse points. + /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. + /// See to run this method from an elevated state. /// /// /// @@ -100,13 +97,12 @@ public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, s /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK /D") to a directory as a transacted operation. - ///   /// - /// Symbolic links can point to a non-existent target. - /// When creating a symbolic link, the operating system does not check to see if the target exists. - /// Symbolic links are reparse points. - /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. - /// See to run this method in an elevated state. + /// Symbolic links can point to a non-existent target. + /// When creating a symbolic link, the operating system does not check to see if the target exists. + /// Symbolic links are reparse points. + /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. + /// See to run this method from an elevated state. /// /// /// diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Delete.cs b/AlphaFS/Filesystem/Directory Class/Directory.Delete.cs index bdb97ad1d..8650e13dc 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Delete.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Delete.cs @@ -57,7 +57,7 @@ public static void Delete(string path) /// /// /// The name of the directory to remove. - /// true to remove directories, subdirectories, and files in . false otherwise. + /// true to remove directories, subdirectories, and files in ; otherwise, false. [SecurityCritical] public static void Delete(string path, bool recursive) { @@ -92,7 +92,7 @@ public static void Delete(string path, PathFormat pathFormat) /// /// /// The name of the directory to remove. - /// true to remove directories, subdirectories, and files in . false otherwise. + /// true to remove directories, subdirectories, and files in ; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void Delete(string path, bool recursive, PathFormat pathFormat) @@ -110,7 +110,7 @@ public static void Delete(string path, bool recursive, PathFormat pathFormat) /// /// /// The name of the directory to remove. - /// true to remove directories, subdirectories, and files in . false otherwise. + /// true to remove directories, subdirectories, and files in ; otherwise, false. /// true overrides read only of files and directories. [SecurityCritical] public static void Delete(string path, bool recursive, bool ignoreReadOnly) @@ -127,7 +127,7 @@ public static void Delete(string path, bool recursive, bool ignoreReadOnly) /// /// /// The name of the directory to remove. - /// true to remove directories, subdirectories, and files in . false otherwise. + /// true to remove directories, subdirectories, and files in ; otherwise, false. /// true overrides read only of files and directories. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -183,7 +183,7 @@ public static void DeleteTransacted(KernelTransaction transaction, string path, /// /// The transaction. /// The name of the directory to remove. - /// true to remove directories, subdirectories, and files in . false otherwise. + /// true to remove directories, subdirectories, and files in ; otherwise, false. [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive) { @@ -200,7 +200,7 @@ public static void DeleteTransacted(KernelTransaction transaction, string path, /// /// The transaction. /// The name of the directory to remove. - /// true to remove directories, subdirectories, and files in . false otherwise. + /// true to remove directories, subdirectories, and files in ; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, PathFormat pathFormat) @@ -219,7 +219,7 @@ public static void DeleteTransacted(KernelTransaction transaction, string path, /// /// The transaction. /// The name of the directory to remove. - /// true to remove directories, subdirectories, and files in . false otherwise. + /// true to remove directories, subdirectories, and files in ; otherwise, false. /// true overrides read only of files and directories. [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly) @@ -237,7 +237,7 @@ public static void DeleteTransacted(KernelTransaction transaction, string path, /// /// The transaction. /// The name of the directory to remove. - /// true to remove directories, subdirectories, and files in . false otherwise. + /// true to remove directories, subdirectories, and files in ; otherwise, false. /// true overrides read only of files and directories. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -263,7 +263,7 @@ public static void DeleteTransacted(KernelTransaction transaction, string path, /// The transaction. /// A FileSystemEntryInfo instance. Use either or , not both. /// The name of the directory to remove. Use either or , not both. - /// true to remove all files and subdirectories recursively; false otherwise only the top level empty directory. + /// true to remove all files and subdirectories recursively; otherwise, false only the top level empty directory. /// true overrides read only attribute of files and directories. /// When true does not throw an when the directory does not exist. /// Indicates the format of the path parameter(s). diff --git a/AlphaFS/Filesystem/Directory Class/Directory.DeleteJunction.cs b/AlphaFS/Filesystem/Directory Class/Directory.DeleteJunction.cs index 9113a701c..3c7ae7499 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.DeleteJunction.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.DeleteJunction.cs @@ -29,11 +29,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Directory { /// [AlphaFS] Deletes an NTFS directory junction. - ///   - /// - /// Only the directory junction is removed, not the target. - /// - /// A instance referencing the junction point. + /// Only the directory junction is removed, not the target. /// /// /// @@ -49,11 +45,7 @@ public static void DeleteJunction(string junctionPath) /// [AlphaFS] Deletes an NTFS directory junction. - ///   - /// - /// Only the directory junction is removed, not the target. - /// - /// A instance referencing the junction point. + /// Only the directory junction is removed, not the target. /// /// /// @@ -70,11 +62,7 @@ public static void DeleteJunction(string junctionPath, PathFormat pathFormat) /// [AlphaFS] Deletes an NTFS directory junction. - ///   - /// - /// Only the directory junction is removed, not the target. - /// - /// A instance referencing the junction point. + /// Only the directory junction is removed, not the target. /// /// /// @@ -91,11 +79,7 @@ public static void DeleteJunction(string junctionPath, bool removeDirectory) /// [AlphaFS] Deletes an NTFS directory junction. - ///   - /// - /// Only the directory junction is removed, not the target. - /// - /// A instance referencing the junction point. + /// Only the directory junction is removed, not the target. /// /// /// @@ -115,11 +99,7 @@ public static void DeleteJunction(string junctionPath, bool removeDirectory, Pat /// [AlphaFS] Deletes an NTFS directory junction. - ///   - /// - /// Only the directory junction is removed, not the target. - /// - /// A instance referencing the junction point. + /// Only the directory junction is removed, not the target. /// /// /// @@ -136,11 +116,7 @@ public static void DeleteJunction(KernelTransaction transaction, string junction /// [AlphaFS] Deletes an NTFS directory junction. - ///   - /// - /// Only the directory junction is removed, not the target. - /// - /// A instance referencing the junction point. + /// Only the directory junction is removed, not the target. /// /// /// @@ -158,11 +134,7 @@ public static void DeleteJunction(KernelTransaction transaction, string junction /// [AlphaFS] Deletes an NTFS directory junction. - ///   - /// - /// Only the directory junction is removed, not the target. - /// - /// A instance referencing the junction point. + /// Only the directory junction is removed, not the target. /// /// /// @@ -180,11 +152,7 @@ public static void DeleteJunction(KernelTransaction transaction, string junction /// [AlphaFS] Deletes an NTFS directory junction. - ///   - /// - /// Only the directory junction is removed, not the target. - /// - /// A instance referencing the junction point. + /// Only the directory junction is removed, not the target. /// /// /// @@ -205,11 +173,7 @@ public static void DeleteJunction(KernelTransaction transaction, string junction /// [AlphaFS] Deletes an NTFS directory junction. - ///   - /// - /// Only the directory junction is removed, not the target. - /// - /// A instance referencing the junction point. + /// Only the directory junction is removed, not the target. /// /// /// @@ -249,7 +213,7 @@ internal static void DeleteJunctionCore(KernelTransaction transaction, FileSyste // Remove the directory junction. using (var safeHandle = OpenDirectoryJunction(transaction, fsEntryInfo.LongFullPath, pathFormat)) - Device.DeleteDirectoryJunction(safeHandle); + Device.FileSystemHelper.DeleteDirectoryJunction(safeHandle); // Optionally the folder itself, which should and must be empty. diff --git a/AlphaFS/Filesystem/Directory Class/Directory.DisableCompression.cs b/AlphaFS/Filesystem/Directory Class/Directory.DisableCompression.cs index c1b8b7614..c2f4b39ad 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.DisableCompression.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.DisableCompression.cs @@ -39,7 +39,7 @@ public static partial class Directory [SecurityCritical] public static void DisableCompression(string path) { - Device.ToggleCompressionCore(null, path, false, PathFormat.RelativePath); + Device.FileSystemHelper.ToggleCompressionCore(null, path, false, PathFormat.RelativePath); } @@ -56,7 +56,7 @@ public static void DisableCompression(string path) [SecurityCritical] public static void DisableCompression(string path, PathFormat pathFormat) { - Device.ToggleCompressionCore(null, path, false, pathFormat); + Device.FileSystemHelper.ToggleCompressionCore(null, path, false, pathFormat); } @@ -75,7 +75,7 @@ public static void DisableCompression(string path, PathFormat pathFormat) [SecurityCritical] public static void DisableCompressionTransacted(KernelTransaction transaction, string path) { - Device.ToggleCompressionCore(transaction, path, false, PathFormat.RelativePath); + Device.FileSystemHelper.ToggleCompressionCore(transaction, path, false, PathFormat.RelativePath); } @@ -93,7 +93,7 @@ public static void DisableCompressionTransacted(KernelTransaction transaction, s [SecurityCritical] public static void DisableCompressionTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { - Device.ToggleCompressionCore(transaction, path, false, pathFormat); + Device.FileSystemHelper.ToggleCompressionCore(transaction, path, false, pathFormat); } } } diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnableCompression.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnableCompression.cs index 04e5f6337..21e63d625 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnableCompression.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnableCompression.cs @@ -39,7 +39,7 @@ public static partial class Directory [SecurityCritical] public static void EnableCompression(string path) { - Device.ToggleCompressionCore(null, path, true, PathFormat.RelativePath); + Device.FileSystemHelper.ToggleCompressionCore(null, path, true, PathFormat.RelativePath); } /// [AlphaFS] Enables NTFS compression of the specified directory and the files in it. @@ -55,7 +55,7 @@ public static void EnableCompression(string path) [SecurityCritical] public static void EnableCompression(string path, PathFormat pathFormat) { - Device.ToggleCompressionCore(null, path, true, pathFormat); + Device.FileSystemHelper.ToggleCompressionCore(null, path, true, pathFormat); } @@ -74,7 +74,7 @@ public static void EnableCompression(string path, PathFormat pathFormat) [SecurityCritical] public static void EnableCompressionTransacted(KernelTransaction transaction, string path) { - Device.ToggleCompressionCore(transaction, path, true, PathFormat.RelativePath); + Device.FileSystemHelper.ToggleCompressionCore(transaction, path, true, PathFormat.RelativePath); } @@ -92,7 +92,7 @@ public static void EnableCompressionTransacted(KernelTransaction transaction, st [SecurityCritical] public static void EnableCompressionTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { - Device.ToggleCompressionCore(transaction, path, true, pathFormat); + Device.FileSystemHelper.ToggleCompressionCore(transaction, path, true, pathFormat); } } } diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateDirectories.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateDirectories.cs index b9ea774f9..841916986 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateDirectories.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateDirectories.cs @@ -31,8 +31,8 @@ public static partial class Directory { #region .NET - /// Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -47,8 +47,8 @@ public static IEnumerable EnumerateDirectories(string path) } - /// Returns an enumerable collection of directory names that match a in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . + /// Returns an collection of directory names that match a in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// @@ -68,8 +68,8 @@ public static IEnumerable EnumerateDirectories(string path, string searc } - /// Returns an enumerable collection of directory names that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . + /// Returns an collection of directory names that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . /// /// /// @@ -95,8 +95,8 @@ public static IEnumerable EnumerateDirectories(string path, string searc #endregion // .NET - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -112,8 +112,8 @@ public static IEnumerable EnumerateDirectories(string path, PathFormat p } - /// [AlphaFS] Returns an enumerable collection of directory names that match a in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of directory names that match a in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// @@ -135,8 +135,8 @@ public static IEnumerable EnumerateDirectories(string path, string searc } - /// [AlphaFS] Returns an enumerable collection of directory names that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . + /// [AlphaFS] Returns an collection of directory names that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . /// /// /// @@ -162,8 +162,8 @@ public static IEnumerable EnumerateDirectories(string path, string searc } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -179,8 +179,8 @@ public static IEnumerable EnumerateDirectories(string path, DirectoryEnu } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -197,8 +197,8 @@ public static IEnumerable EnumerateDirectories(string path, DirectoryEnu } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -220,8 +220,8 @@ public static IEnumerable EnumerateDirectories(string path, string searc } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -244,8 +244,8 @@ public static IEnumerable EnumerateDirectories(string path, string searc } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -261,8 +261,8 @@ public static IEnumerable EnumerateDirectories(string path, DirectoryEnu } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -279,8 +279,8 @@ public static IEnumerable EnumerateDirectories(string path, DirectoryEnu } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -302,8 +302,8 @@ public static IEnumerable EnumerateDirectories(string path, string searc } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -326,8 +326,8 @@ public static IEnumerable EnumerateDirectories(string path, string searc } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -344,8 +344,8 @@ public static IEnumerable EnumerateDirectories(string path, DirectoryEnu } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -363,8 +363,8 @@ public static IEnumerable EnumerateDirectories(string path, DirectoryEnu } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -387,8 +387,8 @@ public static IEnumerable EnumerateDirectories(string path, string searc } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -414,8 +414,8 @@ public static IEnumerable EnumerateDirectories(string path, string searc - /// [AlphaFS] Returns an enumerable collection of directory instances in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory instances in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -431,8 +431,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory instances that match a in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of directory instances that match a in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// @@ -454,8 +454,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory names that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . + /// [AlphaFS] Returns an collection of directory names that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . /// /// /// @@ -481,8 +481,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory instances in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory instances in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -499,8 +499,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory instances that match a in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of directory instances that match a in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// @@ -523,8 +523,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory names that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . + /// [AlphaFS] Returns an collection of directory names that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of the full names (including paths) for the directories in the directory specified by and that match the specified and . /// /// /// @@ -551,8 +551,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory instances in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory instances in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -569,8 +569,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory instances in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory instances in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -588,8 +588,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory instances that match a in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of directory instances that match a in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// @@ -612,8 +612,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory instances that match a in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of directory instances that match a in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by and that match the specified . /// /// /// @@ -637,8 +637,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -655,8 +655,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -674,8 +674,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -698,8 +698,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -723,8 +723,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -742,8 +742,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -762,8 +762,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// @@ -787,8 +787,8 @@ public static IEnumerable EnumerateDirectoriesTransacted(KernelTransacti } - /// [AlphaFS] Returns an enumerable collection of directory names in a specified . - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by . + /// [AlphaFS] Returns an collection of directory names in a specified . + /// Returns an collection of the full names (including paths) for the directories in the directory specified by . /// /// /// diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileIdBothDirectoryInfo.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileIdBothDirectoryInfo.cs index b0e475392..084b7aa59 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileIdBothDirectoryInfo.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileIdBothDirectoryInfo.cs @@ -34,7 +34,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Directory { /// [AlphaFS] Retrieves information about files in the directory specified by in mode. - /// An enumeration of records for each file system entry in the specified diretory. + /// Returns an enumeration of records for each file system entry in the specified directory. /// The operating system is older than Windows Vista. /// A path to a directory from which to retrieve information. [SecurityCritical] @@ -44,7 +44,7 @@ public static IEnumerable EnumerateFileIdBothDirectoryI } /// [AlphaFS] Retrieves information about files in the directory specified by in mode. - /// An enumeration of records for each file system entry in the specified diretory. + /// Returns an enumeration of records for each file system entry in the specified directory. /// The operating system is older than Windows Vista. /// A path to a directory from which to retrieve information. /// Indicates the format of the path parameter(s). @@ -57,7 +57,7 @@ public static IEnumerable EnumerateFileIdBothDirectoryI /// [AlphaFS] Retrieves information about files in the directory specified by in specified mode. - /// An enumeration of records for each file system entry in the specified diretory. + /// Returns an enumeration of records for each file system entry in the specified directory. /// The operating system is older than Windows Vista. /// A path to a directory from which to retrieve information. /// The mode with which to open a handle to the directory. @@ -68,7 +68,7 @@ public static IEnumerable EnumerateFileIdBothDirectoryI } /// [AlphaFS] Retrieves information about files in the directory specified by in specified mode. - /// An enumeration of records for each file system entry in the specified diretory. + /// Returns an enumeration of records for each file system entry in the specified directory. /// The operating system is older than Windows Vista. /// A path to a directory from which to retrieve information. /// The mode with which to open a handle to the directory. @@ -82,7 +82,7 @@ public static IEnumerable EnumerateFileIdBothDirectoryI /// [AlphaFS] Retrieves information about files in the directory handle specified. - /// An IEnumerable of records for each file system entry in the specified diretory. + /// Returns an collection for each file system entry in the specified directory. /// The operating system is older than Windows Vista. /// An open handle to the directory from which to retrieve information. [SecurityCritical] @@ -95,7 +95,7 @@ public static IEnumerable EnumerateFileIdBothDirectoryI #region Transactional /// [AlphaFS] Retrieves information about files in the directory specified by in mode. - /// An enumeration of records for each file system entry in the specified diretory. + /// Returns an enumeration of records for each file system entry in the specified directory. /// The operating system is older than Windows Vista. /// The transaction. /// A path to a directory from which to retrieve information. @@ -106,7 +106,7 @@ public static IEnumerable EnumerateFileIdBothDirectoryI } /// [AlphaFS] Retrieves information about files in the directory specified by in mode. - /// An enumeration of records for each file system entry in the specified diretory. + /// Returns an enumeration of records for each file system entry in the specified directory. /// The operating system is older than Windows Vista. /// The transaction. /// A path to a directory from which to retrieve information. @@ -120,7 +120,7 @@ public static IEnumerable EnumerateFileIdBothDirectoryI /// [AlphaFS] Retrieves information about files in the directory specified by in specified mode. - /// An enumeration of records for each file system entry in the specified diretory. + /// Returns an enumeration of records for each file system entry in the specified directory. /// The operating system is older than Windows Vista. /// The transaction. /// A path to a directory from which to retrieve information. @@ -132,7 +132,7 @@ public static IEnumerable EnumerateFileIdBothDirectoryI } /// [AlphaFS] Retrieves information about files in the directory specified by in specified mode. - /// An enumeration of records for each file system entry in the specified diretory. + /// Returns an enumeration of records for each file system entry in the specified directory. /// The operating system is older than Windows Vista. /// The transaction. /// A path to a directory from which to retrieve information. @@ -148,8 +148,8 @@ public static IEnumerable EnumerateFileIdBothDirectoryI #region Internal Methods - /// Returns an enumerable collection of information about files in the directory handle specified. - /// An IEnumerable of records for each file system entry in the specified diretory. + /// Returns an collection of information about files in the directory handle specified. + /// Returns an instance for each file system entry in the specified directory. /// The operating system is older than Windows Vista. /// /// Either use or , not both. @@ -188,7 +188,7 @@ internal static IEnumerable EnumerateFileIdBothDirector try { - if (!NativeMethods.IsValidHandle(safeFileHandle, Marshal.GetLastWin32Error(), !continueOnException)) + if (!Utils.IsValidHandle(safeFileHandle, Marshal.GetLastWin32Error(), !continueOnException)) yield break; var fileNameOffset = (int) Marshal.OffsetOf(typeof(NativeMethods.FILE_ID_BOTH_DIR_INFO), "FileName"); diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntries.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntries.cs index fe3bfb231..ee2444ee6 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntries.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntries.cs @@ -31,8 +31,8 @@ public static partial class Directory { #region .NET - /// Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -47,8 +47,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path) } - /// Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// @@ -68,8 +68,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, string } - /// Returns an enumerable collection of file names and directory names that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of file system entries in the directory specified by and that match the specified and . + /// Returns an collection of file names and directory names that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of file system entries in the directory specified by and that match the specified and . /// /// /// @@ -95,8 +95,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, string #endregion // .NET - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -112,8 +112,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, PathFo } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// @@ -135,8 +135,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, string } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of file system entries in the directory specified by and that match the specified and . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of file system entries in the directory specified by and that match the specified and . /// /// /// @@ -162,8 +162,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, string } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -179,8 +179,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, Direct } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -197,8 +197,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, Direct } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// @@ -220,8 +220,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, string } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// @@ -244,8 +244,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, string } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -261,8 +261,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, Direct } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -279,8 +279,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, Direct } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -297,8 +297,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, Direct } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -316,8 +316,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, Direct } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// @@ -340,8 +340,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, string } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// @@ -367,8 +367,8 @@ public static IEnumerable EnumerateFileSystemEntries(string path, string - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -384,8 +384,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// @@ -407,8 +407,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of file system entries in the directory specified by and that match the specified and . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of file system entries in the directory specified by and that match the specified and . /// /// /// @@ -434,8 +434,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -452,8 +452,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// @@ -476,8 +476,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of file system entries in the directory specified by and that match the specified and . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of file system entries in the directory specified by and that match the specified and . /// /// /// @@ -504,8 +504,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -522,8 +522,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -541,8 +541,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// @@ -565,8 +565,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// @@ -590,8 +590,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -608,8 +608,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -627,8 +627,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -646,8 +646,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names in a specified . - /// An enumerable collection of file system entries in the directory specified by . + /// [AlphaFS] Returns an collection of file names and directory names in a specified . + /// Returns an collection of file system entries in the directory specified by . /// /// /// @@ -666,8 +666,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// @@ -691,8 +691,8 @@ public static IEnumerable EnumerateFileSystemEntriesTransacted(KernelTra } - /// [AlphaFS] Returns an enumerable collection of file names and directory names that match a in a specified . - /// An enumerable collection of file system entries in the directory specified by and that match the specified . + /// [AlphaFS] Returns an collection of file names and directory names that match a in a specified . + /// Returns an collection of file system entries in the directory specified by and that match the specified . /// /// /// diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntryInfos.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntryInfos.cs index 6c6f604ac..039c8ca1b 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntryInfos.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntryInfos.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -62,7 +62,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path) } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -96,7 +96,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, PathF } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -130,7 +130,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, Direc } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -165,7 +165,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, Direc } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -203,7 +203,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, strin } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -242,7 +242,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, strin } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path using . + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path using . /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -281,7 +281,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, strin } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path using . + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path using . /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -321,7 +321,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, strin } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -355,7 +355,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, Direc } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -390,7 +390,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, Direc } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -425,7 +425,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, Direc } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -461,7 +461,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, Direc } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -501,7 +501,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, strin } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -542,7 +542,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, strin } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -583,7 +583,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, strin } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -627,7 +627,7 @@ public static IEnumerable EnumerateFileSystemEntryInfos(string path, strin - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -661,7 +661,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -696,7 +696,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -731,7 +731,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -767,7 +767,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -807,7 +807,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -848,7 +848,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path using . + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path using . /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -889,7 +889,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path using . + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path using . /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -931,7 +931,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -966,7 +966,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -1002,7 +1002,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -1038,7 +1038,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path. + /// [AlphaFS] Returns an collection of file system entries in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -1075,7 +1075,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -1116,7 +1116,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -1158,7 +1158,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -1200,7 +1200,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr } - /// [AlphaFS] Returns an enumerable collection of file system entries that match a in a specified path. + /// [AlphaFS] Returns an collection of file system entries that match a in a specified path. /// The matching file system entries. The type of the items is determined by the type . /// /// @@ -1245,7 +1245,7 @@ public static IEnumerable EnumerateFileSystemEntryInfosTransacted(KernelTr - /// [AlphaFS] Returns an enumerable collection of file system entries in a specified path using and . + /// [AlphaFS] Returns an collection of file system entries in a specified path using and . /// The matching file system entries. The type of the items is determined by the type . /// /// diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFiles.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFiles.cs index 771747b91..487198033 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFiles.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFiles.cs @@ -31,8 +31,8 @@ public static partial class Directory { #region .NET - /// Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -47,8 +47,8 @@ public static IEnumerable EnumerateFiles(string path) } - /// Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -68,8 +68,8 @@ public static IEnumerable EnumerateFiles(string path, string searchPatte } - /// Returns an enumerable collection of file names that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the specified and . + /// Returns an collection of file names that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the specified and . /// /// /// @@ -95,8 +95,8 @@ public static IEnumerable EnumerateFiles(string path, string searchPatte #endregion // .NET - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -112,8 +112,8 @@ public static IEnumerable EnumerateFiles(string path, PathFormat pathFor } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -135,8 +135,8 @@ public static IEnumerable EnumerateFiles(string path, string searchPatte } - /// [AlphaFS] Returns an enumerable collection of file names that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the specified and . + /// [AlphaFS] Returns an collection of file names that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the specified and . /// /// /// @@ -162,8 +162,8 @@ public static IEnumerable EnumerateFiles(string path, string searchPatte } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -179,8 +179,8 @@ public static IEnumerable EnumerateFiles(string path, DirectoryEnumerati } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -197,8 +197,8 @@ public static IEnumerable EnumerateFiles(string path, DirectoryEnumerati } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -220,8 +220,8 @@ public static IEnumerable EnumerateFiles(string path, string searchPatte } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -244,8 +244,8 @@ public static IEnumerable EnumerateFiles(string path, string searchPatte } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -261,8 +261,8 @@ public static IEnumerable EnumerateFiles(string path, DirectoryEnumerati } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -279,8 +279,8 @@ public static IEnumerable EnumerateFiles(string path, DirectoryEnumerati } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -302,8 +302,8 @@ public static IEnumerable EnumerateFiles(string path, string searchPatte } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -326,8 +326,8 @@ public static IEnumerable EnumerateFiles(string path, string searchPatte } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -344,8 +344,8 @@ public static IEnumerable EnumerateFiles(string path, DirectoryEnumerati } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -363,8 +363,8 @@ public static IEnumerable EnumerateFiles(string path, DirectoryEnumerati } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -387,8 +387,8 @@ public static IEnumerable EnumerateFiles(string path, string searchPatte } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -414,8 +414,8 @@ public static IEnumerable EnumerateFiles(string path, string searchPatte - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -431,8 +431,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file instances that match a in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file instances that match a in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -454,8 +454,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file instances instances that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the specified and . + /// [AlphaFS] Returns an collection of file instances instances that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the specified and . /// /// /// @@ -481,8 +481,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -499,8 +499,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file instances that match a in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file instances that match a in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -523,8 +523,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file instances instances that match a in a specified , and optionally searches subdirectories. - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the specified and . + /// [AlphaFS] Returns an collection of file instances instances that match a in a specified , and optionally searches subdirectories. + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the specified and . /// /// /// @@ -551,8 +551,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -569,8 +569,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -588,8 +588,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file instances that match a in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file instances that match a in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -612,8 +612,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file instances that match a in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file instances that match a in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -637,8 +637,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -655,8 +655,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -674,8 +674,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -698,8 +698,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -723,8 +723,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -742,8 +742,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by . /// /// /// @@ -762,8 +762,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// @@ -787,8 +787,8 @@ public static IEnumerable EnumerateFilesTransacted(KernelTransaction tra } - /// [AlphaFS] Returns an enumerable collection of file names in a specified . - /// An enumerable collection of the full names (including paths) for the files in the directory specified by and that match the . + /// [AlphaFS] Returns an collection of file names in a specified . + /// Returns an collection of the full names (including paths) for the files in the directory specified by and that match the . /// /// /// diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateLogicalDrives.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateLogicalDrives.cs index b257867fa..5ca2a9c35 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateLogicalDrives.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateLogicalDrives.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Directory { /// [AlphaFS] Enumerates the drive names of all logical drives on the Computer with the ready status. - /// An IEnumerable of type that represents the logical drives on the Computer. + /// Returns an IEnumerable of type that represents the logical drives on the Computer. [SecurityCritical] [Obsolete("Use DriveInfo.GetDrives()")] public static IEnumerable EnumerateLogicalDrives() @@ -39,7 +39,7 @@ public static IEnumerable EnumerateLogicalDrives() /// [AlphaFS] Enumerates the drive names of all logical drives on the Computer. - /// An IEnumerable of type that represents the logical drives on the Computer. + /// Returns an IEnumerable of type that represents the logical drives on the Computer. /// Retrieve logical drives as known by the Environment. /// Retrieve only when accessible (IsReady) logical drives. [SecurityCritical] diff --git a/AlphaFS/Filesystem/Directory Class/Directory.ExistsDrive.cs b/AlphaFS/Filesystem/Directory Class/Directory.ExistsDrive.cs index 5279cc372..2d1e07219 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.ExistsDrive.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.ExistsDrive.cs @@ -28,7 +28,7 @@ public static partial class Directory { /// [AlphaFS] Checks if specified is a local- or network drive. /// The path to check, such as: "C:" or "\\server\c$". - /// true if the drive exists, false otherwise. + /// true if the drive exists; otherwise, false. public static bool ExistsDrive(string path) { return ExistsDriveOrFolderOrFile(null, path, false, (int) Win32Errors.NO_ERROR, false, false); @@ -38,7 +38,7 @@ public static bool ExistsDrive(string path) /// [AlphaFS] Checks if specified is a local- or network drive. /// The transaction. /// The path to check, such as: "C:" or "\\server\c$". - /// true if the drive exists, false otherwise. + /// true if the drive exists; otherwise, false. public static bool ExistsDrive(KernelTransaction transaction, string path) { return ExistsDriveOrFolderOrFile(transaction, path, false, (int) Win32Errors.NO_ERROR, false, false); @@ -49,7 +49,7 @@ public static bool ExistsDrive(KernelTransaction transaction, string path) /// The transaction. /// The path to check, such as: "C:" or "\\server\c$". /// Throws DeviceNotReadyException when drive is not found. - /// true if the drive exists, false otherwise. + /// true if the drive exists; otherwise, false. [Obsolete("This function will be removed.")] public static bool ExistsDrive(KernelTransaction transaction, string path, bool throwIfDriveNotExists) { @@ -58,7 +58,7 @@ public static bool ExistsDrive(KernelTransaction transaction, string path, bool /// [AlphaFS] Checks if specified is a local- or network drive. - /// true if the drive exists, false otherwise. + /// true if the drive exists; otherwise, false. internal static bool ExistsDriveOrFolderOrFile(KernelTransaction transaction, string path, bool isFolder, int lastError, bool throwIfDriveNotExists, bool throwIfFolderOrFileNotExists) { if (Utils.IsNullOrWhiteSpace(path)) diff --git a/AlphaFS/Filesystem/Directory Class/Directory.ExistsJunction.cs b/AlphaFS/Filesystem/Directory Class/Directory.ExistsJunction.cs index f72490948..ca575a4c1 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.ExistsJunction.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.ExistsJunction.cs @@ -29,14 +29,13 @@ public static partial class Directory { /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// - /// Returns true if refers to an existing directory junction. - /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. + /// Returns true if refers to an existing directory junction. + /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// - ///   /// - /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. - /// 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. + /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. + /// 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. /// /// /// @@ -52,14 +51,13 @@ public static bool ExistsJunction(string junctionPath) /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// - /// Returns true if refers to an existing directory junction. - /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. + /// Returns true if refers to an existing directory junction. + /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// - ///   /// - /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. - /// 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. + /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. + /// 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. /// /// /// @@ -78,14 +76,13 @@ public static bool ExistsJunction(string junctionPath, PathFormat pathFormat) /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// - /// Returns true if refers to an existing directory junction. - /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. + /// Returns true if refers to an existing directory junction. + /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// - ///   /// - /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. - /// 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. + /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. + /// 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. /// /// /// @@ -102,14 +99,13 @@ public static bool ExistsJunction(KernelTransaction transaction, string junction /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// - /// Returns true if refers to an existing directory junction. - /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. + /// Returns true if refers to an existing directory junction. + /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// - ///   /// - /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. - /// 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. + /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. + /// 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. /// /// /// @@ -129,14 +125,13 @@ public static bool ExistsJunction(KernelTransaction transaction, string junction /// [AlphaFS] Determines whether the given path refers to an existing directory junction on disk. /// - /// Returns true if refers to an existing directory junction. - /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. + /// Returns true if refers to an existing directory junction. + /// Returns false if the directory junction does not exist or an error occurs when trying to determine if the specified file exists. /// - ///   /// - /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. - /// 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. + /// The Exists method returns false if any error occurs while trying to determine if the specified file exists. + /// 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. /// /// /// diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetAccessControl.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetAccessControl.cs index 4b7fed774..0ba49c044 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetAccessControl.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetAccessControl.cs @@ -31,7 +31,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Directory { /// Gets a object that encapsulates the access control list (ACL) entries for the specified directory. - /// A object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -43,7 +43,7 @@ public static DirectorySecurity GetAccessControl(string path) } /// Gets a object that encapsulates the specified type of access control list (ACL) entries for a particular directory. - /// A object that encapsulates the access control rules for the directory described by the parameter. + /// Returns a object that encapsulates the access control rules for the directory described by the parameter. /// /// /// @@ -57,7 +57,7 @@ public static DirectorySecurity GetAccessControl(string path, AccessControlSecti /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for the specified directory. - /// A object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -70,7 +70,7 @@ public static DirectorySecurity GetAccessControl(string path, PathFormat pathFor } /// [AlphaFS] Gets a object that encapsulates the specified type of access control list (ACL) entries for a particular directory. - /// A object that encapsulates the access control rules for the directory described by the parameter. + /// Returns a object that encapsulates the access control rules for the directory described by the parameter. /// /// /// @@ -85,7 +85,7 @@ public static DirectorySecurity GetAccessControl(string path, AccessControlSecti /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for the specified directory handle. - /// A object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -97,7 +97,7 @@ public static DirectorySecurity GetAccessControl(SafeFileHandle handle) } /// [AlphaFS] Gets a object that encapsulates the specified type of access control list (ACL) entries for a particular directory handle. - /// A object that encapsulates the access control rules for the directory described by the parameter. + /// Returns a object that encapsulates the access control rules for the directory described by the parameter. /// /// /// diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetChangeTime.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetChangeTime.cs index dc0dbed5c..e7f12258d 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetChangeTime.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetChangeTime.cs @@ -28,7 +28,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Directory { /// [AlphaFS] Gets the change date and time of the specified directory. - /// A structure set to the change date and time for the specified directory. This value is expressed in local time. + /// Returns a structure set to the change date and time for the specified directory. This value is expressed in local time. /// The directory for which to obtain creation date and time information. [SecurityCritical] public static DateTime GetChangeTime(string path) @@ -37,7 +37,7 @@ public static DateTime GetChangeTime(string path) } /// [AlphaFS] Gets the change date and time of the specified directory. - /// A structure set to the change date and time for the specified directory. This value is expressed in local time. + /// Returns a structure set to the change date and time for the specified directory. This value is expressed in local time. /// The directory for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -49,7 +49,7 @@ public static DateTime GetChangeTime(string path, PathFormat pathFormat) /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified directory. - /// A structure set to the change date and time for the specified directory. This value is expressed in UTC time. + /// Returns a structure set to the change date and time for the specified directory. This value is expressed in UTC time. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] public static DateTime GetChangeTimeUtc(string path) @@ -58,7 +58,7 @@ public static DateTime GetChangeTimeUtc(string path) } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified directory. - /// A structure set to the change date and time for the specified directory. This value is expressed in UTC time. + /// Returns a structure set to the change date and time for the specified directory. This value is expressed in UTC time. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -70,7 +70,7 @@ public static DateTime GetChangeTimeUtc(string path, PathFormat pathFormat) /// [AlphaFS] Gets the change date and time of the specified directory. - /// A structure set to the change date and time for the specified directory. This value is expressed in local time. + /// Returns a structure set to the change date and time for the specified directory. This value is expressed in local time. /// An open handle to the directory from which to retrieve information. [SecurityCritical] public static DateTime GetChangeTime(SafeFileHandle safeFileHandle) @@ -79,7 +79,7 @@ public static DateTime GetChangeTime(SafeFileHandle safeFileHandle) } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified directory. - /// A structure set to the change date and time for the specified directory. This value is expressed in UTC time. + /// Returns a structure set to the change date and time for the specified directory. This value is expressed in UTC time. /// An open handle to the directory from which to retrieve information. [SecurityCritical] public static DateTime GetChangeTimeUtc(SafeFileHandle safeFileHandle) @@ -90,7 +90,7 @@ public static DateTime GetChangeTimeUtc(SafeFileHandle safeFileHandle) #region Transactional /// [AlphaFS] Gets the change date and time of the specified directory. - /// A structure set to the change date and time for the specified directory. This value is expressed in local time. + /// Returns a structure set to the change date and time for the specified directory. This value is expressed in local time. /// The transaction. /// The directory for which to obtain creation date and time information. [SecurityCritical] @@ -100,7 +100,7 @@ public static DateTime GetChangeTimeTransacted(KernelTransaction transaction, st } /// [AlphaFS] Gets the change date and time of the specified directory. - /// A structure set to the change date and time for the specified directory. This value is expressed in local time. + /// Returns a structure set to the change date and time for the specified directory. This value is expressed in local time. /// The transaction. /// The directory for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). @@ -113,7 +113,7 @@ public static DateTime GetChangeTimeTransacted(KernelTransaction transaction, st /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified directory. - /// A structure set to the change date and time for the specified directory. This value is expressed in UTC time. + /// Returns a structure set to the change date and time for the specified directory. This value is expressed in UTC time. /// The transaction. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] @@ -123,7 +123,7 @@ public static DateTime GetChangeTimeUtcTransacted(KernelTransaction transaction, } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified directory. - /// A structure set to the change date and time for the specified directory. This value is expressed in UTC time. + /// Returns a structure set to the change date and time for the specified directory. This value is expressed in UTC time. /// The transaction. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetCreationTime.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetCreationTime.cs index e3ea4c90e..034c5c2e8 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetCreationTime.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetCreationTime.cs @@ -29,7 +29,7 @@ partial class Directory #region .NET /// Gets the creation date and time of the specified directory. - /// A structure set to the creation date and time for the specified directory. This value is expressed in local time. + /// Returns a structure set to the creation date and time for the specified directory. This value is expressed in local time. /// The directory for which to obtain creation date and time information. [SecurityCritical] public static DateTime GetCreationTime(string path) @@ -40,7 +40,7 @@ public static DateTime GetCreationTime(string path) /// Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified directory. - /// A structure set to the creation date and time for the specified directory. This value is expressed in UTC time. + /// Returns a structure set to the creation date and time for the specified directory. This value is expressed in UTC time. /// The directory for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] public static DateTime GetCreationTimeUtc(string path) @@ -51,7 +51,7 @@ public static DateTime GetCreationTimeUtc(string path) #endregion // .NET /// [AlphaFS] Gets the creation date and time of the specified directory. - /// A structure set to the creation date and time for the specified directory. This value is expressed in local time. + /// Returns a structure set to the creation date and time for the specified directory. This value is expressed in local time. /// The directory for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -63,7 +63,7 @@ public static DateTime GetCreationTime(string path, PathFormat pathFormat) /// [AlphaFS] Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified directory. - /// A structure set to the creation date and time for the specified directory. This value is expressed in UTC time. + /// Returns a structure set to the creation date and time for the specified directory. This value is expressed in UTC time. /// The directory for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -76,7 +76,7 @@ public static DateTime GetCreationTimeUtc(string path, PathFormat pathFormat) #region Transactional /// [AlphaFS] Gets the creation date and time of the specified directory. - /// A structure set to the creation date and time for the specified directory. This value is expressed in local time. + /// Returns a structure set to the creation date and time for the specified directory. This value is expressed in local time. /// The transaction. /// The directory for which to obtain creation date and time information. [SecurityCritical] @@ -86,7 +86,7 @@ public static DateTime GetCreationTimeTransacted(KernelTransaction transaction, } /// [AlphaFS] Gets the creation date and time of the specified directory. - /// A structure set to the creation date and time for the specified directory. This value is expressed in local time. + /// Returns a structure set to the creation date and time for the specified directory. This value is expressed in local time. /// The transaction. /// The directory for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). @@ -99,7 +99,7 @@ public static DateTime GetCreationTimeTransacted(KernelTransaction transaction, /// [AlphaFS] Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified directory. - /// A structure set to the creation date and time for the specified directory. This value is expressed in UTC time. + /// Returns a structure set to the creation date and time for the specified directory. This value is expressed in UTC time. /// The transaction. /// The directory for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] @@ -109,7 +109,7 @@ public static DateTime GetCreationTimeUtcTransacted(KernelTransaction transactio } /// [AlphaFS] Gets the creation date and time, in Coordinated Universal Time (UTC) format, of the specified directory. - /// A structure set to the creation date and time for the specified directory. This value is expressed in UTC time. + /// Returns a structure set to the creation date and time for the specified directory. This value is expressed in UTC time. /// The transaction. /// The directory for which to obtain creation date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetDirectories.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetDirectories.cs index 6b2f3f83f..cf1301818 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetDirectories.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetDirectories.cs @@ -35,7 +35,7 @@ public static partial class Directory #region .NET /// Returns the names of subdirectories (including their paths) in the specified directory. - /// An array of the full names (including paths) of subdirectories in the specified path, or an empty array if no directories are found. + /// Returns an array of the full names (including paths) of subdirectories in the specified path, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names @@ -58,7 +58,7 @@ public static string[] GetDirectories(string path) /// Returns the names of subdirectories (including their paths) that match the specified search pattern in the specified directory. - /// An array of the full names (including paths) of the subdirectories that match the search pattern in the specified directory, or an empty array if no directories are found. + /// Returns an array of the full names (including paths) of the subdirectories that match the search pattern in the specified directory, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names @@ -86,7 +86,7 @@ public static string[] GetDirectories(string path, string searchPattern) /// Returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories. - /// An array of the full names (including paths) of the subdirectories that match the specified criteria, or an empty array if no directories are found. + /// Returns an array of the full names (including paths) of the subdirectories that match the specified criteria, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names @@ -122,7 +122,7 @@ public static string[] GetDirectories(string path, string searchPattern, SearchO /// [AlphaFS] Returns the names of subdirectories (including their paths) in the specified directory. - /// An array of the full names (including paths) of subdirectories in the specified path, or an empty array if no directories are found. + /// Returns an array of the full names (including paths) of subdirectories in the specified path, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names @@ -146,7 +146,7 @@ public static string[] GetDirectoriesTransacted(KernelTransaction transaction, s /// [AlphaFS] Returns the names of subdirectories (including their paths) that match the specified search pattern in the specified directory. - /// An array of the full names (including paths) of the subdirectories that match the search pattern in the specified directory, or an empty array if no directories are found. + /// Returns an array of the full names (including paths) of the subdirectories that match the search pattern in the specified directory, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names @@ -175,7 +175,7 @@ public static string[] GetDirectoriesTransacted(KernelTransaction transaction, s /// [AlphaFS] Returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories. - /// An array of the full names (including paths) of the subdirectories that match the specified criteria, or an empty array if no directories are found. + /// Returns an array of the full names (including paths) of the subdirectories that match the specified criteria, or an empty array if no directories are found. /// /// The names returned by this method are prefixed with the directory information provided in path. /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetFileIdInfo.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetFileIdInfo.cs index 518d5e8db..ed9739fb1 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetFileIdInfo.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetFileIdInfo.cs @@ -26,7 +26,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Directory { /// [AlphaFS] Gets the unique identifier for a directory. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a directory can change over time. /// The path to the directory. [SecurityCritical] @@ -37,7 +37,7 @@ public static FileIdInfo GetFileIdInfo(string path) /// [AlphaFS] Gets the unique identifier for a directory. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a directory can change over time. /// The path to the directory. /// Indicates the format of the path parameter(s). @@ -51,7 +51,7 @@ public static FileIdInfo GetFileIdInfo(string path, PathFormat pathFormat) /// [AlphaFS] Gets the unique identifier for a directory. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a directory can change over time. /// The transaction. /// The path to the directory. @@ -63,7 +63,7 @@ public static FileIdInfo GetFileIdTransacted(KernelTransaction transaction, stri /// [AlphaFS] Gets the unique identifier for a directory. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a directory can change over time. /// The transaction. /// The path to the directory. diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetFileInfoByHandle.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetFileInfoByHandle.cs index 5b5a5878c..e7f36558d 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetFileInfoByHandle.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetFileInfoByHandle.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Directory { /// [AlphaFS] Retrieves file information for the specified directory. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the directory ID for a directory can change over time. /// The path to the directory. [SecurityCritical] @@ -38,7 +38,7 @@ public static ByHandleFileInfo GetFileInfoByHandle(string path) /// [AlphaFS] Retrieves file information for the specified directory. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the directory ID for a directory can change over time. /// The path to the directory. /// Indicates the format of the path parameter(s). @@ -52,7 +52,7 @@ public static ByHandleFileInfo GetFileInfoByHandle(string path, PathFormat pathF /// [AlphaFS] Retrieves file information for the specified directory. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the directory ID for a directory can change over time. /// The transaction. /// The path to the directory. @@ -64,7 +64,7 @@ public static ByHandleFileInfo GetFileInfoByHandleTransacted(KernelTransaction t /// [AlphaFS] Retrieves file information for the specified directory. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the directory ID for a directory can change over time. /// The transaction. /// The path to the directory. @@ -79,7 +79,7 @@ public static ByHandleFileInfo GetFileInfoByHandleTransacted(KernelTransaction t /// [AlphaFS] Retrieves file information for the specified . - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the directory ID for a directory can change over time. /// A connected to the open file or directory from which to retrieve the information. [SecurityCritical] diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntries.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntries.cs index eba3ff7c8..66dfc7c70 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntries.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntries.cs @@ -35,7 +35,7 @@ public static partial class Directory #region .NET /// Returns the names of all files and subdirectories in the specified directory. - /// An string[] array of the names of files and subdirectories in the specified directory. + /// Returns a string[] array of the names of files and subdirectories in the specified directory. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, @@ -57,7 +57,7 @@ public static string[] GetFileSystemEntries(string path) } /// Returns an array of file system entries that match the specified search criteria. - /// An string[] array of file system entries that match the specified search criteria. + /// Returns a string[] array of file system entries that match the specified search criteria. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, @@ -84,7 +84,7 @@ public static string[] GetFileSystemEntries(string path, string searchPattern) } /// Gets an array of all the file names and directory names that match a in a specified path, and optionally searches subdirectories. - /// An string[] array of file system entries that match the specified search criteria. + /// Returns a string[] array of file system entries that match the specified search criteria. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, @@ -118,7 +118,7 @@ public static string[] GetFileSystemEntries(string path, string searchPattern, S /// Returns the names of all files and subdirectories in the specified directory. - /// An string[] array of the names of files and subdirectories in the specified directory. + /// Returns a string[] array of the names of files and subdirectories in the specified directory. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, @@ -141,7 +141,7 @@ public static string[] GetFileSystemEntriesTransacted(KernelTransaction transact } /// Returns an array of file system entries that match the specified search criteria. - /// An string[] array of file system entries that match the specified search criteria. + /// Returns a string[] array of file system entries that match the specified search criteria. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, @@ -169,7 +169,7 @@ public static string[] GetFileSystemEntriesTransacted(KernelTransaction transact } /// Gets an array of all the file names and directory names that match a in a specified path, and optionally searches subdirectories. - /// An string[] array of file system entries that match the specified search criteria. + /// Returns a string[] array of file system entries that match the specified search criteria. /// /// The EnumerateFileSystemEntries and GetFileSystemEntries methods differ as follows: When you use EnumerateFileSystemEntries, /// you can start enumerating the collection of entries before the whole collection is returned; when you use GetFileSystemEntries, diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetFiles.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetFiles.cs index 2572a0fdd..31fd31578 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetFiles.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetFiles.cs @@ -35,7 +35,7 @@ public static partial class Directory #region .NET /// Returns the names of files (including their paths) in the specified directory. - /// An array of the full names (including paths) for the files in the specified directory, or an empty array if no files are found. + /// Returns an array of the full names (including paths) for the files in the specified directory, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. @@ -59,7 +59,7 @@ public static string[] GetFiles(string path) /// Returns the names of files (including their paths) that match the specified search pattern in the specified directory. - /// An array of the full names (including paths) for the files in the specified directory that match the specified search pattern, or an empty array if no files are found. + /// Returns an array of the full names (including paths) for the files in the specified directory that match the specified search pattern, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. @@ -88,7 +88,7 @@ public static string[] GetFiles(string path, string searchPattern) /// Returns the names of files (including their paths) that match the specified search pattern in the current directory, and optionally searches subdirectories. - /// An array of the full names (including paths) for the files in the specified directory that match the specified search pattern and option, or an empty array if no files are found. + /// Returns an array of the full names (including paths) for the files in the specified directory that match the specified search pattern and option, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. @@ -125,7 +125,7 @@ public static string[] GetFiles(string path, string searchPattern, SearchOption /// [AlphaFS] Returns the names of files (including their paths) in the specified directory. - /// An array of the full names (including paths) for the files in the specified directory, or an empty array if no files are found. + /// Returns an array of the full names (including paths) for the files in the specified directory, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. @@ -149,7 +149,7 @@ public static string[] GetFilesTransacted(KernelTransaction transaction, string } /// [AlphaFS] Returns the names of files (including their paths) that match the specified search pattern in the specified directory. - /// An array of the full names (including paths) for the files in the specified directory that match the specified search pattern, or an empty array if no files are found. + /// Returns an array of the full names (including paths) for the files in the specified directory that match the specified search pattern, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. @@ -178,7 +178,7 @@ public static string[] GetFilesTransacted(KernelTransaction transaction, string } /// [AlphaFS] Returns the names of files (including their paths) that match the specified search pattern in the current directory, and optionally searches subdirectories. - /// An array of the full names (including paths) for the files in the specified directory that match the specified search pattern and option, or an empty array if no files are found. + /// Returns an array of the full names (including paths) for the files in the specified directory that match the specified search pattern and option, or an empty array if no files are found. /// /// The returned file names are appended to the supplied parameter. /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetLastAccessTime.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetLastAccessTime.cs index e5e0d95a5..5e77772be 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetLastAccessTime.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetLastAccessTime.cs @@ -29,7 +29,7 @@ public static partial class Directory #region .NET /// Gets the date and time that the specified directory was last accessed. - /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. + /// Returns a structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The directory for which to obtain access date and time information. [SecurityCritical] public static DateTime GetLastAccessTime(string path) @@ -38,7 +38,7 @@ public static DateTime GetLastAccessTime(string path) } /// Gets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. - /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in UTC time. + /// Returns a structure set to the date and time that the specified directory was last accessed. This value is expressed in UTC time. /// The directory for which to obtain access date and time information. [SecurityCritical] public static DateTime GetLastAccessTimeUtc(string path) @@ -49,7 +49,7 @@ public static DateTime GetLastAccessTimeUtc(string path) #endregion // .NET /// [AlphaFS] Gets the date and time that the specified directory was last accessed. - /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. + /// Returns a structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The directory for which to obtain access date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -61,7 +61,7 @@ public static DateTime GetLastAccessTime(string path, PathFormat pathFormat) /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. - /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in UTC time. + /// Returns a structure set to the date and time that the specified directory was last accessed. This value is expressed in UTC time. /// The directory for which to obtain access date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -73,7 +73,7 @@ public static DateTime GetLastAccessTimeUtc(string path, PathFormat pathFormat) #region Transactional /// [AlphaFS] Gets the date and time that the specified directory was last accessed. - /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. + /// Returns a structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The transaction. /// The directory for which to obtain access date and time information. [SecurityCritical] @@ -83,7 +83,7 @@ public static DateTime GetLastAccessTimeTransacted(KernelTransaction transaction } /// [AlphaFS] Gets the date and time that the specified directory was last accessed. - /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. + /// Returns a structure set to the date and time that the specified directory was last accessed. This value is expressed in local time. /// The transaction. /// The directory for which to obtain access date and time information. /// Indicates the format of the path parameter(s). @@ -96,7 +96,7 @@ public static DateTime GetLastAccessTimeTransacted(KernelTransaction transaction /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. - /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in UTC time. + /// Returns a structure set to the date and time that the specified directory was last accessed. This value is expressed in UTC time. /// The transaction. /// The directory for which to obtain access date and time information. [SecurityCritical] @@ -106,7 +106,7 @@ public static DateTime GetLastAccessTimeUtcTransacted(KernelTransaction transact } /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. - /// A structure set to the date and time that the specified directory was last accessed. This value is expressed in UTC time. + /// Returns a structure set to the date and time that the specified directory was last accessed. This value is expressed in UTC time. /// The transaction. /// The directory for which to obtain access date and time information. /// Indicates the format of the path parameter(s). diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetLastWriteTime.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetLastWriteTime.cs index b83a51b0b..2ec9e32a4 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetLastWriteTime.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetLastWriteTime.cs @@ -29,7 +29,7 @@ public static partial class Directory #region .NET /// Gets the date and time that the specified directory was last written to. - /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. + /// Returns a structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The directory for which to obtain write date and time information. [SecurityCritical] public static DateTime GetLastWriteTime(string path) @@ -40,7 +40,7 @@ public static DateTime GetLastWriteTime(string path) /// Gets the date and time, in coordinated universal time (UTC) time, that the specified directory was last written to. - /// A structure set to the date and time that the specified directory was last written to. This value is expressed in UTC time. + /// Returns a structure set to the date and time that the specified directory was last written to. This value is expressed in UTC time. /// The directory for which to obtain write date and time information. [SecurityCritical] public static DateTime GetLastWriteTimeUtc(string path) @@ -51,7 +51,7 @@ public static DateTime GetLastWriteTimeUtc(string path) #endregion // .NET /// [AlphaFS] Gets the date and time that the specified directory was last written to. - /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. + /// Returns a structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The directory for which to obtain write date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -63,7 +63,7 @@ public static DateTime GetLastWriteTime(string path, PathFormat pathFormat) /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC) time, that the specified directory was last written to. - /// A structure set to the date and time that the specified directory was last written to. This value is expressed in UTC time. + /// Returns a structure set to the date and time that the specified directory was last written to. This value is expressed in UTC time. /// The directory for which to obtain write date and time information. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -75,7 +75,7 @@ public static DateTime GetLastWriteTimeUtc(string path, PathFormat pathFormat) #region Transactional /// [AlphaFS] Gets the date and time that the specified directory was last written to. - /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. + /// Returns a structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The transaction. /// The directory for which to obtain write date and time information. [SecurityCritical] @@ -85,7 +85,7 @@ public static DateTime GetLastWriteTimeTransacted(KernelTransaction transaction, } /// [AlphaFS] Gets the date and time that the specified directory was last written to. - /// A structure set to the date and time that the specified directory was last written to. This value is expressed in local time. + /// Returns a structure set to the date and time that the specified directory was last written to. This value is expressed in local time. /// The transaction. /// The directory for which to obtain write date and time information. /// Indicates the format of the path parameter(s). @@ -98,7 +98,7 @@ public static DateTime GetLastWriteTimeTransacted(KernelTransaction transaction, /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC) time, that the specified directory was last written to. - /// A structure set to the date and time that the specified directory was last written to. This value is expressed in UTC time. + /// Returns a structure set to the date and time that the specified directory was last written to. This value is expressed in UTC time. /// The transaction. /// The directory for which to obtain write date and time information. [SecurityCritical] @@ -108,7 +108,7 @@ public static DateTime GetLastWriteTimeUtcTransacted(KernelTransaction transacti } /// [AlphaFS] Gets the date and time, in coordinated universal time (UTC) time, that the specified directory was last written to. - /// A structure set to the date and time that the specified directory was last written to. This value is expressed in UTC time. + /// Returns a structure set to the date and time that the specified directory was last written to. This value is expressed in UTC time. /// The transaction. /// The directory for which to obtain write date and time information. /// Indicates the format of the path parameter(s). diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs index c21acf058..e076a4b3a 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetLogicalDrives.cs @@ -29,7 +29,7 @@ public static partial class Directory #region .NET /// Retrieves the names of the logical drives on the Computer in the form "drive letter:\". - /// An array of type that represents the logical drives on the Computer. + /// Returns an array of type that represents the logical drives on the Computer. [SecurityCritical] public static string[] GetLogicalDrives() { @@ -40,7 +40,7 @@ public static string[] GetLogicalDrives() /// [AlphaFS] Retrieves the names of the logical drives on the Computer in the form "drive letter:\". - /// An array of type that represents the logical drives on the Computer. + /// Returns an array of type that represents the logical drives on the Computer. /// Retrieve logical drives as known by the Environment. /// Retrieve only when accessible (IsReady) logical drives. [SecurityCritical] diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetProperties.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetProperties.cs index b41a84547..fcfd5631a 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetProperties.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetProperties.cs @@ -36,7 +36,7 @@ public static partial class Directory /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// - /// A dictionary mapping the keys mentioned above to their respective aggregated values. + /// Returns a dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// @@ -59,7 +59,7 @@ public static Dictionary GetProperties(string path) /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// - /// A dictionary mapping the keys mentioned above to their respective aggregated values. + /// Returns a dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// @@ -83,7 +83,7 @@ public static Dictionary GetProperties(string path, PathFormat pat /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// - /// A dictionary mapping the keys mentioned above to their respective aggregated values. + /// Returns a dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// @@ -107,7 +107,7 @@ public static Dictionary GetProperties(string path, DirectoryEnume /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// - /// A dictionary mapping the keys mentioned above to their respective aggregated values. + /// Returns a dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// @@ -134,7 +134,7 @@ public static Dictionary GetProperties(string path, DirectoryEnume /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// - /// A dictionary mapping the keys mentioned above to their respective aggregated values. + /// Returns a dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// @@ -157,7 +157,7 @@ public static Dictionary GetPropertiesTransacted(KernelTransaction /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// - /// A dictionary mapping the keys mentioned above to their respective aggregated values. + /// Returns a dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// @@ -182,7 +182,7 @@ public static Dictionary GetPropertiesTransacted(KernelTransaction /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// - /// A dictionary mapping the keys mentioned above to their respective aggregated values. + /// Returns a dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// @@ -206,7 +206,7 @@ public static Dictionary GetPropertiesTransacted(KernelTransaction /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// - /// A dictionary mapping the keys mentioned above to their respective aggregated values. + /// Returns a dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// @@ -234,7 +234,7 @@ public static Dictionary GetPropertiesTransacted(KernelTransaction /// Size: is the total size of enumerated objects. /// Error: is the total number of errors encountered during enumeration. /// - /// A dictionary mapping the keys mentioned above to their respective aggregated values. + /// Returns a dictionary mapping the keys mentioned above to their respective aggregated values. /// Directory: is an object which has attribute without one. /// /// diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Move.cs b/AlphaFS/Filesystem/Directory Class/Directory.Move.cs index 160e42c5d..159aa269c 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Move.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Move.cs @@ -58,7 +58,7 @@ public static void Move(string sourcePath, string destinationPath) /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// @@ -81,7 +81,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Pat /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// @@ -104,7 +104,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// @@ -130,7 +130,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// @@ -153,7 +153,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// @@ -179,7 +179,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// @@ -206,7 +206,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// @@ -234,7 +234,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// @@ -257,7 +257,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// @@ -285,7 +285,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// @@ -307,13 +307,13 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin /// [AlphaFS] Moves a file or a directory and its contents to a new location, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method does not work across disk volumes unless contains . /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Compression.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Compression.cs index d83ada9d7..e25ac3a73 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Compression.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Compression.cs @@ -103,7 +103,7 @@ public void Decompress(DirectoryEnumerationOptions options) [SecurityCritical] public void DisableCompression() { - Device.ToggleCompressionCore(Transaction, LongFullName, false, PathFormat.LongFullPath); + Device.FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, false, PathFormat.LongFullPath); } #endregion // DisableCompression @@ -118,7 +118,7 @@ public void DisableCompression() [SecurityCritical] public void EnableCompression() { - Device.ToggleCompressionCore(Transaction, LongFullName, true, PathFormat.LongFullPath); + Device.FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, true, PathFormat.LongFullPath); } #endregion // EnableCompression diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs index a9c784b01..06126dfb8 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs @@ -32,7 +32,7 @@ public sealed partial class DirectoryInfo /// [AlphaFS] Copies a instance and its contents to a new path. - /// A new instance if the directory was completely copied. + /// Returns a new instance if the directory was completely copied. /// /// Use this method to prevent overwriting of an existing directory by default. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -56,7 +56,7 @@ public DirectoryInfo CopyTo(string destinationPath) /// [AlphaFS] Copies a instance and its contents to a new path. - /// A new instance if the directory was completely copied. + /// Returns a new instance if the directory was completely copied. /// /// Use this method to prevent overwriting of an existing directory by default. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -95,7 +95,7 @@ public DirectoryInfo CopyTo(string destinationPath, PathFormat pathFormat) /// /// /// The destination directory path. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, bool preserveDates) { @@ -121,7 +121,7 @@ public DirectoryInfo CopyTo(string destinationPath, bool preserveDates) /// /// /// The destination directory path. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, bool preserveDates, PathFormat pathFormat) @@ -210,7 +210,7 @@ public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, Pat /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates) { @@ -240,7 +240,7 @@ public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, boo /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) @@ -255,7 +255,7 @@ public DirectoryInfo CopyTo(string destinationPath, CopyOptions copyOptions, boo /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// and the possibility of notifying the application of its progress through a callback function. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. @@ -284,7 +284,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, Co /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// and the possibility of notifying the application of its progress through a callback function. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. @@ -314,7 +314,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, Co /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// and the possibility of notifying the application of its progress through a callback function. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. @@ -329,7 +329,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, Co /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] @@ -344,7 +344,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bo /// [AlphaFS] Copies an existing directory to a new directory, allowing the overwriting of an existing directory, can be specified. /// and the possibility of notifying the application of its progress through a callback function. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing directory. @@ -359,7 +359,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bo /// /// The destination directory path. /// that specify how the directory is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the directory has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). @@ -378,7 +378,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bo /// [AlphaFS] Copy/move a Non-/Transacted file or directory including its children to a new location, /// or can be specified, and the possibility of notifying the application of its progress through a callback function. /// - /// A class with details of the Copy or Move action. + /// Returns a class with details of the Copy or Move action. /// /// Option is recommended for very large file transfers. /// You cannot use the Move method to overwrite an existing file, unless contains . @@ -391,7 +391,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bo /// /// /// The destination directory path. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// that specify how the file is to be copied. This parameter can be null. /// that specify how the file is to be moved. This parameter can be null. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CreateJunction.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CreateJunction.cs index 8388cce7f..03baf384d 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CreateJunction.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CreateJunction.cs @@ -29,14 +29,10 @@ public sealed partial class DirectoryInfo { /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// - ///   - /// The directory must be empty and reside on a local volume. - /// - /// - ///   - /// 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. + /// The directory must be empty and reside on a local volume. + /// 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. /// /// /// @@ -57,14 +53,10 @@ public void CreateJunction(string junctionPath) /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// - ///   - /// The directory must be empty and reside on a local volume. - /// - /// - ///   - /// 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. + /// The directory must be empty and reside on a local volume. + /// 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. /// /// /// @@ -86,14 +78,10 @@ public void CreateJunction(string junctionPath, PathFormat pathFormat) /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// - ///   - /// The directory must be empty and reside on a local volume. - /// - /// - ///   - /// 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. + /// The directory must be empty and reside on a local volume. + /// 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. /// /// /// @@ -115,14 +103,10 @@ public void CreateJunction(string junctionPath, bool overwrite) /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// - ///   - /// The directory must be empty and reside on a local volume. - /// - /// - ///   - /// 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. + /// The directory must be empty and reside on a local volume. + /// 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. /// /// /// @@ -145,14 +129,10 @@ public void CreateJunction(string junctionPath, bool overwrite, PathFormat pathF /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// - ///   - /// The directory must be empty and reside on a local volume. - /// - /// - ///   - /// 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. + /// The directory must be empty and reside on a local volume. + /// 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. /// /// /// @@ -175,14 +155,10 @@ public void CreateJunction(string junctionPath, bool overwrite, bool copyTargetT /// [AlphaFS] Converts the instance into a directory junction instance (similar to CMD command: "MKLINK /J"). /// - ///   - /// The directory must be empty and reside on a local volume. - /// - /// - ///   - /// 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. + /// The directory must be empty and reside on a local volume. + /// 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. /// /// /// diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.DeleteJunction.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.DeleteJunction.cs index b9f8dcffb..5d3c55b4b 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.DeleteJunction.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.DeleteJunction.cs @@ -28,11 +28,7 @@ namespace Alphaleonis.Win32.Filesystem public sealed partial class DirectoryInfo { /// [AlphaFS] Removes the directory junction. - ///   - /// - /// Only the directory junction is removed, not the target. - /// - /// A instance referencing the junction point. + /// Only the directory junction is removed, not the target. /// /// /// @@ -50,11 +46,7 @@ public void DeleteJunction() /// [AlphaFS] Removes the directory junction. - ///   - /// - /// Only the directory junction is removed, not the target. - /// - /// A instance referencing the junction point. + /// Only the directory junction is removed, not the target. /// /// /// diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Encryption.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Encryption.cs index f11e3efe5..db8a95dca 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Encryption.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Encryption.cs @@ -65,7 +65,7 @@ public void Decrypt(bool recursive) #region DisableEncryption /// [AlphaFS] Disables encryption of the specified directory and the files in it. It does not affect encryption of subdirectories below the indicated directory. - /// true on success, false otherwise. + /// true on success; otherwise, false. /// This method will create/change the file "Desktop.ini" and wil set Encryption value: "Disable=0" [SecurityCritical] public void DisableEncryption() @@ -78,7 +78,7 @@ public void DisableEncryption() #region EnableEncryption /// [AlphaFS] Enables encryption of the specified directory and the files in it. It does not affect encryption of subdirectories below the indicated directory. - /// true on success, false otherwise. + /// true on success; otherwise, false. /// This method will create/change the file "Desktop.ini" and wil set Encryption value: "Disable=1" [SecurityCritical] public void EnableEncryption() diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateAlternateDataStreams.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateAlternateDataStreams.cs index ea701187a..33fb37c33 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateAlternateDataStreams.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateAlternateDataStreams.cs @@ -26,8 +26,8 @@ namespace Alphaleonis.Win32.Filesystem { public sealed partial class DirectoryInfo { - /// [AlphaFS] Returns an enumerable collection of instances for the directory. - /// An enumerable collection of instances for the directory. + /// [AlphaFS] Returns an collection of instances for the directory. + /// Returns an collection of instances for the directory. [SecurityCritical] public IEnumerable EnumerateAlternateDataStreams() { diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateDirectories.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateDirectories.cs index 791dd322d..1c8898d58 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateDirectories.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateDirectories.cs @@ -30,8 +30,8 @@ public sealed partial class DirectoryInfo { #region .NET - /// Returns an enumerable collection of directory information in the current directory. - /// An enumerable collection of directories in the current directory. + /// Returns an collection of directory information in the current directory. + /// Returns an collection of directories in the current directory. /// /// /// @@ -44,8 +44,8 @@ public IEnumerable EnumerateDirectories() return Directory.EnumerateFileSystemEntryInfosCore(true, Transaction, LongFullName, Path.WildcardStarMatchAll, null, null, null, PathFormat.LongFullPath); } - /// Returns an enumerable collection of directory information that matches a specified search pattern. - /// An enumerable collection of directories that matches . + /// Returns an collection of directory information that matches a specified search pattern. + /// Returns an collection of directories that matches . /// /// /// @@ -63,8 +63,8 @@ public IEnumerable EnumerateDirectories(string searchPattern) return Directory.EnumerateFileSystemEntryInfosCore(true, Transaction, LongFullName, searchPattern, null, null, null, PathFormat.LongFullPath); } - /// Returns an enumerable collection of directory information that matches a specified search pattern and search subdirectory option. - /// An enumerable collection of directories that matches and . + /// Returns an collection of directory information that matches a specified search pattern and search subdirectory option. + /// Returns an collection of directories that matches and . /// /// /// @@ -90,8 +90,8 @@ public IEnumerable EnumerateDirectories(string searchPattern, Sea - /// [AlphaFS] Returns an enumerable collection of directory information in the current directory. - /// An enumerable collection of directories in the current directory. + /// [AlphaFS] Returns an collection of directory information in the current directory. + /// Returns an collection of directories in the current directory. /// /// /// @@ -105,8 +105,8 @@ public IEnumerable EnumerateDirectories(DirectoryEnumerationOptio return Directory.EnumerateFileSystemEntryInfosCore(true, Transaction, LongFullName, Path.WildcardStarMatchAll, null, options, null, PathFormat.LongFullPath); } - /// Returns an enumerable collection of directory information that matches a specified search pattern. - /// An enumerable collection of directories that matches . + /// Returns an collection of directory information that matches a specified search pattern. + /// Returns an collection of directories that matches . /// /// /// diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateFileSystemInfos.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateFileSystemInfos.cs index 0576a592c..57490ddac 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateFileSystemInfos.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateFileSystemInfos.cs @@ -31,8 +31,8 @@ public sealed partial class DirectoryInfo { #region .NET - /// Returns an enumerable collection of file system information in the current directory. - /// An enumerable collection of file system information in the current directory. + /// Returns an collection of file system information in the current directory. + /// Returns an collection of file system information in the current directory. /// /// /// @@ -46,8 +46,8 @@ public IEnumerable EnumerateFileSystemInfos() return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, Path.WildcardStarMatchAll, null, null, null, PathFormat.LongFullPath); } - /// Returns an enumerable collection of file system information that matches a specified search pattern. - /// An enumerable collection of file system information objects that matches . + /// Returns an collection of file system information that matches a specified search pattern. + /// Returns an collection of file system information objects that matches . /// /// /// @@ -66,8 +66,8 @@ public IEnumerable EnumerateFileSystemInfos(string searchPattern return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, searchPattern, null, null, null, PathFormat.LongFullPath); } - /// Returns an enumerable collection of file system information that matches a specified search pattern and search subdirectory option. - /// An enumerable collection of file system information objects that matches and . + /// Returns an collection of file system information that matches a specified search pattern and search subdirectory option. + /// Returns an collection of file system information objects that matches and . /// /// /// @@ -94,8 +94,8 @@ public IEnumerable EnumerateFileSystemInfos(string searchPattern - /// [AlphaFS] Returns an enumerable collection of file system information in the current directory. - /// An enumerable collection of file system information in the current directory. + /// [AlphaFS] Returns an collection of file system information in the current directory. + /// Returns an collection of file system information in the current directory. /// /// /// @@ -110,8 +110,8 @@ public IEnumerable EnumerateFileSystemInfos(DirectoryEnumeration return Directory.EnumerateFileSystemEntryInfosCore(null, Transaction, LongFullName, Path.WildcardStarMatchAll, null, options, null, PathFormat.LongFullPath); } - /// [AlphaFS] Returns an enumerable collection of file system information that matches a specified search pattern. - /// An enumerable collection of file system information objects that matches . + /// [AlphaFS] Returns an collection of file system information that matches a specified search pattern. + /// Returns an collection of file system information objects that matches . /// /// /// diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateFiles.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateFiles.cs index 7879fbca8..24b13a8b9 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateFiles.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.EnumerateFiles.cs @@ -30,8 +30,8 @@ public sealed partial class DirectoryInfo { #region .NET - /// Returns an enumerable collection of file information in the current directory. - /// An enumerable collection of the files in the current directory. + /// Returns an collection of file information in the current directory. + /// Returns an collection of the files in the current directory. /// /// /// @@ -44,8 +44,8 @@ public IEnumerable EnumerateFiles() return Directory.EnumerateFileSystemEntryInfosCore(false, Transaction, LongFullName, Path.WildcardStarMatchAll, null, null, null, PathFormat.LongFullPath); } - /// Returns an enumerable collection of file information that matches a search pattern. - /// An enumerable collection of files that matches . + /// Returns an collection of file information that matches a search pattern. + /// Returns an collection of files that matches . /// /// /// @@ -63,8 +63,8 @@ public IEnumerable EnumerateFiles(string searchPattern) return Directory.EnumerateFileSystemEntryInfosCore(false, Transaction, LongFullName, searchPattern, null, null, null, PathFormat.LongFullPath); } - /// Returns an enumerable collection of file information that matches a specified search pattern and search subdirectory option. - /// An enumerable collection of files that matches and . + /// Returns an collection of file information that matches a specified search pattern and search subdirectory option. + /// Returns an collection of files that matches and . /// /// /// @@ -90,8 +90,8 @@ public IEnumerable EnumerateFiles(string searchPattern, SearchOption s - /// Returns an enumerable collection of file information in the current directory. - /// An enumerable collection of the files in the current directory. + /// Returns an collection of file information in the current directory. + /// Returns an collection of the files in the current directory. /// /// /// @@ -105,8 +105,8 @@ public IEnumerable EnumerateFiles(DirectoryEnumerationOptions options) return Directory.EnumerateFileSystemEntryInfosCore(false, Transaction, LongFullName, Path.WildcardStarMatchAll, null, options, null, PathFormat.LongFullPath); } - /// Returns an enumerable collection of file information that matches a search pattern. - /// An enumerable collection of files that matches . + /// Returns an collection of file information that matches a search pattern. + /// Returns an collection of files that matches . /// /// /// diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetAccessControl.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetAccessControl.cs index 56c15f1b6..2290ac565 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetAccessControl.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetAccessControl.cs @@ -29,7 +29,7 @@ public sealed partial class DirectoryInfo #region .NET /// Gets a object that encapsulates the access control list (ACL) entries for the directory described by the current DirectoryInfo object. - /// A object that encapsulates the access control rules for the directory. + /// Returns a object that encapsulates the access control rules for the directory. [SecurityCritical] public DirectorySecurity GetAccessControl() @@ -39,7 +39,7 @@ public DirectorySecurity GetAccessControl() /// Gets a object that encapsulates the specified type of access control list (ACL) entries for the directory described by the current object. /// One of the values that specifies the type of access control list (ACL) information to receive. - /// A object that encapsulates the access control rules for the file described by the path parameter. + /// Returns a object that encapsulates the access control rules for the file described by the path parameter. [SecurityCritical] public DirectorySecurity GetAccessControl(AccessControlSections includeSections) diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetDirectories.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetDirectories.cs index 96b008064..56d5f28a9 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetDirectories.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetDirectories.cs @@ -31,7 +31,7 @@ public sealed partial class DirectoryInfo #region .NET /// Returns the subdirectories of the current directory. - /// An array of objects. + /// Returns an array of objects. /// If there are no subdirectories, this method returns an empty array. This method is not recursive. /// /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names @@ -51,7 +51,7 @@ public DirectoryInfo[] GetDirectories() } /// Returns an array of directories in the current matching the given search criteria. - /// An array of type matching . + /// Returns an array of type matching . /// /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names /// before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. @@ -75,7 +75,7 @@ public DirectoryInfo[] GetDirectories(string searchPattern) } /// Returns an array of directories in the current matching the given search criteria and using a value to determine whether to search subdirectories. - /// An array of type matching . + /// Returns an array of type matching . /// If there are no subdirectories, or no subdirectories match the searchPattern parameter, this method returns an empty array. /// /// The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFileId.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFileId.cs index 562e4ca1f..cc3af7c04 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFileId.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFileId.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Filesystem public sealed partial class DirectoryInfo { /// [AlphaFS] Gets the unique identifier for the directory. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// Directory IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a directory can change over time. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFileSystemInfos.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFileSystemInfos.cs index 5edb6f3cf..d32b7c7b8 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFileSystemInfos.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFileSystemInfos.cs @@ -32,7 +32,7 @@ public sealed partial class DirectoryInfo #region .NET /// Returns an array of strongly typed entries representing all the files and subdirectories in a directory. - /// An array of strongly typed entries. + /// Returns an array of strongly typed entries. /// /// For subdirectories, the objects returned by this method can be cast to the derived class . /// Use the value returned by the property to determine whether the represents a file or a directory. @@ -61,7 +61,7 @@ public FileSystemInfo[] GetFileSystemInfos() /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// - /// An array of strongly typed entries. + /// Returns an array of strongly typed entries. /// /// For subdirectories, the objects returned by this method can be cast to the derived class . /// Use the value returned by the property to determine whether the represents a file or a directory. @@ -94,7 +94,7 @@ public FileSystemInfo[] GetFileSystemInfos(string searchPattern) /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// - /// An array of strongly typed entries. + /// Returns an array of strongly typed entries. /// /// For subdirectories, the objects returned by this method can be cast to the derived class . /// Use the value returned by the property to determine whether the represents a file or a directory. diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFiles.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFiles.cs index b8abbf52d..de00417cf 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFiles.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.GetFiles.cs @@ -31,7 +31,7 @@ public sealed partial class DirectoryInfo #region .NET /// Returns a file list from the current directory. - /// An array of type . + /// Returns an array of type . /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// If there are no files in the , this method returns an empty array. /// @@ -57,7 +57,7 @@ public FileInfo[] GetFiles() /// This parameter can contain a combination of valid literal path and wildcard /// ( and ) characters, but does not support regular expressions. /// - /// An array of type . + /// Returns an array of type . /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// If there are no files in the , this method returns an empty array. /// @@ -87,7 +87,7 @@ public FileInfo[] GetFiles(string searchPattern) /// One of the enumeration values that specifies whether the /// should include only the current directory or should include all subdirectories. /// - /// An array of type . + /// Returns an array of type . /// The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required. /// If there are no files in the , this method returns an empty array. /// diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.MoveTo.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.MoveTo.cs index deac938f2..b46a877a9 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.MoveTo.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.MoveTo.cs @@ -65,7 +65,7 @@ public void MoveTo(string destinationPath) /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A new instance if the directory was completely moved. + /// Returns a new instance if the directory was completely moved. /// /// /// @@ -95,7 +95,7 @@ public DirectoryInfo MoveTo(string destinationPath, PathFormat pathFormat) /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A new instance if the directory was completely moved. + /// Returns a new instance if the directory was completely moved. /// /// /// @@ -125,7 +125,7 @@ public DirectoryInfo MoveTo(string destinationPath, MoveOptions moveOptions) /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A new instance if the directory was completely moved. + /// Returns a new instance if the directory was completely moved. /// /// /// @@ -158,7 +158,7 @@ public DirectoryInfo MoveTo(string destinationPath, MoveOptions moveOptions, Pat /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// @@ -196,7 +196,7 @@ public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, Co /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two directories have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// /// diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.ToString.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.ToString.cs index 2acfb4b88..9d1d02eab 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.ToString.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.ToString.cs @@ -24,7 +24,7 @@ namespace Alphaleonis.Win32.Filesystem public sealed partial class DirectoryInfo { /// Returns the original path that was passed by the user. - /// A string that represents this object. + /// Returns a string that represents this object. public override string ToString() { return DisplayPath; diff --git a/AlphaFS/Device/DiskSpaceInfo.cs b/AlphaFS/Filesystem/DiskSpaceInfo.cs similarity index 98% rename from AlphaFS/Device/DiskSpaceInfo.cs rename to AlphaFS/Filesystem/DiskSpaceInfo.cs index f4bda31a2..4635a9129 100644 --- a/AlphaFS/Device/DiskSpaceInfo.cs +++ b/AlphaFS/Filesystem/DiskSpaceInfo.cs @@ -69,7 +69,7 @@ public DiskSpaceInfo(string driveName) // 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:\"). + // 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(driveName, false); } @@ -126,7 +126,7 @@ public long ClusterSize /// Gets the name of a drive. - /// This property is the name assigned to the drive, such as: "C:\" or "D:\". + /// This property is the name assigned to the drive, such as: C:\ or "D:\". public string DriveName { get; private set; } @@ -265,7 +265,7 @@ private void Reset() /// Returns the drive name. - /// A string that represents this object. + /// Returns a string that represents this object. public override string ToString() { return DriveName; diff --git a/AlphaFS/Filesystem/File Class/File.AppendText.cs b/AlphaFS/Filesystem/File Class/File.AppendText.cs index cbb10707b..4e2e059dc 100644 --- a/AlphaFS/Filesystem/File Class/File.AppendText.cs +++ b/AlphaFS/Filesystem/File Class/File.AppendText.cs @@ -32,7 +32,7 @@ public static partial class File #region .NET /// Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. - /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. + /// Returns a stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesn�t exist or it is on an unmapped drive). @@ -49,7 +49,7 @@ public static StreamWriter AppendText(string path) /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. - /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. + /// Returns a stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesn�t exist or it is on an unmapped drive). @@ -65,7 +65,7 @@ public static StreamWriter AppendText(string path, PathFormat pathFormat) /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. - /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. + /// Returns a stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesn�t exist or it is on an unmapped drive). @@ -82,7 +82,7 @@ public static StreamWriter AppendText(string path, Encoding encoding, PathFormat /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. - /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. + /// Returns a stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesn�t exist or it is on an unmapped drive). @@ -100,7 +100,7 @@ public static StreamWriter AppendText(string path, Encoding encoding) /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. - /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. + /// Returns a stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesn�t exist or it is on an unmapped drive). @@ -116,7 +116,7 @@ public static StreamWriter AppendTextTransacted(KernelTransaction transaction, s /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. - /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. + /// Returns a stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesn�t exist or it is on an unmapped drive). @@ -133,7 +133,7 @@ public static StreamWriter AppendTextTransacted(KernelTransaction transaction, s /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. - /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. + /// Returns a stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesn�t exist or it is on an unmapped drive). @@ -150,7 +150,7 @@ public static StreamWriter AppendTextTransacted(KernelTransaction transaction, s } /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. - /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. + /// Returns a stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesn�t exist or it is on an unmapped drive). @@ -169,7 +169,7 @@ public static StreamWriter AppendTextTransacted(KernelTransaction transaction, s /// [AlphaFS] Creates a that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. - /// A stream writer that appends UTF-8 encoded text to the specified file or to a new file. + /// Returns a stream writer that appends UTF-8 encoded text to the specified file or to a new file. /// path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. /// path is null. /// The specified path is invalid (for example, the directory doesn�t exist or it is on an unmapped drive). diff --git a/AlphaFS/Filesystem/File Class/File.Compress.cs b/AlphaFS/Filesystem/File Class/File.Compress.cs index ae1e9f32d..85ecb9ecd 100644 --- a/AlphaFS/Filesystem/File Class/File.Compress.cs +++ b/AlphaFS/Filesystem/File Class/File.Compress.cs @@ -30,7 +30,7 @@ public static partial class File [SecurityCritical] public static void Compress(string path) { - Device.ToggleCompressionCore(null, path, true, PathFormat.RelativePath); + Device.FileSystemHelper.ToggleCompressionCore(null, path, true, PathFormat.RelativePath); } @@ -40,7 +40,7 @@ public static void Compress(string path) [SecurityCritical] public static void Compress(string path, PathFormat pathFormat) { - Device.ToggleCompressionCore(null, path, true, pathFormat); + Device.FileSystemHelper.ToggleCompressionCore(null, path, true, pathFormat); } @@ -50,7 +50,7 @@ public static void Compress(string path, PathFormat pathFormat) [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path) { - Device.ToggleCompressionCore(transaction, path, true, PathFormat.RelativePath); + Device.FileSystemHelper.ToggleCompressionCore(transaction, path, true, PathFormat.RelativePath); } @@ -61,7 +61,7 @@ public static void CompressTransacted(KernelTransaction transaction, string path [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { - Device.ToggleCompressionCore(transaction, path, true, pathFormat); + Device.FileSystemHelper.ToggleCompressionCore(transaction, path, true, pathFormat); } } } diff --git a/AlphaFS/Filesystem/File Class/File.Copy.cs b/AlphaFS/Filesystem/File Class/File.Copy.cs index cad337be8..a988e7dac 100644 --- a/AlphaFS/Filesystem/File Class/File.Copy.cs +++ b/AlphaFS/Filesystem/File Class/File.Copy.cs @@ -85,7 +85,7 @@ public static void Copy(string sourcePath, string destinationPath, bool overwrit /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -109,7 +109,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Pat /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -136,7 +136,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, boo /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -160,7 +160,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -185,7 +185,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -210,7 +210,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -239,7 +239,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -264,7 +264,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -290,7 +290,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -301,7 +301,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates) { @@ -316,7 +316,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -327,7 +327,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult Copy(string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) @@ -345,7 +345,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -374,7 +374,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -404,7 +404,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -415,7 +415,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] @@ -434,7 +434,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -445,7 +445,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). @@ -465,7 +465,7 @@ public static CopyMoveResult Copy(string sourcePath, string destinationPath, Cop /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -491,7 +491,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -518,7 +518,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -530,7 +530,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates) { @@ -545,7 +545,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -557,7 +557,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] public static CopyMoveResult CopyTransacted(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) @@ -575,7 +575,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -605,7 +605,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -636,7 +636,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// /// @@ -648,7 +648,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] @@ -667,12 +667,12 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. /// If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior. /// - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// The transaction. /// The file to copy. /// The name of the destination file. This cannot be a directory. /// that specify how the file is to be copied. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). @@ -709,7 +709,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// Note that if you attempt to replace a file by moving a file of the same name into /// that directory, you get an IOException. /// - /// A class with the status of the Copy or Move action. + /// Returns a class with the status of the Copy or Move action. /// /// /// @@ -724,7 +724,7 @@ public static CopyMoveResult CopyTransacted(KernelTransaction transaction, strin /// The destination directory path plus file name. /// that specify how the file is to be copied. This parameter can be null. /// Flags that specify how the file or directory is to be moved. This parameter can be null. - /// true if original Timestamps must be preserved, false otherwise. This parameter is ignored for move operations. + /// true if original Timestamps must be preserved; otherwise, false. This parameter is ignored for move operations. /// A callback function that is called each time another portion of the file has been copied/moved. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// A instance containing Copy or Move action progress. diff --git a/AlphaFS/Filesystem/File Class/File.Create.cs b/AlphaFS/Filesystem/File Class/File.Create.cs index 36a1fc7e4..a3b3a2c33 100644 --- a/AlphaFS/Filesystem/File Class/File.Create.cs +++ b/AlphaFS/Filesystem/File Class/File.Create.cs @@ -37,7 +37,7 @@ public static partial class File /// Creates or overwrites a file in the specified path. /// The path and name of the file to create. - /// A that provides read/write access to the file specified in . + /// Returns a that provides read/write access to the file specified in . [SecurityCritical] public static FileStream Create(string path) { @@ -48,7 +48,7 @@ public static FileStream Create(string path) /// Creates or overwrites the specified file. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. - /// A with the specified buffer size that provides read/write access to the file specified in . + /// Returns a with the specified buffer size that provides read/write access to the file specified in . [SecurityCritical] public static FileStream Create(string path, int bufferSize) { @@ -60,7 +60,7 @@ public static FileStream Create(string path, int bufferSize) /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. - /// A new file with the specified buffer size. + /// Returns a new file with the specified buffer size. [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options) { @@ -73,7 +73,7 @@ public static FileStream Create(string path, int bufferSize, FileOptions options /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// One of the values that determines the access control and audit security for the file. - /// A new file with the specified buffer size, file options, and file security. + /// Returns a new file with the specified buffer size, file options, and file security. [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { @@ -86,7 +86,7 @@ public static FileStream Create(string path, int bufferSize, FileOptions options /// [AlphaFS] Creates or overwrites a file in the specified path. /// The path and name of the file to create. /// Indicates the format of the path parameter(s). - /// A that provides read/write access to the file specified in . + /// Returns a that provides read/write access to the file specified in . [SecurityCritical] public static FileStream Create(string path, PathFormat pathFormat) { @@ -98,7 +98,7 @@ public static FileStream Create(string path, PathFormat pathFormat) /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// Indicates the format of the path parameter(s). - /// A with the specified buffer size that provides read/write access to the file specified in . + /// Returns a with the specified buffer size that provides read/write access to the file specified in . [SecurityCritical] public static FileStream Create(string path, int bufferSize, PathFormat pathFormat) { @@ -111,7 +111,7 @@ public static FileStream Create(string path, int bufferSize, PathFormat pathForm /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// Indicates the format of the path parameter(s). - /// A new file with the specified buffer size. + /// Returns a new file with the specified buffer size. [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options, PathFormat pathFormat) { @@ -125,7 +125,7 @@ public static FileStream Create(string path, int bufferSize, FileOptions options /// One of the values that describes how to create or overwrite the file. /// One of the values that determines the access control and audit security for the file. /// Indicates the format of the path parameter(s). - /// A new file with the specified buffer size, file options, and file security. + /// Returns a new file with the specified buffer size, file options, and file security. [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity, PathFormat pathFormat) @@ -139,7 +139,7 @@ public static FileStream Create(string path, int bufferSize, FileOptions options /// [AlphaFS] Creates or overwrites a file in the specified path. /// The transaction. /// The path and name of the file to create. - /// A that provides read/write access to the file specified in . + /// Returns a that provides read/write access to the file specified in . [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path) { @@ -151,7 +151,7 @@ public static FileStream CreateTransacted(KernelTransaction transaction, string /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. - /// A with the specified buffer size that provides read/write access to the file specified in . + /// Returns a with the specified buffer size that provides read/write access to the file specified in . [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize) { @@ -164,7 +164,7 @@ public static FileStream CreateTransacted(KernelTransaction transaction, string /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. - /// A new file with the specified buffer size. + /// Returns a new file with the specified buffer size. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options) { @@ -178,7 +178,7 @@ public static FileStream CreateTransacted(KernelTransaction transaction, string /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// One of the values that determines the access control and audit security for the file. - /// A new file with the specified buffer size, file options, and file security. + /// Returns a new file with the specified buffer size, file options, and file security. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { @@ -190,7 +190,7 @@ public static FileStream CreateTransacted(KernelTransaction transaction, string /// The transaction. /// The path and name of the file to create. /// Indicates the format of the path parameter(s). - /// A that provides read/write access to the file specified in . + /// Returns a that provides read/write access to the file specified in . [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { @@ -203,7 +203,7 @@ public static FileStream CreateTransacted(KernelTransaction transaction, string /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// Indicates the format of the path parameter(s). - /// A with the specified buffer size that provides read/write access to the file specified in . + /// Returns a with the specified buffer size that provides read/write access to the file specified in . [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, PathFormat pathFormat) { @@ -217,7 +217,7 @@ public static FileStream CreateTransacted(KernelTransaction transaction, string /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// Indicates the format of the path parameter(s). - /// A new file with the specified buffer size. + /// Returns a new file with the specified buffer size. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options, PathFormat pathFormat) { @@ -232,7 +232,7 @@ public static FileStream CreateTransacted(KernelTransaction transaction, string /// One of the values that describes how to create or overwrite the file. /// One of the values that determines the access control and audit security for the file. /// Indicates the format of the path parameter(s). - /// A new file with the specified buffer size, file options, and file security. + /// Returns a new file with the specified buffer size, file options, and file security. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options, FileSecurity fileSecurity, PathFormat pathFormat) @@ -255,7 +255,7 @@ public static FileStream CreateTransacted(KernelTransaction transaction, string /// The option controls how you would like to share created file with other requesters. /// Indicates the format of the parameter. /// The number of bytes buffered for reads and writes to the file. - /// A that provides read/write access to the file specified in path. + /// Returns a that provides read/write access to the file specified in path. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive")] [SecurityCritical] @@ -282,7 +282,7 @@ internal static FileStream CreateFileStreamCore(KernelTransaction transaction, s /// Creates or opens a file, directory or I/O device. - /// A that provides read/write access to the file or directory specified by . + /// Returns a that provides read/write access to the file or directory specified by . /// /// To obtain a directory handle using CreateFile, specify the FILE_FLAG_BACKUP_SEMANTICS flag as part of dwFlagsAndAttributes. /// 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. @@ -348,7 +348,7 @@ internal static SafeFileHandle CreateFileCore(KernelTransaction transaction, str var lastError = Marshal.GetLastWin32Error(); - NativeMethods.IsValidHandle(safeHandle, lastError, pathLp, !continueOnException); + Utils.IsValidHandle(safeHandle, lastError, pathLp, !continueOnException); if (isAppend) diff --git a/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs b/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs index 50e4d6e02..f0e1404d7 100644 --- a/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs +++ b/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs @@ -33,7 +33,7 @@ public static partial class File #region Obsolete /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file. - /// See to run this method in an elevated state. + /// See to run this method from an elevated state. /// /// /// The operating system is older than Windows Vista. @@ -50,7 +50,7 @@ public static void CreateSymbolicLink(string symlinkFileName, string targetFileN /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file. - /// See to run this method in an elevated state. + /// See to run this method from an elevated state. /// /// /// The operating system is older than Windows Vista. @@ -68,7 +68,7 @@ public static void CreateSymbolicLink(string symlinkFileName, string targetFileN /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file as a transacted operation. - /// See to run this method in an elevated state. + /// See to run this method from an elevated state. /// /// /// The operating system is older than Windows Vista. @@ -86,7 +86,7 @@ public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, s /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file as a transacted operation. - /// See to run this method in an elevated state. + /// See to run this method from an elevated state. /// /// /// The operating system is older than Windows Vista. @@ -107,13 +107,12 @@ public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, s /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file. - ///   /// - /// Symbolic links can point to a non-existent target. - /// When creating a symbolic link, the operating system does not check to see if the target exists. - /// Symbolic links are reparse points. - /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. - /// See to run this method in an elevated state. + /// Symbolic links can point to a non-existent target. + /// When creating a symbolic link, the operating system does not check to see if the target exists. + /// Symbolic links are reparse points. + /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. + /// See to run this method from an elevated state. /// /// /// @@ -130,13 +129,12 @@ public static void CreateSymbolicLink(string symlinkFileName, string targetFileN /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file. - ///   /// - /// Symbolic links can point to a non-existent target. - /// When creating a symbolic link, the operating system does not check to see if the target exists. - /// Symbolic links are reparse points. - /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. - /// See to run this method in an elevated state. + /// Symbolic links can point to a non-existent target. + /// When creating a symbolic link, the operating system does not check to see if the target exists. + /// Symbolic links are reparse points. + /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. + /// See to run this method from an elevated state. /// /// /// @@ -154,13 +152,12 @@ public static void CreateSymbolicLink(string symlinkFileName, string targetFileN /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file as a transacted operation. - ///   /// - /// Symbolic links can point to a non-existent target. - /// When creating a symbolic link, the operating system does not check to see if the target exists. - /// Symbolic links are reparse points. - /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. - /// See to run this method in an elevated state. + /// Symbolic links can point to a non-existent target. + /// When creating a symbolic link, the operating system does not check to see if the target exists. + /// Symbolic links are reparse points. + /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. + /// See to run this method from an elevated state. /// /// /// @@ -178,13 +175,12 @@ public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, s /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file as a transacted operation. - ///   /// - /// Symbolic links can point to a non-existent target. - /// When creating a symbolic link, the operating system does not check to see if the target exists. - /// Symbolic links are reparse points. - /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. - /// See to run this method in an elevated state. + /// Symbolic links can point to a non-existent target. + /// When creating a symbolic link, the operating system does not check to see if the target exists. + /// Symbolic links are reparse points. + /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. + /// See to run this method from an elevated state. /// /// /// @@ -203,13 +199,12 @@ public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, s /// [AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK") to a file or directory as a transacted operation. - ///   /// - /// Symbolic links can point to a non-existent target. - /// When creating a symbolic link, the operating system does not check to see if the target exists. - /// Symbolic links are reparse points. - /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. - /// See to run this method in an elevated state. + /// Symbolic links can point to a non-existent target. + /// When creating a symbolic link, the operating system does not check to see if the target exists. + /// Symbolic links are reparse points. + /// There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path. + /// See to run this method from an elevated state. /// /// /// diff --git a/AlphaFS/Filesystem/File Class/File.CreateText.cs b/AlphaFS/Filesystem/File Class/File.CreateText.cs index aaa973570..50542982d 100644 --- a/AlphaFS/Filesystem/File Class/File.CreateText.cs +++ b/AlphaFS/Filesystem/File Class/File.CreateText.cs @@ -33,7 +33,7 @@ public static partial class File /// Creates or opens a file for writing UTF-8 encoded text. /// The file to be opened for writing. - /// A StreamWriter that writes to the specified file using UTF-8 encoding. + /// Returns a StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateText(string path) @@ -44,7 +44,7 @@ public static StreamWriter CreateText(string path) /// [AlphaFS] Creates or opens a file for writing UTF-8 encoded text. /// The file to be opened for writing. /// Indicates the format of the path parameter(s). - /// A StreamWriter that writes to the specified file using UTF-8 encoding. + /// Returns a StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateText(string path, PathFormat pathFormat) @@ -56,7 +56,7 @@ public static StreamWriter CreateText(string path, PathFormat pathFormat) /// The file to be opened for writing. /// The encoding that is applied to the contents of the file. /// Indicates the format of the path parameter(s). - /// A StreamWriter that writes to the specified file using UTF-8 encoding. + /// Returns a StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateText(string path, Encoding encoding, PathFormat pathFormat) @@ -67,7 +67,7 @@ public static StreamWriter CreateText(string path, Encoding encoding, PathFormat /// [AlphaFS] Creates or opens a file for writing UTF-8 encoded text. /// The transaction. /// The file to be opened for writing. - /// A StreamWriter that writes to the specified file using UTF-8 encoding. + /// Returns a StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateTextTransacted(KernelTransaction transaction, string path) @@ -80,7 +80,7 @@ public static StreamWriter CreateTextTransacted(KernelTransaction transaction, s /// The file to be opened for writing. /// The encoding that is applied to the contents of the file. /// Indicates the format of the path parameter(s). - /// A StreamWriter that writes to the specified file using UTF-8 encoding. + /// Returns a StreamWriter that writes to the specified file using UTF-8 encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public static StreamWriter CreateTextTransacted(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) @@ -97,7 +97,7 @@ public static StreamWriter CreateTextTransacted(KernelTransaction transaction, s /// The file to be opened for writing. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). - /// A that writes to the specified file using NativeMethods.DefaultFileBufferSize encoding. + /// Returns a that writes to the specified file using NativeMethods.DefaultFileBufferSize encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] internal static StreamWriter CreateTextCore(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) diff --git a/AlphaFS/Filesystem/File Class/File.Decompress.cs b/AlphaFS/Filesystem/File Class/File.Decompress.cs index b47cf1335..d6ab13554 100644 --- a/AlphaFS/Filesystem/File Class/File.Decompress.cs +++ b/AlphaFS/Filesystem/File Class/File.Decompress.cs @@ -30,7 +30,7 @@ public static partial class File [SecurityCritical] public static void Decompress(string path) { - Device.ToggleCompressionCore(null, path, false, PathFormat.RelativePath); + Device.FileSystemHelper.ToggleCompressionCore(null, path, false, PathFormat.RelativePath); } @@ -40,7 +40,7 @@ public static void Decompress(string path) [SecurityCritical] public static void Decompress(string path, PathFormat pathFormat) { - Device.ToggleCompressionCore(null, path, false, pathFormat); + Device.FileSystemHelper.ToggleCompressionCore(null, path, false, pathFormat); } @@ -50,7 +50,7 @@ public static void Decompress(string path, PathFormat pathFormat) [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path) { - Device.ToggleCompressionCore(transaction, path, false, PathFormat.RelativePath); + Device.FileSystemHelper.ToggleCompressionCore(transaction, path, false, PathFormat.RelativePath); } @@ -61,7 +61,7 @@ public static void DecompressTransacted(KernelTransaction transaction, string pa [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { - Device.ToggleCompressionCore(transaction, path, false, pathFormat); + Device.FileSystemHelper.ToggleCompressionCore(transaction, path, false, pathFormat); } } } diff --git a/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs b/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs index 93392ec2d..f9efaf6b1 100644 --- a/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs +++ b/AlphaFS/Filesystem/File Class/File.EnumerateAlternateDataStreams.cs @@ -29,7 +29,7 @@ public static partial class File { /// [AlphaFS] Enumerates all altername datastreams of the specified file. /// The path to the file to enumerate streams of. - /// An enumeration of instances. + /// Returns an enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreams(string path) { @@ -39,7 +39,7 @@ public static IEnumerable EnumerateAlternateDataStreams /// [AlphaFS] Enumerates all altername datastreams of the specified file. /// The path to the file to enumerate streams of. /// Indicates the format of the path parameter(s). - /// An enumeration of instances. + /// Returns an enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreams(string path, PathFormat pathFormat) { @@ -49,7 +49,7 @@ public static IEnumerable EnumerateAlternateDataStreams /// [AlphaFS] Enumerates all altername datastreams of the specified file. /// The transaction. /// The path to the file to enumerate streams of. - /// An enumeration of instances. + /// Returns an enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreamsTransacted(KernelTransaction transaction, string path) { @@ -60,7 +60,7 @@ public static IEnumerable EnumerateAlternateDataStreams /// The transaction. /// The path to the file to enumerate streams of. /// Indicates the format of the path parameter(s). - /// An enumeration of instances. + /// Returns an enumeration of instances. [SecurityCritical] public static IEnumerable EnumerateAlternateDataStreamsTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { @@ -74,7 +74,7 @@ public static IEnumerable EnumerateAlternateDataStreams /// The transaction. /// The path to the file or directory to enumerate streams of. /// Indicates the format of the path parameter(s). - /// An enumeration of instances. + /// Returns an enumeration of instances. [SecurityCritical] internal static IEnumerable EnumerateAlternateDataStreamsCore(KernelTransaction transaction, string path, PathFormat pathFormat) { diff --git a/AlphaFS/Filesystem/File Class/File.EnumerateHardlinks.cs b/AlphaFS/Filesystem/File Class/File.EnumerateHardlinks.cs index 900c31775..0e388df79 100644 --- a/AlphaFS/Filesystem/File Class/File.EnumerateHardlinks.cs +++ b/AlphaFS/Filesystem/File Class/File.EnumerateHardlinks.cs @@ -33,8 +33,8 @@ public static partial class File { #region EnumerateHardlinks - /// [AlphaFS] Creates an enumeration of all the hard links to the specified . - /// An enumerable collection of of all the hard links to the specified + /// [AlphaFS] Returns an collection of all the hard links to the specified . + /// Returns an collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The name of the file. /// Indicates the format of the path parameter(s). @@ -45,8 +45,8 @@ public static IEnumerable EnumerateHardlinks(string path, PathFormat pat return EnumerateHardlinksCore(null, path, pathFormat); } - /// [AlphaFS] Creates an enumeration of all the hard links to the specified . - /// An enumerable collection of of all the hard links to the specified + /// [AlphaFS] Returns an collection of all the hard links to the specified . + /// Returns an collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The name of the file. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hardlinks")] @@ -56,8 +56,8 @@ public static IEnumerable EnumerateHardlinks(string path) return EnumerateHardlinksCore(null, path, PathFormat.RelativePath); } - /// [AlphaFS] Creates an enumeration of all the hard links to the specified . - /// An enumerable collection of of all the hard links to the specified + /// [AlphaFS] Returns an collection of all the hard links to the specified . + /// Returns an collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The transaction. /// The name of the file. @@ -69,8 +69,8 @@ public static IEnumerable EnumerateHardlinksTransacted(KernelTransaction return EnumerateHardlinksCore(transaction, path, pathFormat); } - /// [AlphaFS] Creates an enumeration of all the hard links to the specified . - /// An enumerable collection of of all the hard links to the specified + /// [AlphaFS] Returns an collection of all the hard links to the specified . + /// Returns an collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The transaction. /// The name of the file. @@ -85,8 +85,8 @@ public static IEnumerable EnumerateHardlinksTransacted(KernelTransaction #region Internal Methods - /// [AlphaFS] Creates an enumeration of all the hard links to the specified . - /// An enumerable collection of of all the hard links to the specified + /// [AlphaFS] Returns an collection of all the hard links to the specified . + /// Returns an collection of of all the hard links to the specified /// The operating system is older than Windows Vista. /// The transaction. /// The name of the file. @@ -116,7 +116,7 @@ internal static IEnumerable EnumerateHardlinksCore(KernelTransaction tra { var lastError = Marshal.GetLastWin32Error(); - if (!NativeMethods.IsValidHandle(safeHandle, false)) + if (!Utils.IsValidHandle(safeHandle, false)) { switch ((uint) lastError) { diff --git a/AlphaFS/Filesystem/File Class/File.GetAccessControl.cs b/AlphaFS/Filesystem/File Class/File.GetAccessControl.cs index dbd7e3603..84f8b1838 100644 --- a/AlphaFS/Filesystem/File Class/File.GetAccessControl.cs +++ b/AlphaFS/Filesystem/File Class/File.GetAccessControl.cs @@ -32,7 +32,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class File { /// Gets a object that encapsulates the access control list (ACL) entries for a specified file. - /// A object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -44,7 +44,7 @@ public static FileSecurity GetAccessControl(string path) } /// Gets a object that encapsulates the access control list (ACL) entries for a specified file. - /// A object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -58,7 +58,7 @@ public static FileSecurity GetAccessControl(string path, AccessControlSections i /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for a specified file. - /// A object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -71,7 +71,7 @@ public static FileSecurity GetAccessControl(string path, PathFormat pathFormat) } /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for a specified file. - /// A object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -86,7 +86,7 @@ public static FileSecurity GetAccessControl(string path, AccessControlSections i /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for a specified file handle. - /// A object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -98,7 +98,7 @@ public static FileSecurity GetAccessControl(SafeFileHandle handle) } /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for a specified file handle. - /// A object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -114,7 +114,7 @@ public static FileSecurity GetAccessControl(SafeFileHandle handle, AccessControl /// [AlphaFS] Gets an object for a particular file or directory. - /// An object that encapsulates the access control rules for the file or directory described by the parameter. + /// Returns an object that encapsulates the access control rules for the file or directory described by the parameter. /// /// /// @@ -225,7 +225,7 @@ private static T GetSecurityDescriptor(uint lastError, bool isFolder, string if (lastError != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException(lastError, !Utils.IsNullOrWhiteSpace(path) ? path : null); - if (!NativeMethods.IsValidHandle(securityDescriptor, false)) + if (!Utils.IsValidHandle(securityDescriptor, false)) throw new IOException(Resources.Returned_Invalid_Security_Descriptor); diff --git a/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs b/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs index fdc6e35b2..ae7900fcb 100644 --- a/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs +++ b/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs @@ -35,7 +35,7 @@ public static partial class File #region GetChangeTime /// [AlphaFS] Gets the change date and time of the specified file. - /// A structure set to the change date and time for the specified file. This value is expressed in local time. + /// Returns a structure set to the change date and time for the specified file. This value is expressed in local time. /// The operating system is older than Windows Vista. /// The file for which to obtain creation date and time information. /// Indicates the format of the path parameter(s). @@ -47,7 +47,7 @@ public static DateTime GetChangeTime(string path, PathFormat pathFormat) /// [AlphaFS] Gets the change date and time of the specified file. - /// A structure set to the change date and time for the specified file. This value is expressed in local time. + /// Returns a structure set to the change date and time for the specified file. This value is expressed in local time. /// The operating system is older than Windows Vista. /// The file for which to obtain creation date and time information. [SecurityCritical] @@ -57,7 +57,7 @@ public static DateTime GetChangeTime(string path) } /// [AlphaFS] Gets the change date and time of the specified file. - /// A structure set to the change date and time for the specified file. This value is expressed in local time. + /// Returns a structure set to the change date and time for the specified file. This value is expressed in local time. /// The operating system is older than Windows Vista. /// An open handle to the file or directory from which to retrieve information. [SecurityCritical] @@ -67,7 +67,7 @@ public static DateTime GetChangeTime(SafeFileHandle safeFileHandle) } /// [AlphaFS] Gets the change date and time of the specified file. - /// A structure set to the change date and time for the specified file. This value is expressed in local time. + /// Returns a structure set to the change date and time for the specified file. This value is expressed in local time. /// The operating system is older than Windows Vista. /// The transaction. /// The file for which to obtain creation date and time information. @@ -79,7 +79,7 @@ public static DateTime GetChangeTimeTransacted(KernelTransaction transaction, st } /// [AlphaFS] Gets the change date and time of the specified file. - /// A structure set to the change date and time for the specified file. This value is expressed in local time. + /// Returns a structure set to the change date and time for the specified file. This value is expressed in local time. /// The operating system is older than Windows Vista. /// The transaction. /// The file for which to obtain creation date and time information. @@ -95,7 +95,7 @@ public static DateTime GetChangeTimeTransacted(KernelTransaction transaction, st #region GetChangeTimeUtc /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified file. - /// A structure set to the change date and time for the specified file. This value is expressed in UTC time. + /// Returns a structure set to the change date and time for the specified file. This value is expressed in UTC time. /// The operating system is older than Windows Vista. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. /// Indicates the format of the path parameter(s). @@ -106,7 +106,7 @@ public static DateTime GetChangeTimeUtc(string path, PathFormat pathFormat) } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified file. - /// A structure set to the change date and time for the specified file. This value is expressed in UTC time. + /// Returns a structure set to the change date and time for the specified file. This value is expressed in UTC time. /// The operating system is older than Windows Vista. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. [SecurityCritical] @@ -116,7 +116,7 @@ public static DateTime GetChangeTimeUtc(string path) } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified file. - /// A structure set to the change date and time for the specified file. This value is expressed in UTC time. + /// Returns a structure set to the change date and time for the specified file. This value is expressed in UTC time. /// The operating system is older than Windows Vista. /// An open handle to the file or directory from which to retrieve information. [SecurityCritical] @@ -126,7 +126,7 @@ public static DateTime GetChangeTimeUtc(SafeFileHandle safeFileHandle) } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified file. - /// A structure set to the change date and time for the specified file. This value is expressed in UTC time. + /// Returns a structure set to the change date and time for the specified file. This value is expressed in UTC time. /// The operating system is older than Windows Vista. /// The transaction. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. @@ -138,7 +138,7 @@ public static DateTime GetChangeTimeUtcTransacted(KernelTransaction transaction, } /// [AlphaFS] Gets the change date and time, in Coordinated Universal Time (UTC) format, of the specified file. - /// A structure set to the change date and time for the specified file. This value is expressed in UTC time. + /// Returns a structure set to the change date and time for the specified file. This value is expressed in UTC time. /// The operating system is older than Windows Vista. /// The transaction. /// The file for which to obtain change date and time information, in Coordinated Universal Time (UTC) format. @@ -154,7 +154,7 @@ public static DateTime GetChangeTimeUtcTransacted(KernelTransaction transaction, #region Internal Methods /// Gets the change date and time of the specified file. - /// A structure set to the change date and time for the specified file. This value is expressed in local time. + /// Returns a structure set to the change date and time for the specified file. This value is expressed in local time. /// Use either or , not both. /// /// @@ -186,7 +186,7 @@ internal static DateTime GetChangeTimeCore(KernelTransaction transaction, SafeFi try { - NativeMethods.IsValidHandle(safeFileHandle); + Utils.IsValidHandle(safeFileHandle); using (var safeBuffer = new SafeGlobalMemoryBufferHandle(IntPtr.Size + Marshal.SizeOf(typeof(NativeMethods.FILE_BASIC_INFO)))) { diff --git a/AlphaFS/Filesystem/File Class/File.GetCompressedSize.cs b/AlphaFS/Filesystem/File Class/File.GetCompressedSize.cs index b0f3c27a6..534a029a2 100644 --- a/AlphaFS/Filesystem/File Class/File.GetCompressedSize.cs +++ b/AlphaFS/Filesystem/File Class/File.GetCompressedSize.cs @@ -125,7 +125,7 @@ internal static long GetCompressedSizeCore(KernelTransaction transaction, string if (fileSizeLow == Win32Errors.ERROR_INVALID_FILE_SIZE && fileSizeHigh == 0) NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp); - return NativeMethods.ToLong(fileSizeHigh, fileSizeLow); + return Utils.ToLong(fileSizeHigh, fileSizeLow); } #endregion // Internal Methods diff --git a/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs b/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs index d855448c0..c2699bfd4 100644 --- a/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs +++ b/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class File { /// [AlphaFS] Gets the unique identifier for a file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The path to the file. [SecurityCritical] @@ -41,7 +41,7 @@ public static FileIdInfo GetFileIdInfo(string path) /// [AlphaFS] Gets the unique identifier for a file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The path to the file. /// Indicates the format of the path parameter(s). @@ -55,7 +55,7 @@ public static FileIdInfo GetFileIdInfo(string path, PathFormat pathFormat) /// [AlphaFS] Gets the unique identifier for a file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// The path to the file. @@ -67,7 +67,7 @@ public static FileIdInfo GetFileIdTransacted(KernelTransaction transaction, stri /// [AlphaFS] Gets the unique identifier for a file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// The path to the file. @@ -82,7 +82,7 @@ public static FileIdInfo GetFileIdTransacted(KernelTransaction transaction, stri /// [AlphaFS] Retrieves file information for the specified . - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// A connected to the open file or directory from which to retrieve the information. [SecurityCritical] @@ -101,7 +101,7 @@ public static FileIdInfo GetFileIdInfo(SafeFileHandle handle) /// [AlphaFS] Gets the unique identifier for a file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// The path to the file. diff --git a/AlphaFS/Filesystem/File Class/File.GetFileInfoByHandle.cs b/AlphaFS/Filesystem/File Class/File.GetFileInfoByHandle.cs index 21d714190..9393317d3 100644 --- a/AlphaFS/Filesystem/File Class/File.GetFileInfoByHandle.cs +++ b/AlphaFS/Filesystem/File Class/File.GetFileInfoByHandle.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class File { /// [AlphaFS] Retrieves file information for the specified file. - /// A object containing the requested information. + /// Returns a object containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The path to the file. [SecurityCritical] @@ -41,7 +41,7 @@ public static ByHandleFileInfo GetFileInfoByHandle(string path) /// [AlphaFS] Retrieves file information for the specified file. - /// A object containing the requested information. + /// Returns a object containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The path to the file. /// Indicates the format of the path parameter(s). @@ -53,7 +53,7 @@ public static ByHandleFileInfo GetFileInfoByHandle(string path, PathFormat pathF /// [AlphaFS] Retrieves file information for the specified file. - /// A object containing the requested information. + /// Returns a object containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// The path to the file. @@ -65,7 +65,7 @@ public static ByHandleFileInfo GetFileInfoByHandleTransacted(KernelTransaction t /// [AlphaFS] Retrieves file information for the specified file. - /// A object containing the requested information. + /// Returns a object containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// The path to the file. @@ -80,13 +80,13 @@ public static ByHandleFileInfo GetFileInfoByHandleTransacted(KernelTransaction t /// [AlphaFS] Retrieves file information for the specified . - /// A object containing the requested information. - /// A object containing the requested information. + /// Returns a object containing the requested information. + /// Returns a object containing the requested information. /// A connected to the open file or directory from which to retrieve the information. [SecurityCritical] public static ByHandleFileInfo GetFileInfoByHandle(SafeFileHandle handle) { - NativeMethods.IsValidHandle(handle); + Utils.IsValidHandle(handle); NativeMethods.BY_HANDLE_FILE_INFORMATION info; @@ -102,7 +102,7 @@ public static ByHandleFileInfo GetFileInfoByHandle(SafeFileHandle handle) /// [AlphaFS] Retrieves file information for the specified file. - /// A object containing the requested information. + /// Returns a object containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. /// The transaction. /// The path to the file. diff --git a/AlphaFS/Filesystem/File Class/File.GetLinkTargetInfo.cs b/AlphaFS/Filesystem/File Class/File.GetLinkTargetInfo.cs index bcabf7bd4..92a4fec8c 100644 --- a/AlphaFS/Filesystem/File Class/File.GetLinkTargetInfo.cs +++ b/AlphaFS/Filesystem/File Class/File.GetLinkTargetInfo.cs @@ -108,7 +108,7 @@ internal static LinkTargetInfo GetLinkTargetInfoCore(KernelTransaction transacti using (var safeHandle = CreateFileCore(transaction, reparsePath, eAttributes, null, FileMode.Open, 0, FileShare.ReadWrite, pathFormat != PathFormat.LongFullPath, continueOnException, pathFormat)) - return null != safeHandle ? Device.GetLinkTargetInfo(safeHandle, reparsePath) : null; + return null != safeHandle ? Device.FileSystemHelper.GetLinkTargetInfo(safeHandle, reparsePath) : null; } } } diff --git a/AlphaFS/Filesystem/File Class/File.GetSize.cs b/AlphaFS/Filesystem/File Class/File.GetSize.cs index 1d0e2dd2c..4ce5bdd7c 100644 --- a/AlphaFS/Filesystem/File Class/File.GetSize.cs +++ b/AlphaFS/Filesystem/File Class/File.GetSize.cs @@ -226,7 +226,7 @@ internal static SafeFindFileHandle FindFirstStreamNative(KernelTransaction trans var lastError = Marshal.GetLastWin32Error(); - return NativeMethods.IsValidHandle(safeFindFileHandle, false) ? safeFindFileHandle : null; + return Utils.IsValidHandle(safeFindFileHandle, false) ? safeFindFileHandle : null; } } } diff --git a/AlphaFS/Filesystem/File Class/File.Move.cs b/AlphaFS/Filesystem/File Class/File.Move.cs index 8869b5a5e..3d5bef9f6 100644 --- a/AlphaFS/Filesystem/File Class/File.Move.cs +++ b/AlphaFS/Filesystem/File Class/File.Move.cs @@ -57,7 +57,7 @@ public static void Move(string sourcePath, string destinationPath) /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . @@ -83,7 +83,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Pat /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . @@ -109,7 +109,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . @@ -138,7 +138,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . @@ -164,7 +164,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . @@ -191,7 +191,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . @@ -219,8 +219,8 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with the status of the Move action. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . @@ -251,7 +251,7 @@ public static CopyMoveResult Move(string sourcePath, string destinationPath, Mov /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . @@ -278,7 +278,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . @@ -306,7 +306,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . @@ -335,7 +335,7 @@ public static CopyMoveResult MoveTransacted(KernelTransaction transaction, strin /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// This method works across disk volumes. /// Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an . diff --git a/AlphaFS/Filesystem/File Class/File.Open.cs b/AlphaFS/Filesystem/File Class/File.Open.cs index 9bd14fd36..d7b84bce4 100644 --- a/AlphaFS/Filesystem/File Class/File.Open.cs +++ b/AlphaFS/Filesystem/File Class/File.Open.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System; using Microsoft.Win32.SafeHandles; using System.IO; using System.Security; @@ -38,7 +37,7 @@ public static partial class File /// Opens a on the specified path with read/write access. /// The file to open. /// A 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. - /// A opened in the specified mode and path, with read/write access and not shared. + /// Returns a opened in the specified mode and path, with read/write access and not shared. [SecurityCritical] public static FileStream Open(string path, FileMode mode) { @@ -49,7 +48,7 @@ public static FileStream Open(string path, FileMode mode) /// The file to open. /// A 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. /// A value that specifies the operations that can be performed on the file. - /// An unshared that provides access to the specified file, with the specified mode and access. + /// Returns an unshared that provides access to the specified file, with the specified mode and access. [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access) { @@ -61,7 +60,7 @@ public static FileStream Open(string path, FileMode mode, FileAccess access) /// A 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. /// A value that specifies the operations that can be performed on the file. /// A value specifying the type of access other threads have to the file. - /// A on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. + /// Returns a on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share) { @@ -78,7 +77,7 @@ public static FileStream Open(string path, FileMode mode, FileAccess access, Fil /// of existing files are retained or overwritten. /// /// Indicates the format of the path parameter(s). - /// A opened in the specified mode and path, with read/write access and not shared. + /// Returns a opened in the specified mode and path, with read/write access and not shared. [SecurityCritical] public static FileStream Open(string path, FileMode mode, PathFormat pathFormat) { @@ -483,7 +482,7 @@ public static FileStream Open(string path, FileMode mode, FileSystemRights right /// A 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. /// - /// A opened in the specified mode and path, with read/write access and not shared. + /// Returns a opened in the specified mode and path, with read/write access and not shared. [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode) { @@ -498,7 +497,7 @@ public static FileStream OpenTransacted(KernelTransaction transaction, string pa /// of existing files are retained or overwritten. /// /// Indicates the format of the path parameter(s). - /// A opened in the specified mode and path, with read/write access and not shared. + /// Returns a opened in the specified mode and path, with read/write access and not shared. [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, PathFormat pathFormat) { @@ -568,7 +567,7 @@ public static FileStream OpenTransacted(KernelTransaction transaction, string pa /// A value that specifies the operations that can be performed on the file. /// A value specifying the type of access other threads have to the file. /// Indicates the format of the path parameter(s). - /// A on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. + /// Returns a on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option. [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, PathFormat pathFormat) { diff --git a/AlphaFS/Filesystem/File Class/File.OpenBackupRead.cs b/AlphaFS/Filesystem/File Class/File.OpenBackupRead.cs index d176d9205..683bf2f82 100644 --- a/AlphaFS/Filesystem/File Class/File.OpenBackupRead.cs +++ b/AlphaFS/Filesystem/File Class/File.OpenBackupRead.cs @@ -30,7 +30,7 @@ public static partial class File /// [AlphaFS] Opens the specified file for reading purposes bypassing security attributes. /// The file path to open. /// Indicates the format of the path parameter(s). - /// A on the specified path, having the read-only mode and sharing options. + /// Returns a on the specified path, having the read-only mode and sharing options. [SecurityCritical] public static FileStream OpenBackupRead(string path, PathFormat pathFormat) { @@ -39,7 +39,7 @@ public static FileStream OpenBackupRead(string path, PathFormat pathFormat) /// [AlphaFS] Opens the specified file for reading purposes bypassing security attributes. This method is simpler to use then BackupFileStream to read only file's data stream. /// The file path to open. - /// A on the specified path, having the read-only mode and sharing options. + /// Returns a on the specified path, having the read-only mode and sharing options. [SecurityCritical] public static FileStream OpenBackupRead(string path) { @@ -50,7 +50,7 @@ public static FileStream OpenBackupRead(string path) /// The transaction. /// The file path to open. /// Indicates the format of the path parameter(s). - /// A on the specified path, having the read-only mode and sharing options. + /// Returns a on the specified path, having the read-only mode and sharing options. [SecurityCritical] public static FileStream OpenBackupReadTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { @@ -60,7 +60,7 @@ public static FileStream OpenBackupReadTransacted(KernelTransaction transaction, /// [AlphaFS] Opens the specified file for reading purposes bypassing security attributes. /// The transaction. /// The file path to open. - /// A on the specified path, having the read-only mode and sharing options. + /// Returns a on the specified path, having the read-only mode and sharing options. [SecurityCritical] public static FileStream OpenBackupReadTransacted(KernelTransaction transaction, string path) { diff --git a/AlphaFS/Filesystem/File Class/File.OpenRead.cs b/AlphaFS/Filesystem/File Class/File.OpenRead.cs index 6e3c0adb2..a7b3c2527 100644 --- a/AlphaFS/Filesystem/File Class/File.OpenRead.cs +++ b/AlphaFS/Filesystem/File Class/File.OpenRead.cs @@ -29,7 +29,7 @@ public static partial class File { /// Opens an existing file for reading. /// The file to be opened for reading. - /// A read-only on the specified path. + /// Returns a read-only on the specified path. /// /// This method is equivalent to the (string, FileMode, FileAccess, FileShare) constructor overload with a /// value of Open, a value of Read and a value of Read. @@ -43,7 +43,7 @@ public static FileStream OpenRead(string path) /// [AlphaFS] Opens an existing file for reading. /// The file to be opened for reading. /// Indicates the format of the path parameter(s). - /// A read-only on the specified path. + /// Returns a read-only on the specified path. /// /// This method is equivalent to the (string, FileMode, FileAccess, FileShare) constructor overload with a /// value of Open, a value of Read and a value of Read. @@ -57,7 +57,7 @@ public static FileStream OpenRead(string path, PathFormat pathFormat) /// [AlphaFS] Opens an existing file for reading. /// The transaction. /// The file to be opened for reading. - /// A read-only on the specified path. + /// Returns a read-only on the specified path. /// /// This method is equivalent to the (string, FileMode, FileAccess, FileShare) constructor overload with a /// value of Open, a value of Read and a value of Read. @@ -72,7 +72,7 @@ public static FileStream OpenReadTransacted(KernelTransaction transaction, strin /// The transaction. /// The file to be opened for reading. /// Indicates the format of the path parameter(s). - /// A read-only on the specified path. + /// Returns a read-only on the specified path. /// /// This method is equivalent to the (string, FileMode, FileAccess, FileShare) constructor overload with a /// value of Open, a value of Read and a value of Read. diff --git a/AlphaFS/Filesystem/File Class/File.OpenText.cs b/AlphaFS/Filesystem/File Class/File.OpenText.cs index 660279384..047b31e8a 100644 --- a/AlphaFS/Filesystem/File Class/File.OpenText.cs +++ b/AlphaFS/Filesystem/File Class/File.OpenText.cs @@ -30,7 +30,7 @@ public static partial class File { /// Opens an existing UTF-8 encoded text file for reading. /// The file to be opened for reading. - /// A on the specified path. + /// Returns a on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] @@ -42,7 +42,7 @@ public static StreamReader OpenText(string path) /// [AlphaFS] Opens an existing UTF-8 encoded text file for reading. /// The file to be opened for reading. /// Indicates the format of the path parameter(s). - /// A on the specified path. + /// Returns a on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] @@ -55,7 +55,7 @@ public static StreamReader OpenText(string path, PathFormat pathFormat) /// The file to be opened for reading. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). - /// A on the specified path. + /// Returns a on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] @@ -68,7 +68,7 @@ public static StreamReader OpenText(string path, Encoding encoding, PathFormat p /// [AlphaFS] Opens an existing encoded text file for reading. /// The file to be opened for reading. /// The applied to the contents of the file. - /// A on the specified path. + /// Returns a on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] @@ -80,7 +80,7 @@ public static StreamReader OpenText(string path, Encoding encoding) /// [AlphaFS] Opens an existing UTF-8 encoded text file for reading. /// The transaction. /// The file to be opened for reading. - /// A on the specified path. + /// Returns a on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public static StreamReader OpenTextTransacted(KernelTransaction transaction, string path) @@ -92,7 +92,7 @@ public static StreamReader OpenTextTransacted(KernelTransaction transaction, str /// The transaction. /// The file to be opened for reading. /// Indicates the format of the path parameter(s). - /// A on the specified path. + /// Returns a on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public static StreamReader OpenTextTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) @@ -105,7 +105,7 @@ public static StreamReader OpenTextTransacted(KernelTransaction transaction, str /// The file to be opened for reading. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). - /// A on the specified path. + /// Returns a on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public static StreamReader OpenTextTransacted(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) @@ -117,7 +117,7 @@ public static StreamReader OpenTextTransacted(KernelTransaction transaction, str /// The transaction. /// The file to be opened for reading. /// The applied to the contents of the file. - /// A on the specified path. + /// Returns a on the specified path. /// This method is equivalent to the (String) constructor overload. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public static StreamReader OpenTextTransacted(KernelTransaction transaction, string path, Encoding encoding) diff --git a/AlphaFS/Filesystem/File Class/File.OpenWrite.cs b/AlphaFS/Filesystem/File Class/File.OpenWrite.cs index ae16e1abc..ac8f9c6c3 100644 --- a/AlphaFS/Filesystem/File Class/File.OpenWrite.cs +++ b/AlphaFS/Filesystem/File Class/File.OpenWrite.cs @@ -28,7 +28,7 @@ public static partial class File { /// Opens an existing file or creates a new file for writing. /// The file to be opened for writing. - /// An unshared object on the specified path with access. + /// Returns an unshared object on the specified path with access. /// This method is equivalent to the (String, FileMode, FileAccess, FileShare) constructor overload with file mode set to OpenOrCreate, the access set to Write, and the share mode set to None. [SecurityCritical] public static FileStream OpenWrite(string path) @@ -39,7 +39,7 @@ public static FileStream OpenWrite(string path) /// [AlphaFS] Opens an existing file or creates a new file for writing. /// The file to be opened for writing. /// Indicates the format of the path parameter(s). - /// An unshared object on the specified path with access. + /// Returns an unshared object on the specified path with access. /// This method is equivalent to the (String, FileMode, FileAccess, FileShare) constructor overload with file mode set to OpenOrCreate, the access set to Write, and the share mode set to None. [SecurityCritical] public static FileStream OpenWrite(string path, PathFormat pathFormat) @@ -50,7 +50,7 @@ public static FileStream OpenWrite(string path, PathFormat pathFormat) /// [AlphaFS] Opens an existing file or creates a new file for writing. /// The transaction. /// The file to be opened for writing. - /// An unshared object on the specified path with access. + /// Returns an unshared object on the specified path with access. /// This method is equivalent to the (String, FileMode, FileAccess, FileShare) constructor overload with file mode set to OpenOrCreate, the access set to Write, and the share mode set to None. [SecurityCritical] public static FileStream OpenWriteTransacted(KernelTransaction transaction, string path) @@ -62,7 +62,7 @@ public static FileStream OpenWriteTransacted(KernelTransaction transaction, stri /// The transaction. /// The file to be opened for writing. /// Indicates the format of the path parameter(s). - /// An unshared object on the specified path with access. + /// Returns an unshared object on the specified path with access. /// This method is equivalent to the (String, FileMode, FileAccess, FileShare) constructor overload with file mode set to OpenOrCreate, the access set to Write, and the share mode set to None. [SecurityCritical] public static FileStream OpenWriteTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) diff --git a/AlphaFS/Filesystem/File Class/File.ReadAllBytes.cs b/AlphaFS/Filesystem/File Class/File.ReadAllBytes.cs index 6d86de657..351312534 100644 --- a/AlphaFS/Filesystem/File Class/File.ReadAllBytes.cs +++ b/AlphaFS/Filesystem/File Class/File.ReadAllBytes.cs @@ -32,7 +32,7 @@ public static partial class File /// Opens a binary file, reads the contents of the file into a byte array, and then closes the file. /// The file to open for reading. - /// A byte array containing the contents of the file. + /// Returns a byte array containing the contents of the file. [SecurityCritical] public static byte[] ReadAllBytes(string path) { @@ -42,7 +42,7 @@ public static byte[] ReadAllBytes(string path) /// [AlphaFS] Opens a binary file, reads the contents of the file into a byte array, and then closes the file. /// The file to open for reading. /// Indicates the format of the path parameter(s). - /// A byte array containing the contents of the file. + /// Returns a byte array containing the contents of the file. [SecurityCritical] public static byte[] ReadAllBytes(string path, PathFormat pathFormat) { @@ -55,7 +55,7 @@ public static byte[] ReadAllBytes(string path, PathFormat pathFormat) /// [AlphaFS] Opens a binary file, reads the contents of the file into a byte array, and then closes the file. /// The transaction. /// The file to open for reading. - /// A byte array containing the contents of the file. + /// Returns a byte array containing the contents of the file. [SecurityCritical] public static byte[] ReadAllBytesTransacted(KernelTransaction transaction, string path) { @@ -66,7 +66,7 @@ public static byte[] ReadAllBytesTransacted(KernelTransaction transaction, strin /// The transaction. /// The file to open for reading. /// Indicates the format of the path parameter(s). - /// A byte array containing the contents of the file. + /// Returns a byte array containing the contents of the file. [SecurityCritical] public static byte[] ReadAllBytesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { @@ -84,7 +84,7 @@ public static byte[] ReadAllBytesTransacted(KernelTransaction transaction, strin /// The transaction. /// The file to open for reading. /// Indicates the format of the path parameter(s). - /// A byte array containing the contents of the file. + /// Returns a byte array containing the contents of the file. [SecurityCritical] internal static byte[] ReadAllBytesCore(KernelTransaction transaction, string path, PathFormat pathFormat) { diff --git a/AlphaFS/Filesystem/File Class/File.ReadAllLines.cs b/AlphaFS/Filesystem/File Class/File.ReadAllLines.cs index 81251a6fb..acdaa3fd4 100644 --- a/AlphaFS/Filesystem/File Class/File.ReadAllLines.cs +++ b/AlphaFS/Filesystem/File Class/File.ReadAllLines.cs @@ -130,7 +130,7 @@ public static string[] ReadAllLinesTransacted(KernelTransaction transaction, str /// The file to open for reading. /// The applied to the contents of the file. /// Indicates the format of the path parameter(s). - /// An IEnumerable string containing all lines of the file. + /// Returns an IEnumerable string containing all lines of the file. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] internal static IEnumerable ReadAllLinesCore(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) diff --git a/AlphaFS/Filesystem/File Class/File.SetAccessControl.cs b/AlphaFS/Filesystem/File Class/File.SetAccessControl.cs index aba09e2ec..7f099d06e 100644 --- a/AlphaFS/Filesystem/File Class/File.SetAccessControl.cs +++ b/AlphaFS/Filesystem/File Class/File.SetAccessControl.cs @@ -263,7 +263,7 @@ internal static void SetAccessControlCore(string path, SafeFileHandle handle, Ob else { - if (NativeMethods.IsValidHandle(handle)) + if (Utils.IsValidHandle(handle)) { lastError = (int) Security.NativeMethods.SetSecurityInfo(handle, SE_OBJECT_TYPE.SE_FILE_OBJECT, securityInfo, pOwner, pGroup, pDacl, pSacl); diff --git a/AlphaFS/Filesystem/File Class/File.cs b/AlphaFS/Filesystem/File Class/File.cs index 1ebcdc936..63cd51732 100644 --- a/AlphaFS/Filesystem/File Class/File.cs +++ b/AlphaFS/Filesystem/File Class/File.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System.Diagnostics.CodeAnalysis; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.AppendText.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.AppendText.cs index 3d940c4ae..0273ac65c 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.AppendText.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.AppendText.cs @@ -30,7 +30,7 @@ partial class FileInfo #region .NET /// Creates a that appends text to the file represented by this instance of the . - /// A new + /// Returns a new [SecurityCritical] public StreamWriter AppendText() { @@ -39,7 +39,7 @@ public StreamWriter AppendText() /// Creates a that appends text to the file represented by this instance of the . /// The character to use. - /// A new + /// Returns a new [SecurityCritical] public StreamWriter AppendText(Encoding encoding) { diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Compress.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Compress.cs index 226e1d811..0b9be20db 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Compress.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Compress.cs @@ -31,7 +31,7 @@ partial class FileInfo [SecurityCritical] public void Compress() { - Device.ToggleCompressionCore(Transaction, LongFullName, true, PathFormat.LongFullPath); + Device.FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, true, PathFormat.LongFullPath); } #endregion // AlphaFS diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.CopyToMoveTo.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.CopyToMoveTo.cs index ee6b3b42e..abb45b7b9 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.CopyToMoveTo.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.CopyToMoveTo.cs @@ -32,7 +32,7 @@ partial class FileInfo #region .NET /// Copies an existing file to a new file, disallowing the overwriting of an existing file. - /// A new instance with a fully qualified path. + /// Returns a new instance with a fully qualified path. /// /// Use this method to prevent overwriting of an existing file by default. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -56,7 +56,7 @@ public FileInfo CopyTo(string destinationPath) } /// Copies an existing file to a new file, allowing the overwriting of an existing file. - /// A new instance with a fully qualified path. + /// Returns a new instance with a fully qualified path. /// /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -86,7 +86,7 @@ public FileInfo CopyTo(string destinationPath, bool overwrite) #region AlphaFS /// [AlphaFS] Copies an existing file to a new file, disallowing the overwriting of an existing file. - /// A new instance with a fully qualified path. + /// Returns a new instance with a fully qualified path. /// /// Use this method to prevent overwriting of an existing file by default. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -113,7 +113,7 @@ public FileInfo CopyTo(string destinationPath, PathFormat pathFormat) /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file. - /// A new instance with a fully qualified path. + /// Returns a new instance with a fully qualified path. /// /// Use this method to allow or prevent overwriting of an existing file. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -141,7 +141,7 @@ public FileInfo CopyTo(string destinationPath, bool overwrite, PathFormat pathFo /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. - /// A new instance with a fully qualified path. + /// Returns a new instance with a fully qualified path. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. @@ -167,7 +167,7 @@ public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions) } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. - /// A new instance with a fully qualified path. + /// Returns a new instance with a fully qualified path. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. @@ -196,7 +196,7 @@ public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, PathForm /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. - /// A new instance with a fully qualified path. + /// Returns a new instance with a fully qualified path. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. @@ -212,7 +212,7 @@ public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, PathForm /// /// The name of the new file to copy to. /// that specify how the file is to be copied. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. [SecurityCritical] public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates) { @@ -223,7 +223,7 @@ public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool pre } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. - /// A new instance with a fully qualified path. + /// Returns a new instance with a fully qualified path. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. @@ -239,7 +239,7 @@ public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool pre /// /// The name of the new file to copy to. /// that specify how the file is to be copied. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// Indicates the format of the path parameter(s). [SecurityCritical] public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) @@ -253,7 +253,7 @@ public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool pre /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// and the possibility of notifying the application of its progress through a callback function. /// /// Option is recommended for very large file transfers. @@ -282,7 +282,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, Co } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// /// Option is recommended for very large file transfers. /// Use this method to allow or prevent overwriting of an existing file. @@ -313,7 +313,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, Co /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// and the possibility of notifying the application of its progress through a callback function. /// /// Option is recommended for very large file transfers. @@ -330,7 +330,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, Co /// /// The name of the new file to copy to. /// that specify how the file is to be copied. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. [SecurityCritical] @@ -343,7 +343,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bo } /// [AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, can be specified. - /// A class with details of the Copy action. + /// Returns a class with details of the Copy action. /// and the possibility of notifying the application of its progress through a callback function. /// /// Option is recommended for very large file transfers. @@ -360,7 +360,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bo /// /// The name of the new file to copy to. /// that specify how the file is to be copied. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// A callback function that is called each time another portion of the file has been copied. This parameter can be null. /// The argument to be passed to the callback function. This parameter can be null. /// Indicates the format of the path parameter(s). @@ -383,7 +383,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bo #region .NET /// Moves a specified file to a new location, providing the option to specify a new file name. - /// A class with details of the Move action. + /// Returns a class with details of the Move action. /// /// Use this method to prevent overwriting of an existing file by default. /// This method works across disk volumes. @@ -501,7 +501,7 @@ public FileInfo MoveTo(string destinationPath, MoveOptions moveOptions, PathForm /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, can be specified, /// and the possibility of notifying the application of its progress through a callback function. /// - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// Use this method to allow or prevent overwriting of an existing file. /// This method works across disk volumes. @@ -534,7 +534,7 @@ public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, Co } /// [AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, can be specified. - /// A class with the status of the Move action. + /// Returns a class with the status of the Move action. /// /// Use this method to allow or prevent overwriting of an existing file. /// This method works across disk volumes. @@ -575,7 +575,7 @@ public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, Co #region Internal Methods /// Copy/move an existing file to a new file, allowing the overwriting of an existing file. - /// A class with the status of the Copy or Move action. + /// Returns a class with the status of the Copy or Move action. /// /// Option is recommended for very large file transfers. /// Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. @@ -584,7 +584,7 @@ public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, Co /// A full path string to the destination directory /// This parameter can be null. Use to specify how the file is to be copied. /// This parameter can be null. Use that specify how the file is to be moved. - /// true if original Timestamps must be preserved, false otherwise. + /// true if original Timestamps must be preserved; otherwise, false. /// This parameter can be null. A callback function that is called each time another portion of the file has been copied. /// This parameter can be null. The argument to be passed to the callback function. /// [out] Returns the retrieved long full path. diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Create.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Create.cs index d97eb04db..282782871 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Create.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Create.cs @@ -29,7 +29,7 @@ partial class FileInfo #region .NET /// Creates a file. - /// A new file. + /// Returns A new file. [SecurityCritical] public FileStream Create() { diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.CreateText.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.CreateText.cs index 1c4252233..51c6b82d1 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.CreateText.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.CreateText.cs @@ -30,7 +30,7 @@ partial class FileInfo #region .NET /// Creates a instance that writes a new text file. - /// A new + /// Returns a new [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public StreamWriter CreateText() diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Decompress.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Decompress.cs index 8872fe8eb..b387d43e7 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Decompress.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Decompress.cs @@ -31,7 +31,7 @@ partial class FileInfo [SecurityCritical] public void Decompress() { - Device.ToggleCompressionCore(Transaction, LongFullName, false, PathFormat.LongFullPath); + Device.FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, false, PathFormat.LongFullPath); } #endregion // AlphaFS diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.EnumerateAlternateDataStreams.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.EnumerateAlternateDataStreams.cs index a7abe3244..973257313 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.EnumerateAlternateDataStreams.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.EnumerateAlternateDataStreams.cs @@ -26,8 +26,8 @@ namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { - /// [AlphaFS] Returns an enumerable collection of instances for the file. - /// An enumerable collection of instances for the file. + /// [AlphaFS] Returns an collection of instances for the file. + /// Returns an collection of instances for the file. [SecurityCritical] public IEnumerable EnumerateAlternateDataStreams() { diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.GetAccessControl.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.GetAccessControl.cs index 56511e44d..5e1e79310 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.GetAccessControl.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.GetAccessControl.cs @@ -28,16 +28,17 @@ partial class FileInfo { #region .NET - /// Gets a object that encapsulates the access control list (ACL) entries for the file described by the current object. - /// A FileSecurity object that encapsulates the access control rules for the current file. + /// Gets a object that encapsulates the access control list (ACL) entries for the file described by the current object. + /// Returns A FileSecurity object that encapsulates the access control rules for the current file. [SecurityCritical] public FileSecurity GetAccessControl() { return File.GetAccessControlCore(false, LongFullName, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, PathFormat.LongFullPath); } - /// Gets a object that encapsulates the specified type of access control list (ACL) entries for the file described by the current FileInfo object. - /// object that encapsulates the specified type of access control list (ACL) entries for the file described by the current FileInfo object. + + /// Gets a object that encapsulates the specified type of access control list (ACL) entries for the file described by the current FileInfo object. + /// Returns object that encapsulates the specified type of access control list (ACL) entries for the file described by the current FileInfo object. /// One of the values that specifies which group of access control entries to retrieve. [SecurityCritical] public FileSecurity GetAccessControl(AccessControlSections includeSections) diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.GetFileId.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.GetFileId.cs index e1fc21d66..f6295c149 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.GetFileId.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.GetFileId.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Filesystem partial class FileInfo { /// [AlphaFS] Gets the unique identifier for the file. The identifier is composed of a 64-bit volume serial number and 128-bit file system entry identifier. - /// A instance containing the requested information. + /// Returns a instance containing the requested information. /// File IDs are not guaranteed to be unique over time, because file systems are free to reuse them. In some cases, the file ID for a file can change over time. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Open.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Open.cs index 61bde02f2..2c509bff3 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Open.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Open.cs @@ -30,7 +30,7 @@ partial class FileInfo #region .NET /// Opens a file in the specified mode. - /// A file opened in the specified mode, with read/write access and unshared. + /// Returns a file opened in the specified mode, with read/write access and unshared. /// A constant specifying the mode (for example, Open or Append) in which to open the file. [SecurityCritical] public FileStream Open(FileMode mode) @@ -39,7 +39,7 @@ public FileStream Open(FileMode mode) } /// Opens a file in the specified mode with read, write, or read/write access. - /// A object opened in the specified mode and access, and unshared. + /// Returns a object opened in the specified mode and access, and unshared. /// A constant specifying the mode (for example, Open or Append) in which to open the file. /// A constant specifying whether to open the file with Read, Write, or ReadWrite file access. [SecurityCritical] @@ -49,7 +49,7 @@ public FileStream Open(FileMode mode, FileAccess access) } /// Opens a file in the specified mode with read, write, or read/write access and the specified sharing option. - /// A object opened with the specified mode, access, and sharing options. + /// Returns a object opened with the specified mode, access, and sharing options. /// A constant specifying the mode (for example, Open or Append) in which to open the file. /// A constant specifying whether to open the file with Read, Write, or ReadWrite file access. /// A constant specifying the type of access other objects have to this file. @@ -64,7 +64,7 @@ public FileStream Open(FileMode mode, FileAccess access, FileShare share) #region AlphaFS /// [AlphaFS] Opens a file in the specified mode with read, write, or read/write access. - /// A object opened in the specified mode and access, and unshared. + /// Returns a object opened in the specified mode and access, and unshared. /// A constant specifying the mode (for example, Open or Append) in which to open the file. /// A 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. [SecurityCritical] @@ -74,7 +74,7 @@ public FileStream Open(FileMode mode, FileSystemRights rights) } /// [AlphaFS] Opens a file in the specified mode with read, write, or read/write access and the specified sharing option. - /// A object opened with the specified mode, access, and sharing options. + /// Returns a object opened with the specified mode, access, and sharing options. /// A constant specifying the mode (for example, Open or Append) in which to open the file. /// A 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. /// A constant specifying the type of access other objects have to this file. diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenRead.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenRead.cs index 50067f701..901b825a9 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenRead.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenRead.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Filesystem partial class FileInfo { /// Creates a read-only . - /// A new read-only object. + /// Returns a new read-only object. /// This method returns a read-only object with the mode set to Read. [SecurityCritical] public FileStream OpenRead() diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenText.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenText.cs index 6db3e1d44..3807fce38 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenText.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenText.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Filesystem partial class FileInfo { /// Creates a with NativeMethods.DefaultFileEncoding encoding that reads from an existing text file. - /// A new with NativeMethods.DefaultFileEncoding encoding. + /// Returns a new with NativeMethods.DefaultFileEncoding encoding. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public StreamReader OpenText() @@ -39,7 +39,7 @@ public StreamReader OpenText() /// [AlphaFS] Creates a with that reads from an existing text file. - /// A new with the specified . + /// Returns a new with the specified . /// The applied to the contents of the file. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenWrite.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenWrite.cs index becfbe275..4c3e0175b 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenWrite.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.OpenWrite.cs @@ -29,7 +29,7 @@ partial class FileInfo #region .NET /// Creates a write-only . - /// A write-only unshared object for a new or existing file. + /// Returns a write-only unshared object for a new or existing file. [SecurityCritical] public FileStream OpenWrite() { diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Replace.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Replace.cs index de7d15238..41c38b43f 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Replace.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Replace.cs @@ -28,7 +28,7 @@ partial class FileInfo #region .NET /// Replaces the contents of a specified file with the file described by the current object, deleting the original file, and creating a backup of the replaced file. - /// A object that encapsulates information about the file described by the parameter. + /// Returns a object that encapsulates information about the file described by the parameter. /// /// The Replace method replaces the contents of a specified file with the contents of the file described by the current /// object. It also creates a backup of the file that was replaced. Finally, it returns a new @@ -44,7 +44,7 @@ public FileInfo Replace(string destinationFileName, string destinationBackupFile } /// Replaces the contents of a specified file with the file described by the current object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors. - /// A object that encapsulates information about the file described by the parameter. + /// Returns a object that encapsulates information about the file described by the parameter. /// /// The Replace method replaces the contents of a specified file with the contents of the file described by the current /// object. It also creates a backup of the file that was replaced. Finally, it returns a new @@ -65,7 +65,7 @@ public FileInfo Replace(string destinationFileName, string destinationBackupFile #region AlphaFS /// [AlphaFS] Replaces the contents of a specified file with the file described by the current object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors. - /// A object that encapsulates information about the file described by the parameter. + /// Returns a object that encapsulates information about the file described by the parameter. /// /// The Replace method replaces the contents of a specified file with the contents of the file described by the current /// object. It also creates a backup of the file that was replaced. Finally, it returns a new @@ -91,7 +91,7 @@ public FileInfo Replace(string destinationFileName, string destinationBackupFile } /// [AlphaFS] Replaces the contents of a specified file with the file described by the current object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors. - /// A object that encapsulates information about the file described by the parameter. + /// Returns a object that encapsulates information about the file described by the parameter. /// /// The Replace method replaces the contents of a specified file with the contents of the file described by the current /// object. It also creates a backup of the file that was replaced. Finally, it returns a new diff --git a/AlphaFS/Filesystem/FileSystemEntryInfo.cs b/AlphaFS/Filesystem/FileSystemEntryInfo.cs index 9d40385c0..061ea126b 100644 --- a/AlphaFS/Filesystem/FileSystemEntryInfo.cs +++ b/AlphaFS/Filesystem/FileSystemEntryInfo.cs @@ -100,7 +100,7 @@ public string FileName /// The instance file size. public long FileSize { - get { return NativeMethods.ToLong(Win32FindData.nFileSizeHigh, Win32FindData.nFileSizeLow); } + get { return Utils.ToLong(Win32FindData.nFileSizeHigh, Win32FindData.nFileSizeLow); } } diff --git a/AlphaFS/Filesystem/FileSystemInfo.cs b/AlphaFS/Filesystem/FileSystemInfo.cs index 30e9d74d9..a94f71c35 100644 --- a/AlphaFS/Filesystem/FileSystemInfo.cs +++ b/AlphaFS/Filesystem/FileSystemInfo.cs @@ -433,7 +433,7 @@ public void Refresh() /// 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. /// - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { // "Alphaleonis.Win32.Filesystem.FileSystemInfo" @@ -458,7 +458,7 @@ public override bool Equals(object obj) /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { return null != FullName ? FullName.GetHashCode() : 0; @@ -574,7 +574,7 @@ internal static SafeFindFileHandle FindFirstFileNative(KernelTransaction transac lastError = Marshal.GetLastWin32Error(); - if (!NativeMethods.IsValidHandle(safeHandle, false)) + if (!Utils.IsValidHandle(safeHandle, false)) safeHandle = null; diff --git a/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs b/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs index 9e61b35f3..1a72680b7 100644 --- a/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs +++ b/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs @@ -430,7 +430,7 @@ private void VerifyInstanceType(NativeMethods.WIN32_FIND_DATA win32FindData) /// 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. - /// An instance: FileSystemEntryInfo, DirectoryInfo, FileInfo or string (full path). + /// Returns an instance: FileSystemEntryInfo, DirectoryInfo, FileInfo or string (full path). [SecurityCritical] public IEnumerable Enumerate() { @@ -562,7 +562,7 @@ public T Get() { if (null == handle) { - // InputPath might be a logical drive such as: "C:\", "D:\". + // InputPath might be a logical drive such as: C:\, "D:\". var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); diff --git a/AlphaFS/Filesystem/KernelTransaction.cs b/AlphaFS/Filesystem/KernelTransaction.cs index ece18c617..ca288f41c 100644 --- a/AlphaFS/Filesystem/KernelTransaction.cs +++ b/AlphaFS/Filesystem/KernelTransaction.cs @@ -87,7 +87,7 @@ public KernelTransaction(ObjectSecurity securityDescriptor, int timeout, string _hTrans = NativeMethods.CreateTransaction(securityAttributes, IntPtr.Zero, 0, 0, 0, timeout, description); int lastError = Marshal.GetLastWin32Error(); - NativeMethods.IsValidHandle(_hTrans, lastError); + Utils.IsValidHandle(_hTrans, lastError); } } diff --git a/AlphaFS/Filesystem/Link Stream/AlternateDataStreamInfo.cs b/AlphaFS/Filesystem/Link Stream/AlternateDataStreamInfo.cs index e675616a7..154033238 100644 --- a/AlphaFS/Filesystem/Link Stream/AlternateDataStreamInfo.cs +++ b/AlphaFS/Filesystem/Link Stream/AlternateDataStreamInfo.cs @@ -28,30 +28,43 @@ namespace Alphaleonis.Win32.Filesystem /// public struct AlternateDataStreamInfo { + #region Private Fields + + private readonly string _streamName; + private readonly string _fullPath; + + #endregion // Private Fields + + #region Constructor internal AlternateDataStreamInfo(string fullPath, NativeMethods.WIN32_FIND_STREAM_DATA findData) : this() { - StreamName = ParseStreamName(findData.cStreamName); + _streamName = ParseStreamName(findData.cStreamName); + Size = findData.StreamSize; + _fullPath = fullPath; } #endregion // Constructor + #region Public Properties /// Gets the name of the alternate data stream. /// This value is an empty string for the default stream (:$DATA), and for any other data stream it contains the name of the stream. /// The name of the stream. - public string StreamName { get; private set; } + public string StreamName + { + get { return _streamName; } + } + /// Gets the size of the stream. public long Size { get; private set; } - private readonly string _fullPath; - /// Gets the full path to the stream. /// /// This is a path in long path format that can be passed to to open the stream if @@ -69,16 +82,17 @@ public string FullPath #region Public Methods /// Returns the hash code for this instance. - /// A 32-bit signed integer that is the hash code for this instance. + /// Returns a 32-bit signed integer that is the hash code for this instance. public override int GetHashCode() { return StreamName.GetHashCode(); } + /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// - /// true if and this instance are the same type and represent the same value; otherwise, false. + /// true if and this instance are the same type and represent the same value; otherwise, false. /// public override bool Equals(object obj) { @@ -91,6 +105,7 @@ public override bool Equals(object obj) return false; } + /// Equality operator. /// The first operand. /// The second operand. @@ -100,6 +115,7 @@ public override bool Equals(object obj) return first.Equals(second); } + /// Inequality operator. /// The first operand. /// The second operand. @@ -110,6 +126,7 @@ public override bool Equals(object obj) } #endregion // Public Methods + #region Private Methods diff --git a/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs b/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs index daaeedb5c..e5cc7b903 100644 --- a/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs +++ b/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs @@ -185,7 +185,7 @@ public BackupFileStream(KernelTransaction transaction, string path, FileMode mod [SecurityCritical] public BackupFileStream(SafeFileHandle handle, FileSystemRights access) { - NativeMethods.IsValidHandle(handle); + Utils.IsValidHandle(handle); SafeFileHandle = handle; @@ -239,7 +239,7 @@ public override void SetLength(long value) /// Gets a value indicating whether the current stream supports reading. - /// true if the stream supports reading, false otherwise. + /// true if the stream supports reading; otherwise, false. public override bool CanRead { get { return _canRead; } @@ -253,7 +253,7 @@ public override bool CanSeek } /// Gets a value indicating whether the current stream supports writing. - /// true if the stream supports writing, false otherwise. + /// true if the stream supports writing; otherwise, false. public override bool CanWrite { get { return _canWrite; } @@ -440,7 +440,7 @@ public long Skip(long bytes) { uint lowSought, highSought; - var success = NativeMethods.BackupSeek(SafeFileHandle, NativeMethods.GetLowOrderDword(bytes), NativeMethods.GetHighOrderDword(bytes), out lowSought, out highSought, ref _context); + var success = NativeMethods.BackupSeek(SafeFileHandle, Utils.GetLowOrderDword(bytes), Utils.GetHighOrderDword(bytes), out lowSought, out highSought, ref _context); var lastError = Marshal.GetLastWin32Error(); if (!success && lastError != Win32Errors.ERROR_SEEK) @@ -449,7 +449,7 @@ public long Skip(long bytes) NativeError.ThrowException(lastError); } - return NativeMethods.ToLong(highSought, lowSought); + return Utils.ToLong(highSought, lowSought); } @@ -528,7 +528,7 @@ public void Lock(long position, long length) throw new ArgumentOutOfRangeException("length", length, Resources.Negative_Lock_Length); - var success = NativeMethods.LockFile(SafeFileHandle, NativeMethods.GetLowOrderDword(position), NativeMethods.GetHighOrderDword(position), NativeMethods.GetLowOrderDword(length), NativeMethods.GetHighOrderDword(length)); + var success = NativeMethods.LockFile(SafeFileHandle, Utils.GetLowOrderDword(position), Utils.GetHighOrderDword(position), Utils.GetLowOrderDword(length), Utils.GetHighOrderDword(length)); var lastError = Marshal.GetLastWin32Error(); if (!success) @@ -552,7 +552,7 @@ public void Unlock(long position, long length) throw new ArgumentOutOfRangeException("length", length, Resources.Negative_Lock_Length); - var success = NativeMethods.UnlockFile(SafeFileHandle, NativeMethods.GetLowOrderDword(position), NativeMethods.GetHighOrderDword(position), NativeMethods.GetLowOrderDword(length), NativeMethods.GetHighOrderDword(length)); + var success = NativeMethods.UnlockFile(SafeFileHandle, Utils.GetLowOrderDword(position), Utils.GetHighOrderDword(position), Utils.GetLowOrderDword(length), Utils.GetHighOrderDword(length)); var lastError = Marshal.GetLastWin32Error(); if (!success) diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.DiskManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.DiskManagement.cs index fb7b92aa6..e819ba41f 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.DiskManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.DiskManagement.cs @@ -33,7 +33,7 @@ internal static partial class NativeMethods /// /// Symbolic link behavior: If the path points to a symbolic link, the operation is performed on the target. /// 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:\"). + /// 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. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.ErrorMode.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.ErrorMode.cs new file mode 100644 index 000000000..f068b1afb --- /dev/null +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.ErrorMode.cs @@ -0,0 +1,60 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + internal static partial class NativeMethods + { + /// Controls whether the system will handle the specified types of serious errors or whether the process will handle them. + /// + /// 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. + /// + /// Minimum supported client: Windows XP [desktop apps only]. + /// Minimum supported server: Windows Server 2003 [desktop apps only]. + /// The mode. + /// The return value is the previous state of the error-mode bit attributes. + [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); + + + /// Controls whether the system will handle the specified types of serious errors or whether the calling thread will handle them. + /// + /// 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. + /// + /// Minimum supported client: Windows 7 [desktop apps only]. + /// Minimum supported server: Windows Server 2008 R2 [desktop apps only]. + /// The new mode. + /// [out] The old mode. + /// The return value is the previous state of the error-mode bit attributes. + [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); + } +} diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs index 038279da8..a17ef5315 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs @@ -21,6 +21,7 @@ using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; @@ -336,7 +337,7 @@ internal static partial class NativeMethods internal static extern SafeFindFileHandle FindFirstFileTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FIND_FIRST_EX_FLAGS dwAdditionalFlags, SafeHandle hTransaction); /// - /// Creates an enumeration of all the hard links to the specified file. The FindFirstFileNameW function returns a handle to the + /// Returns an collection of all the hard links to the specified file. The FindFirstFileNameW function returns a handle to the /// enumeration that can be used on subsequent calls to the FindNextFileNameW function. /// /// Minimum supported client: Windows Vista [desktop apps only]. @@ -351,7 +352,7 @@ internal static partial class NativeMethods internal static extern SafeFindFileHandle FindFirstFileNameW([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] uint dwFlags, [MarshalAs(UnmanagedType.U4)] out uint stringLength, StringBuilder linkName); /// - /// Creates an enumeration of all the hard links to the specified file as a transacted operation. The function returns a handle to the + /// Returns an collection of all the hard links to the specified file as a transacted operation. The function returns a handle to the /// enumeration that can be used on subsequent calls to the FindNextFileNameW function. /// /// Minimum supported client: Windows Vista [desktop apps only]. diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.Shell32.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.Shell32.cs index 94f10eae5..4bff97654 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.Shell32.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.Shell32.cs @@ -71,7 +71,7 @@ internal interface IQueryAssociations //uint Init(Shell32.AssociationAttributes flags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssoc, IntPtr hkProgid, IntPtr hwnd); /// Searches for and retrieves a file or protocol association-related string from the registry. - /// A standard COM error value, including the following: S_OK, E_POINTER, S_FALSE + /// Returns a standard COM error value, including the following: S_OK, E_POINTER, S_FALSE /// Minimum supported client: Windows 2000 Professional, Windows XP [desktop apps only] /// Minimum supported server: Windows 2000 Server [desktop apps only] void GetString(Shell32.AssociationAttributes flags, Shell32.AssociationString str, [MarshalAs(UnmanagedType.LPWStr)] string pwszExtra, StringBuilder pwszOut, [MarshalAs(UnmanagedType.I4)] out int pcchOut); diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs deleted file mode 100644 index 475bad617..000000000 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.Utilities.cs +++ /dev/null @@ -1,166 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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); - } - - - /// Check is the current handle is not null, not closed and not invalid. - /// The current handle to check. - /// true will throw an , false will not raise this exception.. - /// true on success, false otherwise. - /// - internal static bool IsValidHandle(SafeHandle handle, bool throwException = true) - { - if (null == handle || handle.IsClosed || handle.IsInvalid) - { - if (null != handle && !handle.IsClosed) - handle.Close(); - - if (throwException) - throw new ArgumentException(Resources.Handle_Is_Invalid, "handle"); - - return false; - } - - return true; - } - - - /// Check is the current handle is not null, not closed and not invalid. - /// The current handle to check. - /// The result of Marshal.GetLastWin32Error() - /// true will throw an , false will not raise this exception.. - /// true on success, false otherwise. - /// - internal static bool IsValidHandle(SafeHandle handle, int lastError, bool throwException = true) - { - if (null == handle || handle.IsClosed || handle.IsInvalid) - { - if (null != handle && !handle.IsClosed) - handle.Close(); - - if (throwException) - throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Handle_Is_Invalid_Win32Error, lastError.ToString(CultureInfo.InvariantCulture)), "handle"); - - return false; - } - - return true; - } - - - /// Check is the current handle is not null, not closed and not invalid. - /// The current handle to check. - /// The result of Marshal.GetLastWin32Error() - /// The path on which the Exception occurred. - /// true will throw an Exception, false will not raise this exception.. - /// true on success, false otherwise. - /// - /// - internal static bool IsValidHandle(SafeHandle handle, int lastError, string path, bool throwException = true) - { - if (null == handle || handle.IsClosed || handle.IsInvalid) - { - if (null != handle && !handle.IsClosed) - handle.Close(); - - if (throwException) - NativeError.ThrowException(lastError, path); - - return false; - } - - return true; - } - - - /// Controls whether the system will handle the specified types of serious errors or whether the process will handle them. - /// - /// 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. - /// - /// Minimum supported client: Windows XP [desktop apps only]. - /// Minimum supported server: Windows Server 2003 [desktop apps only]. - /// The mode. - /// The return value is the previous state of the error-mode bit attributes. - [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); - - - /// Controls whether the system will handle the specified types of serious errors or whether the calling thread will handle them. - /// - /// 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. - /// - /// Minimum supported client: Windows 7 [desktop apps only]. - /// Minimum supported server: Windows Server 2008 R2 [desktop apps only]. - /// The new mode. - /// [out] The old mode. - /// The return value is the previous state of the error-mode bit attributes. - [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); - } -} diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs index 52f78d84f..df6b2ac8a 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs @@ -211,12 +211,12 @@ internal static partial class NativeMethods internal static extern bool GetVolumeInformationByHandle(SafeFileHandle hFile, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, out VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); - /// Retrieves a volume GUID path for the volume that is associated with the specified volume mount point (drive letter, volume GUID path, or mounted folder). + /// Retrieves a volume path for the volume that is associated with the specified volume mount point (drive letter, volume path, or mounted folder). /// /// 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. /// - /// Use GetVolumeNameForVolumeMountPoint to obtain a volume GUID path for use with functions such as SetVolumeMountPoint and FindFirstVolumeMountPoint that require a volume GUID path as an input parameter. + /// Use GetVolumeNameForVolumeMountPoint to obtain a volume path for use with functions such as SetVolumeMountPoint and FindFirstVolumeMountPoint that require a volume path as an input parameter. /// SMB does not support volume management functions. /// Mount points aren't supported by ReFS volumes. /// Minimum supported client: Windows XP [desktop apps only] diff --git a/AlphaFS/Filesystem/Native Other/FILETIME.cs b/AlphaFS/Filesystem/Native Other/FILETIME.cs index e4a53ddb4..dc47c13e2 100644 --- a/AlphaFS/Filesystem/Native Other/FILETIME.cs +++ b/AlphaFS/Filesystem/Native Other/FILETIME.cs @@ -22,6 +22,7 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; + namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods @@ -38,6 +39,7 @@ internal struct FILETIME #endregion // Fields + #region Methods /// Converts a value to long. @@ -50,11 +52,12 @@ public static implicit operator long(FILETIME ft) [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "long")] public long ToLong() { - return NativeMethods.ToLong(dwHighDateTime, dwLowDateTime); + return Utils.ToLong(dwHighDateTime, dwLowDateTime); } #endregion + #region Equality #region Equals @@ -77,7 +80,7 @@ public override bool Equals(object obj) #region GetHashCode /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { unchecked diff --git a/AlphaFS/Filesystem/Native Other/WIN32_FILE_ATTRIBUTE_DATA.cs b/AlphaFS/Filesystem/Native Other/WIN32_FILE_ATTRIBUTE_DATA.cs index d70e5b1b6..d74d84221 100644 --- a/AlphaFS/Filesystem/Native Other/WIN32_FILE_ATTRIBUTE_DATA.cs +++ b/AlphaFS/Filesystem/Native Other/WIN32_FILE_ATTRIBUTE_DATA.cs @@ -79,7 +79,7 @@ public WIN32_FILE_ATTRIBUTE_DATA(WIN32_FIND_DATA findData) /// The file size. public long FileSize { - get { return ToLong(nFileSizeHigh, nFileSizeLow); } + get { return Utils.ToLong(nFileSizeHigh, nFileSizeLow); } } } } diff --git a/AlphaFS/Filesystem/Path Class/Path.AddTrailingDirectorySeparator.cs b/AlphaFS/Filesystem/Path Class/Path.AddTrailingDirectorySeparator.cs index 61935d4e9..bc0b75246 100644 --- a/AlphaFS/Filesystem/Path Class/Path.AddTrailingDirectorySeparator.cs +++ b/AlphaFS/Filesystem/Path Class/Path.AddTrailingDirectorySeparator.cs @@ -28,7 +28,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Path { /// [AlphaFS] Adds a trailing character to the string, when absent. - /// A text string with a trailing character. The function returns null when is null. + /// Returns a text string with a trailing character. The function returns null when is null. /// A text string to which the trailing is to be added, when absent. [SecurityCritical] public static string AddTrailingDirectorySeparator(string path) @@ -38,7 +38,7 @@ public static string AddTrailingDirectorySeparator(string path) /// [AlphaFS] Adds a trailing or character to the string, when absent. - /// A text string with a trailing or character. The function returns null when is null. + /// Returns a text string with a trailing or character. The function returns null when is null. /// A text string to which the trailing or is to be added, when absent. /// If true the character will be added instead. [SecurityCritical] diff --git a/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs b/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs index 995b53e15..c805255f2 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs @@ -73,7 +73,7 @@ public static string GetFinalPathNameByHandle(SafeFileHandle handle, FinalPathFo [SecurityCritical] internal static string GetFinalPathNameByHandleCore(SafeFileHandle handle, FinalPathFormats finalPath) { - NativeMethods.IsValidHandle(handle); + Utils.IsValidHandle(handle); var buffer = new StringBuilder(NativeMethods.MaxPathUnicode); @@ -117,13 +117,13 @@ internal static string GetFinalPathNameByHandleCore(SafeFileHandle handle, Final // PageReadOnly = 0x02, using (var handle2 = NativeMethods.CreateFileMapping(handle, null, 2, 0, 1, null)) { - NativeMethods.IsValidHandle(handle, Marshal.GetLastWin32Error()); + Utils.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 (Utils.IsValidHandle(pMem, Marshal.GetLastWin32Error())) if (NativeMethods.GetMappedFileName(Process.GetCurrentProcess().Handle, pMem, buffer, (uint)buffer.Capacity)) NativeMethods.UnmapViewOfFile(pMem); } @@ -174,8 +174,8 @@ internal static string GetFinalPathNameByHandleCore(SafeFileHandle handle, Final } - /// Tranlates DosDevicePath, Volume GUID. For example: "\Device\HarddiskVolumeX\path\filename.ext" can translate to: "\path\filename.ext" or: "\\?\Volume{GUID}\path\filename.ext". - /// A translated dos path. + /// Tranlates DosDevicePath, volume . For example: "\Device\HarddiskVolumeX\path\filename.ext" can translate to: "\path\filename.ext" or: "\\?\Volume{GUID}\path\filename.ext". + /// Returns a translated dos path. /// A DosDevicePath, for example: \Device\HarddiskVolumeX\path\filename.ext. /// Alternate path/device text, usually string.Empty or null. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] diff --git a/AlphaFS/Filesystem/Path Class/Path.GetFullPath.cs b/AlphaFS/Filesystem/Path Class/Path.GetFullPath.cs index 6269b1109..7a3d3ceed 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetFullPath.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetFullPath.cs @@ -36,7 +36,7 @@ public static partial class Path /// It also calculates the address of the file name portion of the full path and file name. ///   /// 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. - /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0. + /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0 ///   /// MSDN: Multithreaded applications and shared library code should not use the GetFullPathName 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, @@ -65,7 +65,7 @@ public static string GetFullPath(string path) /// It also calculates the address of the file name portion of the full path and file name. ///   /// 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. - /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0. + /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0 ///   /// MSDN: Multithreaded applications and shared library code should not use the GetFullPathName 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, @@ -93,7 +93,7 @@ public static string GetFullPath(string path, GetFullPathOptions options) /// It also calculates the address of the file name portion of the full path and file name. ///   /// 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. - /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0. + /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0 ///   /// MSDN: Multithreaded applications and shared library code should not use the GetFullPathName 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, @@ -120,7 +120,7 @@ public static string GetFullPathTransacted(KernelTransaction transaction, string /// It also calculates the address of the file name portion of the full path and file name. ///   /// 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. - /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0. + /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0 ///   /// MSDN: Multithreaded applications and shared library code should not use the GetFullPathName 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, @@ -151,7 +151,7 @@ public static string GetFullPathTransacted(KernelTransaction transaction, string /// It also calculates the address of the file name portion of the full path and file name. ///   /// 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. - /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0. + /// The .NET Framework does not support direct access to physical disks through paths that are device names, such as \\.\PhysicalDrive0 ///   /// MSDN: Multithreaded applications and shared library code should not use the GetFullPathName 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, @@ -192,10 +192,10 @@ internal static string GetFullPathCore(KernelTransaction transaction, string pat options &= ~GetFullPathOptions.CheckAdditional; } - // Do not remove trailing directory separator when path points to a drive like: "C:\" + // 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:\" + // ".", "C:", C:\ if (null == path || path.Length <= 3 || !path.StartsWith(LongPathPrefix, StringComparison.Ordinal) && path[1] != VolumeSeparatorChar) options &= ~GetFullPathOptions.RemoveTrailingDirectorySeparator; } diff --git a/AlphaFS/Filesystem/Path Class/Path.GetInvalidFileNameChars.cs b/AlphaFS/Filesystem/Path Class/Path.GetInvalidFileNameChars.cs index db5f6add5..730a7e9b1 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetInvalidFileNameChars.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetInvalidFileNameChars.cs @@ -28,7 +28,7 @@ public static partial class Path #region .NET /// Gets an array containing the characters that are not allowed in file names. - /// An array containing the characters that are not allowed in file names. + /// Returns an array containing the characters that are not allowed in file names. [SecurityCritical] public static char[] GetInvalidFileNameChars() { diff --git a/AlphaFS/Filesystem/Path Class/Path.GetInvalidPathChars.cs b/AlphaFS/Filesystem/Path Class/Path.GetInvalidPathChars.cs index b1fa3e002..24dc592bf 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetInvalidPathChars.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetInvalidPathChars.cs @@ -28,7 +28,7 @@ public static partial class Path #region .NET /// Gets an array containing the characters that are not allowed in path names. - /// An array containing the characters that are not allowed in path names. + /// Returns an array containing the characters that are not allowed in path names. [SecurityCritical] public static char[] GetInvalidPathChars() { diff --git a/AlphaFS/Filesystem/Path Class/Path.GetLongPath.cs b/AlphaFS/Filesystem/Path Class/Path.GetLongPath.cs index ffc126185..3ebac15a0 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetLongPath.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetLongPath.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Path { /// [AlphaFS] Makes an extended long path from the specified by prefixing . - /// The prefixed with a , the minimum required full path is: "C:\". + /// The prefixed with a , the minimum required full path is: C:\. /// 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. /// /// @@ -42,7 +42,7 @@ public static string GetLongPath(string path) /// Makes an extended long path from the specified by prefixing . - /// The prefixed with a , the minimum required full path is: "C:\". + /// The prefixed with a , the minimum required full path is: C:\. /// 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. /// /// diff --git a/AlphaFS/Filesystem/Path Class/Path.GetPathRoot.cs b/AlphaFS/Filesystem/Path Class/Path.GetPathRoot.cs index 1bd0e2075..091f11931 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetPathRoot.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetPathRoot.cs @@ -30,7 +30,7 @@ public static partial class Path /// Gets the root directory information of the specified path. /// - /// Returns the root directory of , such as "C:\", + /// Returns the root directory of , such as C:\, /// or null if is null, /// or an empty string if does not contain root directory information. /// @@ -47,7 +47,7 @@ public static string GetPathRoot(string path) /// [AlphaFS] Gets the root directory information of the specified path. /// - /// Returns the root directory of , such as "C:\", + /// Returns the root directory of , such as C:\, /// or null if is null, /// or an empty string if does not contain root directory information. /// diff --git a/AlphaFS/Filesystem/Path Class/Path.GetRandomFileName.cs b/AlphaFS/Filesystem/Path Class/Path.GetRandomFileName.cs index b8b7f6706..ab7ee78bd 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetRandomFileName.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetRandomFileName.cs @@ -29,7 +29,7 @@ public static partial class Path #region .NET /// Returns a random folder name or file name. - /// A random folder name or file name. + /// Returns a random folder name or file name. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public static string GetRandomFileName() diff --git a/AlphaFS/Filesystem/Path Class/Path.GetShort83Path.cs b/AlphaFS/Filesystem/Path Class/Path.GetShort83Path.cs index eb2f7831b..054238fed 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetShort83Path.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetShort83Path.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Path { /// [AlphaFS] Retrieves the short path form of the specified path. - /// A path that has the 8.3 path form. + /// Returns a path that has the 8.3 path form. /// Will fail on NTFS volumes with disabled 8.3 name generation. /// The path must actually exist to be able to get the short path name. /// @@ -43,7 +43,7 @@ public static string GetShort83Path(string path) /// [AlphaFS] Retrieves the short path form of the specified path. - /// A path that has the 8.3 path form. + /// Returns a path that has the 8.3 path form. /// Will fail on NTFS volumes with disabled 8.3 name generation. /// The path must actually exist to be able to get the short path name. /// diff --git a/AlphaFS/Filesystem/Path Class/Path.Helpers.cs b/AlphaFS/Filesystem/Path Class/Path.Helpers.cs index 277f3cb83..753e9e4e1 100644 --- a/AlphaFS/Filesystem/Path Class/Path.Helpers.cs +++ b/AlphaFS/Filesystem/Path Class/Path.Helpers.cs @@ -459,7 +459,7 @@ private static string NormalizePath(string path, GetFullPathOptions options) // 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:\" + // Also handle "C:\foo\." -> "C:\foo", while "C:\." -> C:\ if (numSigChars == 0) { if (numDots > 0) diff --git a/AlphaFS/Filesystem/Path Class/Path.IsLongPath.cs b/AlphaFS/Filesystem/Path Class/Path.IsLongPath.cs index 8ffb80c60..bb2f702c1 100644 --- a/AlphaFS/Filesystem/Path Class/Path.IsLongPath.cs +++ b/AlphaFS/Filesystem/Path Class/Path.IsLongPath.cs @@ -28,7 +28,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Path { /// [AlphaFS] Determines whether the specified path starts with a or . - /// true if the specified path has a long path (UNC) prefix, false otherwise. + /// true if the specified path has a long path (UNC) prefix; otherwise, false. /// The path to the file or directory. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] diff --git a/AlphaFS/Filesystem/Path Class/Path.IsUncPath.cs b/AlphaFS/Filesystem/Path Class/Path.IsUncPath.cs index 4bf7f3844..8559a742a 100644 --- a/AlphaFS/Filesystem/Path Class/Path.IsUncPath.cs +++ b/AlphaFS/Filesystem/Path Class/Path.IsUncPath.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Path { /// [AlphaFS] Determines if a path string is a valid Universal Naming Convention (UNC) path. - /// true if the specified path is a Universal Naming Convention (UNC) path, false otherwise. + /// true if the specified path is a Universal Naming Convention (UNC) path; otherwise, false. /// The path to check. [SecurityCritical] public static bool IsUncPath(string path) @@ -38,7 +38,7 @@ public static bool IsUncPath(string path) /// Determines if a path string is a valid Universal Naming Convention (UNC) path, optionally skip invalid path character check. - /// true if the specified path is a Universal Naming Convention (UNC) path, false otherwise. + /// true if the specified path is a Universal Naming Convention (UNC) path; otherwise, false. /// The path to check. /// When true indicates that is already in regular path format. /// true will check for invalid path characters. diff --git a/AlphaFS/Filesystem/Path Class/Path.LocalToUnc.cs b/AlphaFS/Filesystem/Path Class/Path.LocalToUnc.cs index 969cf5651..802d0e6d8 100644 --- a/AlphaFS/Filesystem/Path Class/Path.LocalToUnc.cs +++ b/AlphaFS/Filesystem/Path Class/Path.LocalToUnc.cs @@ -31,7 +31,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Path { /// [AlphaFS] Converts a local path to a network share path. - /// A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". + /// A Local path, e.g.: C:\Windows or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". /// If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing character. /// /// On successful conversion a UNC path is returned. @@ -41,7 +41,7 @@ public static partial class Path /// /// /// - /// A local path, e.g.: "C:\Windows". + /// A local path, e.g.: C:\Windows. [SecurityCritical] public static string LocalToUnc(string localPath) { @@ -50,7 +50,7 @@ public static string LocalToUnc(string localPath) /// [AlphaFS] Converts a local path to a network share path. - /// A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". + /// A Local path, e.g.: C:\Windows or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". /// If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing character. /// /// On successful conversion a UNC path is returned. @@ -60,7 +60,7 @@ public static string LocalToUnc(string localPath) /// /// /// - /// A local path, e.g.: "C:\Windows". + /// A local path, e.g.: C:\Windows. /// Indicates the format of the path parameter. [SecurityCritical] public static string LocalToUnc(string localPath, PathFormat pathFormat) @@ -70,7 +70,7 @@ public static string LocalToUnc(string localPath, PathFormat pathFormat) /// [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. - /// A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". + /// A Local path, e.g.: C:\Windows or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". /// If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing character. /// /// On successful conversion a UNC path is returned. @@ -80,7 +80,7 @@ public static string LocalToUnc(string localPath, PathFormat pathFormat) /// /// /// - /// A local path, e.g.: "C:\Windows". + /// A local path, e.g.: C:\Windows. /// Indicates the format of the path parameter. /// Options for controlling the full path retrieval. [SecurityCritical] @@ -91,7 +91,7 @@ public static string LocalToUnc(string localPath, PathFormat pathFormat, GetFull /// [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. - /// A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". + /// A Local path, e.g.: C:\Windows or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". /// If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing character. /// /// On successful conversion a UNC path is returned. @@ -101,7 +101,7 @@ public static string LocalToUnc(string localPath, PathFormat pathFormat, GetFull /// /// /// - /// A local path, e.g.: "C:\Windows". + /// A local path, e.g.: C:\Windows. /// Options for controlling the full path retrieval. [SecurityCritical] public static string LocalToUnc(string localPath, GetFullPathOptions fullPathOptions) @@ -113,7 +113,7 @@ public static string LocalToUnc(string localPath, GetFullPathOptions fullPathOpt /// 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. - /// A Local path, e.g.: "C:\Windows" or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". + /// A Local path, e.g.: C:\Windows or "C:\Windows\" will be returned as: "\\localhost\C$\Windows". /// If a logical drive points to a network share path (mapped drive), the share path will be returned without a trailing character. /// /// On successful conversion a UNC path is returned. @@ -123,7 +123,7 @@ public static string LocalToUnc(string localPath, GetFullPathOptions fullPathOpt /// /// /// - /// A local path, e.g.: "C:\Windows". + /// A local path, e.g.: C:\Windows. /// Indicates the format of the path parameter. /// Options for controlling the full path retrieval. [SecurityCritical] diff --git a/AlphaFS/Filesystem/Path Class/Path.RemoveTrailingDirectorySeparator.cs b/AlphaFS/Filesystem/Path Class/Path.RemoveTrailingDirectorySeparator.cs index a06ffdb2c..593ab78cb 100644 --- a/AlphaFS/Filesystem/Path Class/Path.RemoveTrailingDirectorySeparator.cs +++ b/AlphaFS/Filesystem/Path Class/Path.RemoveTrailingDirectorySeparator.cs @@ -26,7 +26,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Path { /// [AlphaFS] Removes the trailing character from the string, when present. - /// A text string where the trailing character has been removed. The function returns null when is null. + /// Returns a text string where the trailing character has been removed. The function returns null when is null. /// A text string from which the trailing is to be removed, when present. [SecurityCritical] public static string RemoveTrailingDirectorySeparator(string path) @@ -36,7 +36,7 @@ public static string RemoveTrailingDirectorySeparator(string path) /// [AlphaFS] Removes the trailing or character from the string, when present. - /// A text string where the trailing or character has been removed. The function returns null when is null. + /// Returns a text string where the trailing or character has been removed. The function returns null when is null. /// A text string from which the trailing or is to be removed, when present. /// If true the trailing character will be removed instead. [SecurityCritical] diff --git a/AlphaFS/Filesystem/Shell32.cs b/AlphaFS/Filesystem/Shell32.cs index c730d527d..80964d2ae 100644 --- a/AlphaFS/Filesystem/Shell32.cs +++ b/AlphaFS/Filesystem/Shell32.cs @@ -530,7 +530,7 @@ public static string GetFileFriendlyDocName(string path) /// Icon size or . Can also be combined /// with and others. /// - /// An handle to the Shell icon that represents the file, or IntPtr.Zero on failure. + /// Returns an handle to the Shell icon that represents the file, or IntPtr.Zero on failure. [SecurityCritical] public static IntPtr GetFileIcon(string filePath, FileAttributes iconAttributes) { @@ -543,7 +543,7 @@ public static IntPtr GetFileIcon(string filePath, FileAttributes iconAttributes) /// Retrieves information about an object in the file system, such as a file, folder, directory, or drive root. - /// A struct instance. + /// Returns a struct instance. /// /// You should call this function from a background thread. /// Failure to do so could cause the UI to stop responding. @@ -565,7 +565,7 @@ public static FileInfo GetFileInfo(string filePath, System.IO.FileAttributes att /// Retrieves an instance of containing information about the specified file. /// A path to the file. - /// A class instance. + /// Returns a class instance. [SecurityCritical] public static Shell32Info GetShell32Info(string path) { @@ -575,7 +575,7 @@ public static Shell32Info GetShell32Info(string path) /// Retrieves an instance of containing information about the specified file. /// A path to the file. /// Indicates the format of the path parameter(s). - /// A class instance. + /// Returns a class instance. [SecurityCritical] public static Shell32Info GetShell32Info(string path, PathFormat pathFormat) { @@ -652,7 +652,7 @@ internal static string PathCreateFromUrlAlloc(string urlPath) /// Determines whether a path to a file system object such as a file or folder is valid. /// The full path of maximum length the maximum path length to the object to verify. - /// true if the file exists; false otherwise + /// true if the file exists; otherwise, false [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "lastError")] [SecurityCritical] public static bool PathFileExists(string path) @@ -668,9 +668,9 @@ public static bool PathFileExists(string path) /// The URL. /// /// - /// For all but one of the URL types, UrlIs returns true if the URL is the specified type, or false otherwise. + /// For all but one of the URL types, UrlIs returns true if the URL is the specified type, or otherwise, false. /// If UrlIs is set to , UrlIs will attempt to determine the URL scheme. - /// If the function is able to determine a scheme, it returns true, or false otherwise. + /// If the function is able to determine a scheme, it returns true, or otherwise, false. /// [SecurityCritical] internal static bool UrlIs(string url, UrlType urlType) @@ -710,7 +710,7 @@ internal static string UrlCreateFromPath(string path) /// Tests a URL to determine if it is a file URL. /// The URL. - /// true if the URL is a file URL, or false otherwise. + /// true if the URL is a file URL, or otherwise, false. [SecurityCritical] internal static bool UrlIsFileUrl(string url) { @@ -720,7 +720,7 @@ internal static bool UrlIsFileUrl(string url) /// Returns whether a URL is a URL that browsers typically do not include in navigation history. /// The URL. - /// true if the URL is a URL that is not included in navigation history, or false otherwise. + /// true if the URL is a URL that is not included in navigation history, or otherwise, false. [SecurityCritical] internal static bool UrlIsNoHistory(string url) { @@ -730,7 +730,7 @@ internal static bool UrlIsNoHistory(string url) /// Returns whether a URL is opaque. /// The URL. - /// true if the URL is opaque, or false otherwise. + /// true if the URL is opaque, or otherwise, false. [SecurityCritical] internal static bool UrlIsOpaque(string url) { @@ -790,7 +790,7 @@ private static string GetFileAssociationCore(string path, AssociationAttributes /// Retrieve information about an object in the file system, such as a file, folder, directory, or drive root. - /// A struct instance. + /// Returns a struct instance. /// /// You should call this function from a background thread. /// Failure to do so could cause the UI to stop responding. diff --git a/AlphaFS/Filesystem/Shell32Info.cs b/AlphaFS/Filesystem/Shell32Info.cs index b5e58fca7..1423941de 100644 --- a/AlphaFS/Filesystem/Shell32Info.cs +++ b/AlphaFS/Filesystem/Shell32Info.cs @@ -67,7 +67,7 @@ public Shell32Info(string fileName, PathFormat pathFormat) /// Gets an handle to the Shell icon that represents the file. /// Icon size or . Can also be combined with and others. - /// An handle to the Shell icon that represents the file. + /// Returns an handle to the Shell icon that represents the file. /// Caller is responsible for destroying this handle with DestroyIcon() when no longer needed. [SecurityCritical] public IntPtr GetIcon(Shell32.FileAttributes iconAttributes) diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs b/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs index 1c5bd4e0d..717256bd4 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs @@ -32,7 +32,7 @@ namespace Alphaleonis.Win32.Filesystem /// The error code. /// The error message. /// The faulty path being processed. - /// false otherwise, in which case the caller will throw the corresponding exception. + /// otherwise, false, in which case the caller will throw the corresponding exception. public delegate bool ErrorHandler(int errorCode, string errorMessage, string pathProcessed); diff --git a/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs b/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs index 9e31b1b12..2092b7f35 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs @@ -38,7 +38,7 @@ internal FileIdInfo(NativeMethods.BY_HANDLE_FILE_INFORMATION fibh) _volumeSerialNumber = fibh.dwVolumeSerialNumber; _fileIdHighPart = 0; - _fileIdLowPart = NativeMethods.ToLong(fibh.nFileIndexHigh, fibh.nFileIndexLow); + _fileIdLowPart = Utils.ToLong(fibh.nFileIndexHigh, fibh.nFileIndexLow); } @@ -71,7 +71,7 @@ private static void ArrayToLong(byte[] fileId, int startIndex, int count, out lo /// 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. /// An object to compare with this instance. - /// 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 in the sort order. Zero This instance occurs in the same position in the sort order as . Greater than zero This instance follows in the sort order. + /// 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 in the sort order. Zero This instance occurs in the same position in the sort order as . Greater than zero This instance follows in the sort order. public int CompareTo(object obj) { if (null == obj) @@ -86,7 +86,7 @@ public int CompareTo(object obj) /// Compares the current object with another object of the same type. /// An object to compare with this object. - /// 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 parameter.Zero This object is equal to . Greater than zero This object is greater than . + /// 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 parameter.Zero This object is equal to . Greater than zero This object is greater than . public int CompareTo(FileIdInfo other) { return _volumeSerialNumber != other._volumeSerialNumber @@ -111,7 +111,7 @@ public override bool Equals(object obj) /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. - /// true if the current object is equal to the parameter; otherwise, false. + /// true if the current object is equal to the parameter; otherwise, false. public bool Equals(FileIdInfo other) { return _fileIdLowPart == other._fileIdLowPart && _fileIdHighPart == other._fileIdHighPart && _volumeSerialNumber == other._volumeSerialNumber; @@ -121,7 +121,7 @@ public bool Equals(FileIdInfo other) /// Indicates whether the values of two specified objects are equal. /// The first object to compare. /// The second object to compare. - /// true if and are equal; otherwise, false. + /// true if and are equal; otherwise, false. public static bool operator ==(FileIdInfo first, FileIdInfo second) { return first._fileIdLowPart == second._fileIdLowPart && first._fileIdHighPart == second._fileIdHighPart && first._volumeSerialNumber == second._volumeSerialNumber; @@ -131,7 +131,7 @@ public bool Equals(FileIdInfo other) /// Indicates whether the values of two specified objects are not equal. /// The first object to compare. /// The second object to compare. - /// true if and are not equal; otherwise, false. + /// true if and are not equal; otherwise, false. public static bool operator !=(FileIdInfo first, FileIdInfo second) { return first._fileIdLowPart != second._fileIdLowPart || first._fileIdHighPart != second._fileIdHighPart || first._volumeSerialNumber != second._volumeSerialNumber; @@ -163,7 +163,7 @@ public bool Equals(FileIdInfo other) /// Returns a hash code for this instance. - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// Returns a hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. public override int GetHashCode() { unchecked @@ -176,7 +176,7 @@ public override int GetHashCode() /// Returns a that represents this instance. - /// A that represents this instance. + /// Returns a that represents this instance. public override string ToString() { unchecked diff --git a/AlphaFS/Filesystem/Structures, Enumerations/FinalPathFormats.cs b/AlphaFS/Filesystem/Structures, Enumerations/FinalPathFormats.cs index f9c2ffb6c..f8b96d958 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/FinalPathFormats.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/FinalPathFormats.cs @@ -30,7 +30,7 @@ public enum FinalPathFormats /// (FileNameNormalized / VolumeNameDos) Return the normalized drive name. This is the default. None = 0, - /// Return the path with a volume GUID path instead of the drive name. + /// Return the path with a volume path instead of the drive name. VolumeNameGuid = 1, /// Return the path with the volume device path. diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs index 3fccc43b0..e0560b0ca 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; @@ -29,22 +30,26 @@ namespace Alphaleonis.Win32.Filesystem /// public enum PartitionType { - #region Non-OS - - /// There is no partition. + /// There is no partition or the partition is an unused entry. /// This value can be set for basic and dynamic disks. - /// [Description("00000000-0000-0000-0000-000000000000")] - UnusedEntry, + None = 0, + + + #region Non-OS + + ///// There is no partition. + ///// This value can be set for basic and dynamic disks. + //[Description("00000000-0000-0000-0000-000000000000")] + //UnusedEntry, /// Legacy MBR partition. A partition that is sub-partitioned by a Master Boot Record; "partitions-inside-a-slice configuration". [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mbr")] [Description("024DEE41-33E7-11D3-9D69-0008C781F39F")] LegacyMbr, - /// The partition is an EFI system partition. + /// The partition is an EFI system partition. /// This value can be set for basic and dynamic disks. - /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Efi")] [Description("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")] EfiSystem, @@ -71,40 +76,35 @@ public enum PartitionType #region Windows - /// The partition is a Microsoft reserved partition. + /// The partition is a Microsoft reserved partition. /// This value can be set for basic and dynamic disks. - /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Msft")] [SuppressMessage("Microsoft.Naming", "CA1700:DoNotNameEnumValuesReserved")] [Description("E3C9E316-0B5C-4DB8-817D-F92DF00215AE")] MsftReserved, - - /// The data partition type that is created and recognized by Windows. + + /// The data partition type that is created and recognized by Windows. /// - /// This value can be set only for basic disks, with one exception. - /// Only partitions of this type can be assigned drive letters, receive volume GUID paths, host mounted folders (also called volume mount points), and be enumerated by calls to FindFirstVolume and FindNextVolume. + /// This value can be set only for basic disks, with one exception. + /// Only partitions of this type can be assigned drive letters, receive volume paths, host mounted folders (also called volume mount points), and be enumerated by calls to FindFirstVolume and FindNextVolume. /// - /// [Description("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7")] BasicData, - /// The partition is a Logical Disk Manager (LDM) metadata partition on a dynamic disk. + /// The partition is a Logical Disk Manager (LDM) metadata partition on a dynamic disk. /// This value can be set only for dynamic disks. - /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ldm")] [Description("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3")] LdmMetadata, - /// The partition is an LDM data partition on a dynamic disk. + /// The partition is an LDM data partition on a dynamic disk. /// This value can be set only for dynamic disks. - /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ldm")] [Description("AF9B60A0-1431-4F62-BC68-3311714A69AD")] LdmData, - - /// The partition is a Microsoft recovery partition. + + /// The partition is a Microsoft recovery partition. /// This value can be set for basic and dynamic disks. - /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Msft")] [Description("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC")] MsftRecovery, @@ -443,27 +443,24 @@ public enum PartitionType #region Chrome OS /// Chrome OS Kernel partition. - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Chromse")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("FE3A2A5D-4F32-41A7-B725-ACCC3285A309")] - ChromseOsKernel, + ChromeOsKernel, /// Chrome OS RootFS partition. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fs")] - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Chromse")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Fs")] [Description("3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC")] - ChromseOsRootFs, + ChromeOsRootFs, /// Chrome OS (future use) partition. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Chromse")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [Description("2E0A753D-9E48-43B0-8337-B15192CB1B5E")] - ChromseOsFutureUse, + ChromeOsFutureUse, #endregion // Chrome OS diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PathFormat.cs b/AlphaFS/Filesystem/Structures, Enumerations/PathFormat.cs index 7c6c837e2..afe11a7ae 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PathFormat.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/PathFormat.cs @@ -23,12 +23,12 @@ namespace Alphaleonis.Win32.Filesystem { /// Indicates the format of a path passed to a method. /// - /// At some point in code you know the full path of file system objects, e.g.: "C:\Windows". + /// At some point in code you know the full path of file system objects, e.g.: C:\Windows. /// For example, Directory.EnumerateFileSystemEntries() will return all files and directories from a given path. /// Most likely, some processing will happen on the results of the enum. The file or directory may be passed /// on to another function. Whenever a file path is required, some performance can be gained. ///   - /// A path like: "C:\Windows" or "\\server\share" is considered a full path for a directory because it is rooted and has a drive/unc path. + /// A path like: C:\Windows or "\\server\share" is considered a full path for a directory because it is rooted and has a drive/unc path. /// If the method supports it, and will skip GetFullPath() /// calls for path resolving of the object, while also avoiding path validation and checks. /// Using (default) will always call GetFullPath() and perform path validation and checks. @@ -46,7 +46,7 @@ public enum PathFormat /// The path is a full path in either normal or extended length (UNICODE) format. /// Internally it will be converted to an extended length (UNICODE) path. /// Using this option has a very slight performance advantage compared to using . - /// Example full path: "C:\Windows" or "\\server\share". + /// Example full path: C:\Windows or "\\server\share". /// FullPath, diff --git a/AlphaFS/GlobalSuppressions.cs b/AlphaFS/GlobalSuppressions.cs index 0e996ba08..080cfa0d3 100644 --- a/AlphaFS/GlobalSuppressions.cs +++ b/AlphaFS/GlobalSuppressions.cs @@ -44,3 +44,5 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Filesystem.NativeMethods+PARTITION_INFORMATION_GPT")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Filesystem.NativeMethods+PARTITION_INFORMATION_EX")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Alphaleonis", Scope = "namespace", Target = "Alphaleonis.Win32.Device")] + diff --git a/AlphaFS/Network/DfsInfo.cs b/AlphaFS/Network/DfsInfo.cs index 517e37999..572235a24 100644 --- a/AlphaFS/Network/DfsInfo.cs +++ b/AlphaFS/Network/DfsInfo.cs @@ -69,7 +69,7 @@ internal DfsInfo(NativeMethods.DFS_INFO_9 structure) #region Methods /// Returns the Universal Naming Convention (UNC) path of the DFS root or link. - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return EntryPath; diff --git a/AlphaFS/Network/DfsStorageInfo.cs b/AlphaFS/Network/DfsStorageInfo.cs index a9a16e83b..67cdd4028 100644 --- a/AlphaFS/Network/DfsStorageInfo.cs +++ b/AlphaFS/Network/DfsStorageInfo.cs @@ -54,7 +54,7 @@ internal DfsStorageInfo(NativeMethods.DFS_STORAGE_INFO_1 structure) #region Methods /// The share name of the DFS root target or link target. - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return ShareName; diff --git a/AlphaFS/Network/Host Class/Host.DFS.EnumerateDfsLinks.cs b/AlphaFS/Network/Host Class/Host.DFS.EnumerateDfsLinks.cs index 696904872..19c8c1314 100644 --- a/AlphaFS/Network/Host Class/Host.DFS.EnumerateDfsLinks.cs +++ b/AlphaFS/Network/Host Class/Host.DFS.EnumerateDfsLinks.cs @@ -31,7 +31,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// Enumerates the DFS Links from a DFS namespace. - /// of DFS namespaces. + /// Returns of DFS namespaces. /// /// /// The operating system is older than Windows Vista. diff --git a/AlphaFS/Network/Host Class/Host.DFS.EnumerateDfsRoot.cs b/AlphaFS/Network/Host Class/Host.DFS.EnumerateDfsRoot.cs index 652f0475b..c99dff3a2 100644 --- a/AlphaFS/Network/Host Class/Host.DFS.EnumerateDfsRoot.cs +++ b/AlphaFS/Network/Host Class/Host.DFS.EnumerateDfsRoot.cs @@ -33,7 +33,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// Enumerates the DFS namespaces from the local host. - /// of DFS Root namespaces from the local host. + /// Returns an collection of DFS Root namespaces from the local host. /// /// The operating system is older than Windows Vista. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] @@ -45,7 +45,7 @@ public static IEnumerable EnumerateDfsRoot() /// Enumerates the DFS namespaces from a host. - /// of DFS Root namespaces from a host. + /// Returns an collection of DFS Root namespaces from a host. /// /// The operating system is older than Windows Vista. /// The DNS or NetBIOS name of a host. @@ -61,7 +61,7 @@ public static IEnumerable EnumerateDfsRoot(string host, bool continueOnE /// Enumerates the DFS namespaces from a host. - /// of DFS Root namespaces from a host. + /// Returns an collection of DFS Root namespaces from a host. /// /// /// The operating system is older than Windows Vista. diff --git a/AlphaFS/Network/Host Class/Host.DFS.EnumerateDomainDfsRoot.cs b/AlphaFS/Network/Host Class/Host.DFS.EnumerateDomainDfsRoot.cs index 7fd53a43d..f0bb487ae 100644 --- a/AlphaFS/Network/Host Class/Host.DFS.EnumerateDomainDfsRoot.cs +++ b/AlphaFS/Network/Host Class/Host.DFS.EnumerateDomainDfsRoot.cs @@ -34,7 +34,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// Enumerates the DFS namespaces from the domain. - /// of DFS Root namespaces from the domain. + /// Returns an collection of DFS Root namespaces from the domain. /// /// The operating system is older than Windows Vista. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] @@ -46,7 +46,7 @@ public static IEnumerable EnumerateDomainDfsRoot() /// Enumerates the DFS namespaces from a domain. - /// of DFS Root namespaces from a domain. + /// Returns an collection of DFS Root namespaces from a domain. /// /// The operating system is older than Windows Vista. /// A domain name. @@ -62,7 +62,7 @@ public static IEnumerable EnumerateDomainDfsRoot(string domain, bool con /// Enumerates the DFS namespaces from a domain. - /// of DFS Root namespaces from a domain. + /// Returns an collection of DFS Root namespaces from a domain. /// /// /// The operating system is older than Windows Vista. diff --git a/AlphaFS/Network/Host Class/Host.DFS.GetDfsClientInfo.cs b/AlphaFS/Network/Host Class/Host.DFS.GetDfsClientInfo.cs index f9993fbaa..9c23f64a2 100644 --- a/AlphaFS/Network/Host Class/Host.DFS.GetDfsClientInfo.cs +++ b/AlphaFS/Network/Host Class/Host.DFS.GetDfsClientInfo.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// Gets information about a DFS root or link from the cache maintained by the DFS client. - /// A instance. + /// Returns a instance. /// /// The operating system is older than Windows Vista. /// The Universal Naming Convention (UNC) path of a DFS root or link. @@ -43,7 +43,7 @@ public static DfsInfo GetDfsClientInfo(string dfsName) /// Gets information about a DFS root or link from the cache maintained by the DFS client. - /// A instance. + /// Returns a instance. /// /// The operating system is older than Windows Vista. /// The Universal Naming Convention (UNC) path of a DFS root or link. diff --git a/AlphaFS/Network/Host Class/Host.DFS.GetDfsInfo.cs b/AlphaFS/Network/Host Class/Host.DFS.GetDfsInfo.cs index e6c438c91..de17e60f3 100644 --- a/AlphaFS/Network/Host Class/Host.DFS.GetDfsInfo.cs +++ b/AlphaFS/Network/Host Class/Host.DFS.GetDfsInfo.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// Gets information about a specified DFS root or link in a DFS namespace. - /// A instance. + /// Returns a instance. /// /// The operating system is older than Windows Vista. /// The Universal Naming Convention (UNC) path of a DFS root or link. @@ -46,7 +46,7 @@ public static DfsInfo GetDfsInfo(string dfsName) /// Retrieves information about a specified DFS root or link in a DFS namespace. - /// A instance. + /// Returns a instance. /// /// /// The operating system is older than Windows Vista. diff --git a/AlphaFS/Network/Host Class/Host.EnumerateNetworkConnections.cs b/AlphaFS/Network/Host Class/Host.EnumerateNetworkConnections.cs index 805c1f8d4..3f1fc9d5a 100644 --- a/AlphaFS/Network/Host Class/Host.EnumerateNetworkConnections.cs +++ b/AlphaFS/Network/Host Class/Host.EnumerateNetworkConnections.cs @@ -27,8 +27,8 @@ namespace Alphaleonis.Win32.Network { public static partial class Host { - /// [AlphaFS] Returns an enumerable collection of defined network connections on the local host. - /// An collection of defined network connections on the local host. + /// [AlphaFS] Returns an collection of defined network connections on the local host. + /// Returns an collection of defined network connections on the local host. [SecurityCritical] public static IEnumerable EnumerateNetworkConnections() { @@ -38,9 +38,9 @@ public static IEnumerable EnumerateNetworkConnections() - /// [AlphaFS] Returns an enumerable collection of defined network connections on the local host. + /// [AlphaFS] Returns an collection of defined network connections on the local host. /// A that specifies the network connection ID. - /// An collection of network connection ID's on the local host. + /// Returns an collection of network connection ID's on the local host. [SecurityCritical] internal static IEnumerable EnumerateNetworkConnectionsCore(Guid? networkConnectionID) { diff --git a/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs b/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs index 4813a931c..ae8e2e37a 100644 --- a/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs +++ b/AlphaFS/Network/Host Class/Host.EnumerateNetworks.cs @@ -27,8 +27,8 @@ namespace Alphaleonis.Win32.Network { public static partial class Host { - /// [AlphaFS] Returns an enumerable collection of networks available on the local host. - /// An collection of connected and disconnected networks on the local host. + /// [AlphaFS] Returns an collection of networks available on the local host. + /// Returns an collection of connected and disconnected networks on the local host. [SecurityCritical] public static IEnumerable EnumerateNetworks() { @@ -36,8 +36,8 @@ public static IEnumerable EnumerateNetworks() } - /// [AlphaFS] Returns an enumerable collection of networks available on the local host. - /// An collection of networks on the local host, as specified by . + /// [AlphaFS] Returns an collection of networks available on the local host. + /// Returns an collection of networks on the local host, as specified by . /// The that specify the connectivity level of the returned instances. [SecurityCritical] public static IEnumerable EnumerateNetworks(NetworkConnectivityLevels networkConnectivityLevels) @@ -48,8 +48,8 @@ public static IEnumerable EnumerateNetworks(NetworkConnectivityLeve - /// [AlphaFS] Returns an enumerable collection of networks available on the local host. - /// An collection of networks on the local host, as specified by . + /// [AlphaFS] Returns an collection of networks available on the local host. + /// Returns an collection of networks on the local host, as specified by . /// The that defines a network. /// The that specify the connectivity level of the returned instances. [SecurityCritical] diff --git a/AlphaFS/Network/Host Class/Host.GetNetwork.cs b/AlphaFS/Network/Host Class/Host.GetNetwork.cs index a35641794..84f271fd9 100644 --- a/AlphaFS/Network/Host Class/Host.GetNetwork.cs +++ b/AlphaFS/Network/Host Class/Host.GetNetwork.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// [AlphaFS] Rretrieves a network based on a supplied network ID from the local host. - /// A instance from the local host, as specified by . + /// Returns a instance from the local host, as specified by . /// The that defines a network. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] [SecurityCritical] diff --git a/AlphaFS/Network/Host Class/Host.GetNetworkConnection.cs b/AlphaFS/Network/Host Class/Host.GetNetworkConnection.cs index c3fbcaf2d..5dea02ede 100644 --- a/AlphaFS/Network/Host Class/Host.GetNetworkConnection.cs +++ b/AlphaFS/Network/Host Class/Host.GetNetworkConnection.cs @@ -30,7 +30,7 @@ public static partial class Host { /// [AlphaFS] Retrieves a network based on a specified network connection ID. /// A that specifies the network connection ID. - /// A instance that represents the network connection ID. + /// Returns a instance that represents the network connection ID. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] [SecurityCritical] public static NetworkConnectionInfo GetNetworkConnection(Guid networkConnectionID) diff --git a/AlphaFS/Network/Host Class/Host.SMB.EnumerateDrives.cs b/AlphaFS/Network/Host Class/Host.SMB.EnumerateDrives.cs index e7b24a2ac..944fdfec5 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.EnumerateDrives.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.EnumerateDrives.cs @@ -32,7 +32,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// Enumerates drives from the local host. - /// drives from the local host. + /// Returns an collection of drives from the local host. /// [SecurityCritical] public static IEnumerable EnumerateDrives() @@ -42,7 +42,7 @@ public static IEnumerable EnumerateDrives() /// Enumerates local drives from the specified host. - /// drives from the specified host. + /// Returns an collection of drives from the specified host. /// /// The DNS or NetBIOS name of the remote server. null refers to the local host. [SecurityCritical] @@ -57,7 +57,7 @@ public static IEnumerable EnumerateDrives(string host) /// Enumerates local drives from the specified host. - /// drives from the specified host. + /// Returns an collection of drives from the specified host. /// /// The DNS or NetBIOS name of the remote server. null refers to the local host. /// @@ -78,7 +78,7 @@ public static IEnumerable EnumerateDrives(string host, bool continueO /// Enumerates local drives from the specified host. - /// drives from the specified host. + /// Returns an collection of drives from the specified host. /// /// /// The DNS or NetBIOS name of the remote server. null refers to the local host. diff --git a/AlphaFS/Network/Host Class/Host.SMB.EnumerateOpenConnections.cs b/AlphaFS/Network/Host Class/Host.SMB.EnumerateOpenConnections.cs index a5c896f90..5dcfab92a 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.EnumerateOpenConnections.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.EnumerateOpenConnections.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// Enumerates open connections from the local host. - /// connection information from the local host. + /// Returns an collection of connection information from the local host. /// /// [SecurityCritical] @@ -41,7 +41,7 @@ public static IEnumerable EnumerateOpenConnections() /// Enumerates open connections from the specified host. - /// connection information from the specified . + /// Returns an collection of connection information from the specified . /// /// /// The DNS or NetBIOS name of the remote server. null refers to the local host. @@ -54,7 +54,7 @@ public static IEnumerable EnumerateOpenConnections(string ho /// Enumerates open connections from the specified host. - /// connection information from the specified . + /// Returns an collection of connection information from the specified . /// /// /// The DNS or NetBIOS name of the remote server. null refers to the local host. @@ -73,7 +73,7 @@ public static IEnumerable EnumerateOpenConnections(string ho /// Enumerates open connections from the specified host and . - /// connection information from the specified . + /// Returns an collection of connection information from the specified . /// /// /// The DNS or NetBIOS name of the remote server. null refers to the local host. diff --git a/AlphaFS/Network/Host Class/Host.SMB.EnumerateOpenResources.cs b/AlphaFS/Network/Host Class/Host.SMB.EnumerateOpenResources.cs index cbc4e6186..e8e0d973e 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.EnumerateOpenResources.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.EnumerateOpenResources.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// Enumerates open resources from the local host. - /// open resources from the local host. + /// Returns open resources from the local host. /// /// [SecurityCritical] @@ -41,7 +41,7 @@ public static IEnumerable EnumerateOpenResources() /// Enumerates open resources from the specified host. - /// open resources from the specified . + /// Returns an collection of open resources from the specified . /// /// /// The DNS or NetBIOS name of the remote server. null refers to the local host. @@ -65,7 +65,7 @@ public static IEnumerable EnumerateOpenResources(string host, /// >Enumerates open resources from the specified host. - /// open resources from the specified . + /// Returns an collection of open resources from the specified . /// /// /// The DNS or NetBIOS name of the remote server. null refers to the local host. diff --git a/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs b/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs index 714bf5020..4c22ae8bd 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.EnumerateSessions.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// [AlphaFS] Enumerates sessions established on the local host. - /// An collection from the local host. + /// Returns an collection from the local host. [SecurityCritical] public static IEnumerable EnumerateSessions() { @@ -39,7 +39,7 @@ public static IEnumerable EnumerateSessions() /// [AlphaFS] Enumerates sessions established on the specified . - /// An collection from the specified . + /// Returns an collection from the specified . /// The DNS or NetBIOS name of the specified host. If this parameter is null, the local Computer is used. [SecurityCritical] public static IEnumerable EnumerateSessions(string hostName) @@ -49,7 +49,7 @@ public static IEnumerable EnumerateSessions(string hostName) /// [AlphaFS] Enumerates sessions established on the specified . - /// An collection from the specified . + /// Returns an collection from the specified . /// The DNS or NetBIOS name of the specified host. If this parameter is null, the local Computer is used. /// The name of the Computer session for which information is to be returned. If this parameter is null, information for all Computer sessions on the server is returned. [SecurityCritical] @@ -60,7 +60,7 @@ public static IEnumerable EnumerateSessions(string hostName, string /// [AlphaFS] Enumerates sessions established on the specified . - /// An collection from the specified . + /// Returns an collection from the specified . /// The DNS or NetBIOS name of the specified host. If this parameter is null, the local Computer is used. /// The name of the Computer session for which information is to be returned. If this parameter is null, information for all Computer sessions on the server is returned. /// The name of the user for which information is to be returned. If this parameter is null, information for all users is returned. @@ -74,7 +74,7 @@ public static IEnumerable EnumerateSessions(string hostName, string /// [AlphaFS] Enumerates sessions established on the specified . - /// An collection from the specified . + /// Returns an collection from the specified . /// /// The DNS or NetBIOS name of the specified host. If this parameter is null, the local Computer is used. /// The name of the Computer session for which information is to be returned. If this parameter is null, information for all Computer sessions on the server is returned. diff --git a/AlphaFS/Network/Host Class/Host.SMB.EnumerateShares.cs b/AlphaFS/Network/Host Class/Host.SMB.EnumerateShares.cs index be2bd8b96..507b53540 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.EnumerateShares.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.EnumerateShares.cs @@ -30,19 +30,17 @@ namespace Alphaleonis.Win32.Network { public static partial class Host { - /// Enumerates Server Message Block (SMB) shares from the local host. - /// shares from the specified host. - /// This method also enumerates hidden shares. + /// Enumerates (hidden) Server Message Block (SMB) shares from the local host. + /// Returns an collection of shares from the specified host. [SecurityCritical] public static IEnumerable EnumerateShares() { return EnumerateSharesCore(null, ShareType.All, false); } - - /// Enumerates Server Message Block (SMB) shares from the local host. - /// shares from the specified host. - /// This method also enumerates hidden shares. + + /// Enumerates (hidden) Server Message Block (SMB) shares from the local host. + /// Returns an collection of shares from the specified host. /// true suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. [SecurityCritical] public static IEnumerable EnumerateShares(bool continueOnException) @@ -50,10 +48,9 @@ public static IEnumerable EnumerateShares(bool continueOnException) return EnumerateSharesCore(null, ShareType.All, continueOnException); } - - /// Enumerates Server Message Block (SMB) shares from the local host. - /// shares from the specified host. - /// This method also enumerates hidden shares. + + /// Enumerates (hidden) Server Message Block (SMB) shares from the local host. + /// Returns an collection of shares from the specified host. /// The type of the shared resource to retrieve. /// true suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. [SecurityCritical] @@ -62,10 +59,9 @@ public static IEnumerable EnumerateShares(ShareType shareType, bool c return EnumerateSharesCore(null, shareType, continueOnException); } - - /// Enumerates Server Message Block (SMB) shares from the specified . - /// shares from the specified host. - /// This method also enumerates hidden shares. + + /// Enumerates (hidden) Server Message Block (SMB) shares from the specified . + /// Returns an collection of shares from the specified host. /// The DNS or NetBIOS name of the specified host. [SecurityCritical] public static IEnumerable EnumerateShares(string host) @@ -73,10 +69,9 @@ public static IEnumerable EnumerateShares(string host) return EnumerateSharesCore(host, ShareType.All, false); } - - /// Enumerates Server Message Block (SMB) shares from the specified . - /// shares from the specified host. - /// This method also enumerates hidden shares. + + /// Enumerates (hidden) Server Message Block (SMB) shares from the specified . + /// Returns an collection of shares from the specified host. /// The DNS or NetBIOS name of the specified host. /// true suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. [SecurityCritical] @@ -85,10 +80,9 @@ public static IEnumerable EnumerateShares(string host, bool continueO return EnumerateSharesCore(host, ShareType.All, continueOnException); } - - /// Enumerates Server Message Block (SMB) shares from the specified . - /// shares from the specified host. - /// This method also enumerates hidden shares. + + /// Enumerates (hidden) Server Message Block (SMB) shares from the specified . + /// Returns an collection of shares from the specified host. /// The DNS or NetBIOS name of the specified host. /// The type of the shared resource to retrieve. /// true suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. @@ -101,9 +95,8 @@ public static IEnumerable EnumerateShares(string host, ShareType shar - /// Enumerates Server Message Block (SMB) shares from a local or remote host. - /// shares from the specified host. - /// This method also enumerates hidden shares. + /// Enumerates (hidden) Server Message Block (SMB) shares from a local or remote host. + /// Returns an collection of shares from the specified host. /// /// /// The DNS or NetBIOS name of the specified host. diff --git a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs index e140666d0..4b1ace1ec 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.GetNetStatistics.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// [AlphaFS] Retrieves operating statistics for the Server service from the local host. - /// A instance. + /// Returns a instance. /// [SecurityCritical] public static ServerStatisticsInfo GetServerStatistics() @@ -39,7 +39,7 @@ public static ServerStatisticsInfo GetServerStatistics() /// [AlphaFS] Retrieves operating statistics for the Server service from the specified host. - /// A instance. + /// Returns a instance. /// /// The DNS or NetBIOS name of the local or remote host to retrieve statistics from. [SecurityCritical] @@ -52,7 +52,7 @@ public static ServerStatisticsInfo GetServerStatistics(string hostName) /// [AlphaFS] Retrieves operating statistics for the Workstation service from the local host. - /// A instance. + /// Returns a instance. /// [SecurityCritical] public static WorkstationStatisticsInfo GetWorkstationStatistics() @@ -62,7 +62,7 @@ public static WorkstationStatisticsInfo GetWorkstationStatistics() /// [AlphaFS] Retrieves operating statistics for the Workstation service from the specified host. - /// A instance. + /// Returns a instance. /// /// The DNS or NetBIOS name of the local or remote host to retrieve statistics from. [SecurityCritical] @@ -75,7 +75,7 @@ public static WorkstationStatisticsInfo GetWorkstationStatistics(string hostName /// [AlphaFS] Retrieves or operating statistics for the Server- or Workstation service from the specified host. - /// A or instance, depending on the value. + /// Returns a or instance, depending on the value. /// /// true returns information, false . /// The DNS or NetBIOS name of the local or remote host to retrieve statistics from. diff --git a/AlphaFS/Network/Host Class/Host.SMB.GetShareInfo.cs b/AlphaFS/Network/Host Class/Host.SMB.GetShareInfo.cs index 684d5c2d7..6e99dfac7 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.GetShareInfo.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.GetShareInfo.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Network public static partial class Host { /// Retrieves information about the Server Message Block (SMB) share as defined on the specified host. - /// A class, or null on failure or when not available, and is true. + /// Returns a class, or null on failure or when not available, and is true. /// The share in the format: \\host\share. /// true to suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. [SecurityCritical] @@ -42,7 +42,7 @@ public static ShareInfo GetShareInfo(string uncPath, bool continueOnException) /// Retrieves information about the Server Message Block (SMB) share as defined on the specified host. - /// A class, or null on failure or when not available, and is true. + /// Returns a class, or null on failure or when not available, and is true. /// One of the options. /// The share in the format: \\host\share. /// true to suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. @@ -55,7 +55,7 @@ public static ShareInfo GetShareInfo(ShareInfoLevel shareLevel, string uncPath, /// Retrieves information about the Server Message Block (SMB) share as defined on the specified host. - /// A class, or null on failure or when not available, and is true. + /// Returns a class, or null on failure or when not available, and is true. /// The DNS or NetBIOS name of the specified host. /// The name of the Server Message Block (SMB) share. /// true to suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. @@ -67,7 +67,7 @@ public static ShareInfo GetShareInfo(string host, string share, bool continueOnE /// Retrieves information about the Server Message Block (SMB) share as defined on the specified host. - /// A class, or null on failure or when not available, and is true. + /// Returns a class, or null on failure or when not available, and is true. /// One of the options. /// A string that specifies the DNS or NetBIOS name of the specified . /// A string that specifies the name of the Server Message Block (SMB) share. @@ -82,7 +82,7 @@ public static ShareInfo GetShareInfo(ShareInfoLevel shareLevel, string host, str /// Gets the structure of a Server Message Block (SMB) share. - /// A class, or null on failure or when not available, and is true. + /// Returns a class, or null on failure or when not available, and is true. /// /// One of the options. /// A string that specifies the DNS or NetBIOS name of the specified . diff --git a/AlphaFS/Network/Host Class/Host.WNet.DriveConnection.cs b/AlphaFS/Network/Host Class/Host.WNet.DriveConnection.cs index 37c020c9b..6d9c959bf 100644 --- a/AlphaFS/Network/Host Class/Host.WNet.DriveConnection.cs +++ b/AlphaFS/Network/Host Class/Host.WNet.DriveConnection.cs @@ -138,7 +138,7 @@ private void Dispose(bool isDisposing) /// Returns the last available drive letter used for this connection. - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return LocalName; diff --git a/AlphaFS/Network/Host Class/Host.cs b/AlphaFS/Network/Host Class/Host.cs index 565b01961..40b13cbca 100644 --- a/AlphaFS/Network/Host Class/Host.cs +++ b/AlphaFS/Network/Host Class/Host.cs @@ -280,7 +280,7 @@ internal static IEnumerable EnumerateNetworkObjectCoreThis method uses level to retrieve full REMOTE_NAME_INFO structure. - /// A structure. + /// Returns a structure. /// AlphaFS regards network drives created using SUBST.EXE as invalid. /// /// diff --git a/AlphaFS/Network/NetworkConnectionInfo.cs b/AlphaFS/Network/NetworkConnectionInfo.cs index f185732c3..8bef1e4d8 100644 --- a/AlphaFS/Network/NetworkConnectionInfo.cs +++ b/AlphaFS/Network/NetworkConnectionInfo.cs @@ -85,7 +85,7 @@ public bool IsConnectedToInternet /// Retrieves an instance that represents the network associated with this connection. This value of this property is not cached. - /// A instance. + /// Returns a instance. public NetworkInfo NetworkInfo { get { return new NetworkInfo(_networkConnection.GetNetwork()); } @@ -126,7 +126,7 @@ public NetworkInterface NetworkInterface #region Methods /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return null != NetworkInfo && null != NetworkInterface ? string.Format(CultureInfo.CurrentCulture, "{0} {1}", NetworkInfo.Name, NetworkInterface.Name) : GetType().Name; @@ -152,7 +152,7 @@ public override bool Equals(object obj) /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { unchecked diff --git a/AlphaFS/Network/NetworkInfo.cs b/AlphaFS/Network/NetworkInfo.cs index 0848000d5..27353fd18 100644 --- a/AlphaFS/Network/NetworkInfo.cs +++ b/AlphaFS/Network/NetworkInfo.cs @@ -187,7 +187,7 @@ public Guid NetworkId #region Methods /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { var description = !Utils.IsNullOrWhiteSpace(Description) && !Equals(Name, Description) ? " (" + Description + ")" : string.Empty; @@ -213,7 +213,7 @@ public override bool Equals(object obj) /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { unchecked diff --git a/AlphaFS/Network/OpenConnectionInfo.cs b/AlphaFS/Network/OpenConnectionInfo.cs index ba3de8d44..cd077737f 100644 --- a/AlphaFS/Network/OpenConnectionInfo.cs +++ b/AlphaFS/Network/OpenConnectionInfo.cs @@ -59,7 +59,7 @@ internal OpenConnectionInfo(string hostName, NativeMethods.CONNECTION_INFO_1 con #region Methods /// Returns the full path to the share. - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return Id.ToString(CultureInfo.InvariantCulture); diff --git a/AlphaFS/Network/OpenResourceInfo.cs b/AlphaFS/Network/OpenResourceInfo.cs index b1ef739a5..2f0f41c2e 100644 --- a/AlphaFS/Network/OpenResourceInfo.cs +++ b/AlphaFS/Network/OpenResourceInfo.cs @@ -60,7 +60,7 @@ public void Close() } /// Returns the full path to the share. - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return Id.ToString(CultureInfo.InvariantCulture); diff --git a/AlphaFS/Network/ServerStatisticsInfo.cs b/AlphaFS/Network/ServerStatisticsInfo.cs index 0ad879596..b14bb0cf1 100644 --- a/AlphaFS/Network/ServerStatisticsInfo.cs +++ b/AlphaFS/Network/ServerStatisticsInfo.cs @@ -94,7 +94,7 @@ public int BufferRequestFailed /// The number of server bytes received from the network. public long BytesReceived { - get { return Filesystem.NativeMethods.ToLong(_serverStat.sts0_bytesrcvd_high, _serverStat.sts0_bytesrcvd_low); } + get { return Utils.ToLong(_serverStat.sts0_bytesrcvd_high, _serverStat.sts0_bytesrcvd_low); } } @@ -108,7 +108,7 @@ public string BytesReceivedUnitSize /// The number of server bytes sent to the network. public long BytesSent { - get { return Filesystem.NativeMethods.ToLong(_serverStat.sts0_bytessent_high, _serverStat.sts0_bytessent_low); } + get { return Utils.ToLong(_serverStat.sts0_bytessent_high, _serverStat.sts0_bytessent_low); } } @@ -207,7 +207,7 @@ public void Refresh() /// Returns the local time when statistics collection started or when the statistics were last cleared. - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return HostName; @@ -229,7 +229,7 @@ public override bool Equals(object obj) /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { return null != HostName ? HostName.GetHashCode() : 0; diff --git a/AlphaFS/Network/SessionInfo.cs b/AlphaFS/Network/SessionInfo.cs index 309262cf3..b15795ee1 100644 --- a/AlphaFS/Network/SessionInfo.cs +++ b/AlphaFS/Network/SessionInfo.cs @@ -120,7 +120,7 @@ internal SessionInfo(string hostName, SessionInfoLevel sessionLevel, object stru #region Methods /// Returns the host name of this session information. - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return HostName; diff --git a/AlphaFS/Network/ShareInfo.cs b/AlphaFS/Network/ShareInfo.cs index 5b5650a3a..72291a392 100644 --- a/AlphaFS/Network/ShareInfo.cs +++ b/AlphaFS/Network/ShareInfo.cs @@ -119,7 +119,7 @@ internal ShareInfo(string host, ShareInfoLevel shareLevel, object shareInfo) #region Methods /// Returns the full path to the share. - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return NetFullPath; diff --git a/AlphaFS/Network/WorkstationStatisticsInfo.cs b/AlphaFS/Network/WorkstationStatisticsInfo.cs index fb6cd751b..56b85b450 100644 --- a/AlphaFS/Network/WorkstationStatisticsInfo.cs +++ b/AlphaFS/Network/WorkstationStatisticsInfo.cs @@ -446,7 +446,7 @@ public void Refresh() /// Returns the local time when statistics collection started or when the statistics were last cleared. - /// A string that represents this instance. + /// Returns a string that represents this instance. public override string ToString() { return HostName; @@ -468,7 +468,7 @@ public override bool Equals(object obj) /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { return null != HostName ? HostName.GetHashCode() : 0; diff --git a/AlphaFS/Resources.resx b/AlphaFS/Resources.resx index 64642b98b..3d6758dcc 100644 --- a/AlphaFS/Resources.resx +++ b/AlphaFS/Resources.resx @@ -251,13 +251,13 @@ The directory is not a mount point: [{0}] - Argument must be a drive letter: "C", RootDir: "C:\" or UNC path: "\\server\share" + Argument must be a drive letter: "C", RootDir: C:\ or UNC path: "\\server\share" - Argument must be a drive letter: "C", "C:" or RootDir: "C:\" + Argument must be a drive letter: "C", "C:" or RootDir: C:\ - Argument must be a drive letter: "C", "C:\" or Volume GUID. + Argument must be a drive letter: "C", C:\ or Volume GUID. Cannot add and remove trailing DirectorySeparator simultaneously. diff --git a/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs b/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs index d382c0ce8..b42d04141 100644 --- a/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs +++ b/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs @@ -278,7 +278,7 @@ public void StructureToPtr(object structure, bool deleteOld) /// Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type. - /// A managed object containing the data pointed to by the ptr parameter. + /// Returns a managed object containing the data pointed to by the ptr parameter. public T PtrToStructure(int offset = 0) { return (T) Marshal.PtrToStructure(new IntPtr(handle.ToInt64() + offset), typeof(T)); @@ -286,14 +286,14 @@ public T PtrToStructure(int offset = 0) /// Allocates a managed System.String and copies a specified number of characters from an unmanaged ANSI string into it. - /// A managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null. + /// Returns a managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null. public string PtrToStringAnsi(int offset = 0) { return Marshal.PtrToStringAnsi(new IntPtr(handle.ToInt64() + offset)); } /// Allocates a managed System.String and copies all characters up to the first null character from an unmanaged Unicode string into it. - /// A managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null. + /// Returns a managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null. public string PtrToStringUni() { return Marshal.PtrToStringUni(handle); @@ -301,7 +301,7 @@ public string PtrToStringUni() /// Allocates a managed System.String and copies a specified number of characters from an unmanaged Unicode string into it. - /// A managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null. + /// Returns a managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null. public string PtrToStringUni(int offset, int length) { return Marshal.PtrToStringUni(new IntPtr(handle.ToInt64() + offset), length); diff --git a/AlphaFS/Security/CRC/Crc32.cs b/AlphaFS/Security/CRC/Crc32.cs index 72a8de4c2..16d93cf66 100644 --- a/AlphaFS/Security/CRC/Crc32.cs +++ b/AlphaFS/Security/CRC/Crc32.cs @@ -151,7 +151,7 @@ private static uint CalculateHash(uint[] table, uint seed, IList buffer, i /// Int 32 to big endian bytes. /// The second uint 3. - /// A byte[]. + /// Returns a byte[]. private static byte[] UInt32ToBigEndianBytes(uint uint32) { var result = BitConverter.GetBytes(uint32); diff --git a/AlphaFS/Security/CRC/Crc64.cs b/AlphaFS/Security/CRC/Crc64.cs index 252eaa70a..8d5f48c13 100644 --- a/AlphaFS/Security/CRC/Crc64.cs +++ b/AlphaFS/Security/CRC/Crc64.cs @@ -117,7 +117,7 @@ private static ulong CalculateHash(ulong seed, ulong[] table, IList buffer /// Int 64 to big endian bytes. /// The value. - /// A byte[]. + /// Returns a byte[]. private static byte[] UInt64ToBigEndianBytes(ulong value) { var result = BitConverter.GetBytes(value); @@ -130,7 +130,7 @@ private static byte[] UInt64ToBigEndianBytes(ulong value) /// Initializes the table. /// The polynomial. - /// An ulong[]. + /// Returns an ulong[]. private static ulong[] InitializeTable(ulong polynomial) { if (polynomial == Iso3309Polynomial && Table != null) @@ -146,7 +146,7 @@ private static ulong[] InitializeTable(ulong polynomial) /// Creates a table. /// The polynomial. - /// A new array of ulong. + /// Returns a new array of ulong. private static ulong[] CreateTable(ulong polynomial) { var createTable = new ulong[256]; diff --git a/AlphaFS/Security/InternalPrivilegeEnabler.cs b/AlphaFS/Security/InternalPrivilegeEnabler.cs index 7f309ef6c..c417b725e 100644 --- a/AlphaFS/Security/InternalPrivilegeEnabler.cs +++ b/AlphaFS/Security/InternalPrivilegeEnabler.cs @@ -83,7 +83,7 @@ private void AdjustPrivilege(bool enable) var newPrivilege = new TOKEN_PRIVILEGES { PrivilegeCount = 1, - Luid = Filesystem.NativeMethods.LongToLuid(EnabledPrivilege.LookupLuid()), + Luid = Utils.LongToLuid(EnabledPrivilege.LookupLuid()), // 2 = SePrivilegeEnabled; Attributes = (uint) (enable ? 2 : 0) diff --git a/AlphaFS/Security/Privilege.cs b/AlphaFS/Security/Privilege.cs index 197ebd512..da36dd946 100644 --- a/AlphaFS/Security/Privilege.cs +++ b/AlphaFS/Security/Privilege.cs @@ -308,7 +308,7 @@ public long LookupLuid() NativeError.ThrowException(lastError, _name); - return Filesystem.NativeMethods.LuidToLong(luid); + return Utils.LuidToLong(luid); } @@ -341,7 +341,7 @@ public override bool Equals(object obj) /// Serves as a hash function for a particular type. - /// A hash code for the current Object. + /// Returns a hash code for the current Object. public override int GetHashCode() { return null != _name ? _name.GetHashCode() : 0; @@ -350,7 +350,7 @@ public override int GetHashCode() /// Returns the system name for this privilege. /// This is equivalent to . - /// A that represents the current . + /// Returns a that represents the current . public override string ToString() { return _name; diff --git a/AlphaFS/Security/ProcessContext.cs b/AlphaFS/Security/ProcessContext.cs index 1c2999bb3..717340aac 100644 --- a/AlphaFS/Security/ProcessContext.cs +++ b/AlphaFS/Security/ProcessContext.cs @@ -115,7 +115,7 @@ private static WindowsPrincipal GetWindowsPrincipal(out WindowsIdentity windowsI /// [AlphaFS] Retrieves the elevation type of the current process. - /// A value. + /// Returns a value. [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "OpenProcessToken")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "GetTokenInformation")] private static NativeMethods.TOKEN_ELEVATION_TYPE GetProcessElevationType() diff --git a/AlphaFS/Security/SecurityAttributes.cs b/AlphaFS/Security/SecurityAttributes.cs index cce222e77..7ced32492 100644 --- a/AlphaFS/Security/SecurityAttributes.cs +++ b/AlphaFS/Security/SecurityAttributes.cs @@ -63,7 +63,7 @@ public SecurityAttributes(ObjectSecurity securityDescriptor, bool inheritHandle) /// Marshals an ObjectSecurity instance to unmanaged memory. - /// A safe handle containing the marshalled security descriptor. + /// Returns a safe handle containing the marshalled security descriptor. /// The security descriptor. [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private static SafeGlobalMemoryBufferHandle ToUnmanagedSecurityAttributes(ObjectSecurity securityDescriptor) diff --git a/AlphaFS/Utils.cs b/AlphaFS/Utils.cs index 5e88b37fc..89887612f 100644 --- a/AlphaFS/Utils.cs +++ b/AlphaFS/Utils.cs @@ -25,11 +25,46 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; +using System.Runtime.InteropServices; +using System.Security; +using Alphaleonis.Win32; +using Alphaleonis.Win32.Security; +using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; namespace Alphaleonis { internal static class Utils { + [SecurityCritical] + internal static int GetDoubledBufferSizeOrThrowException(SafeHandle safeBuffer, int lastError, int bufferSize, string pathForException) + { + if (null != safeBuffer && !safeBuffer.IsClosed) + safeBuffer.Close(); + + + switch ((uint)lastError) + { + case Win32Errors.ERROR_MORE_DATA: + case Win32Errors.ERROR_INSUFFICIENT_BUFFER: + case Win32Errors.ERROR_INVALID_PARAMETER: + + if (bufferSize == 0) + bufferSize = NativeMethods.DefaultFileBufferSize / 32; // 128 + + bufferSize *= 2; + break; + + + default: + IsValidHandle(safeBuffer, lastError, String.Format(CultureInfo.InvariantCulture, "Buffer size: {0}. Path: {1}", bufferSize.ToString(CultureInfo.InvariantCulture), pathForException)); + break; + } + + + return bufferSize; + } + + /// Gets an attribute on an enum field value. /// The description belonging to the enum option, as a string /// One of the enum types. @@ -92,6 +127,76 @@ public static bool IsNullOrWhiteSpace(string value) } + /// Check is the current handle is not null, not closed and not invalid. + /// The current handle to check. + /// true will throw an , false will not raise this exception.. + /// true on success; otherwise, false. + /// + internal static bool IsValidHandle(SafeHandle handle, bool throwException = true) + { + if (null == handle || handle.IsClosed || handle.IsInvalid) + { + if (null != handle && !handle.IsClosed) + handle.Close(); + + if (throwException) + throw new ArgumentException(Resources.Handle_Is_Invalid, "handle"); + + return false; + } + + return true; + } + + + /// Check is the current handle is not null, not closed and not invalid. + /// The current handle to check. + /// The result of Marshal.GetLastWin32Error() + /// true will throw an , false will not raise this exception.. + /// true on success; otherwise, false. + /// + internal static bool IsValidHandle(SafeHandle handle, int lastError, bool throwException = true) + { + if (null == handle || handle.IsClosed || handle.IsInvalid) + { + if (null != handle && !handle.IsClosed) + handle.Close(); + + if (throwException) + throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, Resources.Handle_Is_Invalid_Win32Error, lastError.ToString(CultureInfo.InvariantCulture)), "handle"); + + return false; + } + + return true; + } + + + /// Check is the current handle is not null, not closed and not invalid. + /// The current handle to check. + /// The result of Marshal.GetLastWin32Error() + /// The path on which the Exception occurred. + /// true will throw an Exception, false will not raise this exception.. + /// true on success; otherwise, false. + /// + /// + internal static bool IsValidHandle(SafeHandle handle, int lastError, string path, bool throwException = true) + { + if (null == handle || handle.IsClosed || handle.IsInvalid) + { + if (null != handle && !handle.IsClosed) + handle.Close(); + + if (throwException) + NativeError.ThrowException(lastError, path); + + return false; + } + + return true; + } + + /// Converts a number of type T to string formated using , suffixed with a unit size. public static string UnitSizeToText(T numberOfBytes) { @@ -158,5 +263,42 @@ public static int CombineHashCodesOf(T1 arg1, T2 arg2, T3 arg3, { return CombineHashCodesOf(CombineHashCodesOf(arg1, arg2), CombineHashCodesOf(arg3, arg4)); } + + + #region Bitmasking + + 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); + } + + #endregion // Bitmasking } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 13f532f7a..0f0c3846e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ Version 2.3 (2018-XX-XX) ### Breaking Changes - Issue #426: Correct casing of enum `STREAM_ATTRIBUTES` +- Issue #455: As a result, moved class `DeviceInfo` from `Alphaleonis.Win32.Filesystem` to `Alphaleonis.Win32.Device` namespace. Version 2.2.2 (2018-06-05) @@ -33,7 +34,7 @@ Version 2.2.2 (2018-06-05) - Issue #149: Split unit-tests. - Fixed all Sandcastle Help File Builder warnings. -- Because of bug fixes, the correct source-/destination folder is now shown in exceptions thrown from Directory/File.Copy/Move methods, instead of always showing the source folder path. +- Because of bug fixes, the correct source-/destination folder is now shown in exceptions thrown from `Directory`/`File.Copy`/`Move` methods, instead of always showing the source folder path. - Improved some unit tests that would fail when a removable drive is already removed but there's still a cached reference. @@ -42,7 +43,7 @@ Version 2.2.1 (2018-04-05) ### Bugs Fixed -- Issue #433: Directory.ExistsDriveOrFolderOrFile fails on global root path, so a simple file copy from a shadow copy fails with "device GLOBALROOT not ready" (Thx CyberSinh) +- Issue #433: `Directory.ExistsDriveOrFolderOrFile` fails on global root path, so a simple file copy from a shadow copy fails with "`device GLOBALROOT not ready`" (Thx CyberSinh) Version 2.2 (2018-03-25) @@ -221,7 +222,7 @@ Version 2.1 (2016-09-29) ### Bugs Fixed -- Issue #50 : `Path.GetLongPath()` does not prefix on "C:\", should it? +- Issue #50 : `Path.GetLongPath()` does not prefix on C:\, should it? - Issue #60 : Remove all use of "Problematic" methods such as `DangerousAddRef` and `DangerousGetHandle()`. - Issue #160: `File.CreateSymbolicLink()` creates shortcut with no target. (martin-john-green) - Issue #162: `File.AppendAllLines()` concatenates content into one line. (pavelhritonenko) From 10cd497c4505637054c5251abc69f4a1af26fd57 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 7 Jun 2018 21:38:22 +0200 Subject: [PATCH 087/133] -Moved all native members of Device class to Device namespace; -Changed namespace of SafeXxxHandle to namespace Alphaleonis.Win32; --- ...e.GetStorageDeviceInfo_FromLogicalDrive.cs | 4 +- ...efineDosDevice_SymbolicLinkDriveMapping.cs | 2 +- .../AlphaFS_Device.EnumerateDevices.cs | 2 +- AlphaFS/AlphaFS.csproj | 114 +++++++++--------- AlphaFS/Device/Device.DeviceInfo.cs | 3 +- .../DriveInfo.EnumerateLogicalDrives.cs | 2 +- ...ilesystemHelper.CreateDirectoryJunction.cs | 6 +- ...ilesystemHelper.DeleteDirectoryJunction.cs | 2 +- .../FilesystemHelper.GetLinkTarget.cs | 12 +- AlphaFS/Device/Local.EnumerateDevices.cs | 7 +- .../NativeMethods.DeviceManagement.cs | 10 +- .../NativeMethods.DiskManagement.cs | 2 +- .../NativeMethods.DiskPartitionType.cs} | 2 +- .../NativeMethods.EfiPartitionAttributes.cs} | 2 +- .../NativeMethods.VolumeManagement.cs | 6 +- .../Native Other}/DEVICE_INFORMATION_FLAGS.cs | 2 +- .../Native Other/DEVPROPKEY.cs | 2 +- .../Native Other/DISK_DETECTION_INFO.cs | 2 +- .../Native Other/DISK_EXTENT.cs | 2 +- .../Native Other/DISK_EX_INT13_INFO.cs | 2 +- .../Native Other/DISK_GEOMETRY.cs | 2 +- .../Native Other/DISK_GEOMETRY_EX.cs | 2 +- .../Native Other/DISK_INT13_INFO.cs | 2 +- .../Native Other/DISK_PARTITION_INFO.cs | 2 +- .../DRIVE_LAYOUT_INFORMATION_EX.cs | 2 +- .../DRIVE_LAYOUT_INFORMATION_GPT.cs | 2 +- .../DRIVE_LAYOUT_INFORMATION_MBR.cs | 2 +- .../Native Other}/DetectionType.cs | 2 +- .../Native Other}/DeviceGuid.cs | 2 +- .../Native Other/DiskInt13Union.cs | 2 +- .../Native Other}/DiskPartitionType.cs | 2 +- .../Native Other}/DosDeviceAttributes.cs | 2 +- .../Native Other}/EfiPartitionAttributes.cs | 2 +- .../Native Other/IoControlCode.cs | 2 +- .../Native Other/IoMethod.cs | 2 +- .../Native Other/PARTITION_INFORMATION_EX.cs | 2 +- .../Native Other/PARTITION_INFORMATION_GPT.cs | 2 +- .../Native Other/PARTITION_INFORMATION_MBR.cs | 2 +- .../Native Other/PARTITION_STYLE.cs | 2 +- .../Native Other}/PartitionStyle.cs | 2 +- .../Native Other}/PartitionType..cs | 2 +- .../Native Other}/SPDRP.cs | 2 +- .../Native Other/SP_DEVICE_INTERFACE_DATA.cs | 2 +- .../SP_DEVICE_INTERFACE_DETAIL_DATA.cs | 4 +- .../Native Other/SP_DEVINFO_DATA.cs | 2 +- .../STORAGE_ADAPTER_DESCRIPTOR.cs | 2 +- .../Native Other/STORAGE_BUS_TYPE.cs | 2 +- .../Native Other/STORAGE_DEVICE_DESCRIPTOR.cs | 2 +- .../Native Other/STORAGE_DEVICE_NUMBER.cs | 2 +- .../Native Other/STORAGE_DEVICE_TYPE.cs | 2 +- .../Native Other/STORAGE_MEDIA_TYPE.cs | 2 +- .../Native Other/STORAGE_PROPERTY_ID.cs | 2 +- .../Native Other/STORAGE_PROPERTY_QUERY.cs | 2 +- .../Native Other/STORAGE_QUERY_TYPE.cs | 2 +- .../SafeCmConnectMachineHandle.cs | 2 +- .../SafeSetupDiClassDevsExHandle.cs | 2 +- .../Native Other}/StorageBusType.cs | 2 +- .../Native Other}/StorageDeviceType.cs | 2 +- .../Native Other}/StorageMediaType.cs | 2 +- .../Native Other/VOLUME_DISK_EXTENTS.cs | 2 +- .../Native Other/VOLUME_INFO_FLAGS.cs | 2 +- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 1 + .../Storage/Local.GetStorageAdapterInfo.cs | 2 +- .../Storage/Local.GetStorageDeviceInfo.cs | 4 +- .../Storage/Local.GetStoragePartitionInfo.cs | 4 +- .../Storage/Local.GetVolumeDiskExtents.cs | 1 - .../Device/Volume/Volume.DefineDosDevice.cs | 3 +- .../Device/Volume/Volume.DeleteDosDevice.cs | 1 + .../Volume/Volume.DeleteVolumeMountPoint.cs | 2 +- AlphaFS/Device/Volume/Volume.DriveType.cs | 2 +- .../Volume.EnumerateVolumeMountPoints.cs | 4 +- .../Volume/Volume.EnumerateVolumePathNames.cs | 2 +- .../Device/Volume/Volume.EnumerateVolumes.cs | 4 +- AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs | 4 +- .../Device/Volume/Volume.GetVolumePathName.cs | 2 +- .../Device/Volume/Volume.QueryDosDevice.cs | 2 +- .../Volume/Volume.SetVolumeMountPoint.cs | 2 +- AlphaFS/Device/Volume/Volume.VolumeLabel.cs | 4 +- AlphaFS/Device/Volume/VolumeInfo.cs | 48 ++++---- .../Directory Class/Directory.Copy.cs | 1 + .../Directory.CreateSymbolicLink.cs | 1 + .../Directory.GetLinkTargetInfo.cs | 1 + AlphaFS/Filesystem/DiskSpaceInfo.cs | 4 +- .../File Class/File.CreateSymbolicLink.cs | 1 + .../File Class/File.GetLinkTargetInfo.cs | 3 +- AlphaFS/Filesystem/FileSystemEntryInfo.cs | 1 + .../NativeMethods.FileManagement.cs | 1 + .../LinkTargetInfo.cs | 2 + .../ReparsePointTag.cs | 0 .../SymbolicLinkTarget.cs | 0 .../SymbolicLinkTargetInfo.cs | 0 .../SymbolicLinkType.cs | 0 .../SafeEncryptedFileRawHandle.cs | 3 +- AlphaFS/Safe Handles/SafeFindFileHandle.cs | 3 +- AlphaFS/Safe Handles/SafeFindVolumeHandle.cs | 5 +- .../SafeFindVolumeMountPointHandle.cs | 5 +- .../SafeKernelTransactionHandle.cs | 3 +- .../SafeLocalMemoryBufferHandle.cs | 3 +- CHANGELOG.md | 1 - 99 files changed, 207 insertions(+), 193 deletions(-) rename AlphaFS/{Filesystem => Device}/Native Methods/NativeMethods.DeviceManagement.cs (96%) rename AlphaFS/{Filesystem => Device}/Native Methods/NativeMethods.DiskManagement.cs (99%) rename AlphaFS/{Filesystem/Native Other/DiskPartitionType.cs => Device/Native Methods/NativeMethods.DiskPartitionType.cs} (98%) rename AlphaFS/{Filesystem/Native Other/EfiPartitionAttributes.cs => Device/Native Methods/NativeMethods.EfiPartitionAttributes.cs} (98%) rename AlphaFS/{Filesystem => Device}/Native Methods/NativeMethods.VolumeManagement.cs (98%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/DEVICE_INFORMATION_FLAGS.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/DEVPROPKEY.cs (99%) rename AlphaFS/{Filesystem => Device}/Native Other/DISK_DETECTION_INFO.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/DISK_EXTENT.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/DISK_EX_INT13_INFO.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/DISK_GEOMETRY.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/DISK_GEOMETRY_EX.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/DISK_INT13_INFO.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/DISK_PARTITION_INFO.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs (97%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/DetectionType.cs (97%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/DeviceGuid.cs (99%) rename AlphaFS/{Filesystem => Device}/Native Other/DiskInt13Union.cs (97%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/DiskPartitionType.cs (99%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/DosDeviceAttributes.cs (98%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/EfiPartitionAttributes.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/IoControlCode.cs (99%) rename AlphaFS/{Filesystem => Device}/Native Other/IoMethod.cs (97%) rename AlphaFS/{Filesystem => Device}/Native Other/PARTITION_INFORMATION_EX.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/PARTITION_INFORMATION_GPT.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/PARTITION_INFORMATION_MBR.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/PARTITION_STYLE.cs (98%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/PartitionStyle.cs (98%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/PartitionType..cs (99%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/SPDRP.cs (99%) rename AlphaFS/{Filesystem => Device}/Native Other/SP_DEVICE_INTERFACE_DATA.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/SP_DEVICE_INTERFACE_DETAIL_DATA.cs (91%) rename AlphaFS/{Filesystem => Device}/Native Other/SP_DEVINFO_DATA.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs (99%) rename AlphaFS/{Filesystem => Device}/Native Other/STORAGE_BUS_TYPE.cs (99%) rename AlphaFS/{Filesystem => Device}/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs (99%) rename AlphaFS/{Filesystem => Device}/Native Other/STORAGE_DEVICE_NUMBER.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/STORAGE_DEVICE_TYPE.cs (99%) rename AlphaFS/{Filesystem => Device}/Native Other/STORAGE_MEDIA_TYPE.cs (99%) rename AlphaFS/{Filesystem => Device}/Native Other/STORAGE_PROPERTY_ID.cs (99%) rename AlphaFS/{Filesystem => Device}/Native Other/STORAGE_PROPERTY_QUERY.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/STORAGE_QUERY_TYPE.cs (98%) rename AlphaFS/{Safe Handles => Device/Native Other}/SafeCmConnectMachineHandle.cs (98%) rename AlphaFS/{Safe Handles => Device/Native Other}/SafeSetupDiClassDevsExHandle.cs (98%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/StorageBusType.cs (99%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/StorageDeviceType.cs (99%) rename AlphaFS/{Filesystem/Structures, Enumerations => Device/Native Other}/StorageMediaType.cs (99%) rename AlphaFS/{Filesystem => Device}/Native Other/VOLUME_DISK_EXTENTS.cs (98%) rename AlphaFS/{Filesystem => Device}/Native Other/VOLUME_INFO_FLAGS.cs (99%) rename AlphaFS/Filesystem/{Link Stream => Native Other}/LinkTargetInfo.cs (98%) rename AlphaFS/Filesystem/{Structures, Enumerations => Native Other}/ReparsePointTag.cs (100%) rename AlphaFS/Filesystem/{Structures, Enumerations => Native Other}/SymbolicLinkTarget.cs (100%) rename AlphaFS/Filesystem/{Link Stream => Native Other}/SymbolicLinkTargetInfo.cs (100%) rename AlphaFS/Filesystem/{Structures, Enumerations => Native Other}/SymbolicLinkType.cs (100%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs index 1a635ee57..b02c3c245 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs @@ -56,12 +56,12 @@ public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() if (driveInfo.DriveType == System.IO.DriveType.Fixed) { gotDisk = true; - Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.Disk, storageDeviceInfo.DeviceType); + Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.Disk, storageDeviceInfo.DeviceType); } if (driveInfo.DriveType == System.IO.DriveType.CDRom) - Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.CDRom, storageDeviceInfo.DeviceType); + Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.CDRom, storageDeviceInfo.DeviceType); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs index 8240b4d65..0603b46d1 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.DefineDosDevice_SymbolicLinkDriveMapping.cs @@ -50,7 +50,7 @@ private void AlphaFS_Volume_DefineDosDevice_SymbolicLinkDriveMapping(bool isNetw try { - Alphaleonis.Win32.Filesystem.Volume.DefineDosDevice(drive, folder.FullName, Alphaleonis.Win32.Filesystem.DosDeviceAttributes.RawTargetPath); + Alphaleonis.Win32.Filesystem.Volume.DefineDosDevice(drive, folder.FullName, Alphaleonis.Win32.Device.DosDeviceAttributes.RawTargetPath); // Remove Symbolic Link, no exact match: fail. diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs index bececdf49..86694210c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs @@ -48,7 +48,7 @@ private void AlphaFS_Device_EnumerateDevices() var hostName = Environment.MachineName; var classCnt = 0; - foreach (var deviceClass in EnumMemberToList()) + foreach (var deviceClass in EnumMemberToList()) { Console.WriteLine("#{0:000}\tClass: [{1}]", ++classCnt, deviceClass); diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 72c7b1ae4..8fa1a6540 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -329,20 +329,20 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + @@ -352,34 +352,34 @@ - - + + - - - - + + + + - - - - - - - - - - - - + + + + + + + + + + + + - - + + @@ -502,9 +502,9 @@ - + - + @@ -521,14 +521,14 @@ - - - + + + - - - + + + @@ -537,26 +537,26 @@ - - + + - - - - - + + + + + - - + + - + - + - + @@ -679,7 +679,7 @@ - + Code @@ -708,7 +708,7 @@ - + @@ -736,7 +736,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.DeviceInfo.cs b/AlphaFS/Device/Device.DeviceInfo.cs index 497fbd387..e00eca849 100644 --- a/AlphaFS/Device/Device.DeviceInfo.cs +++ b/AlphaFS/Device/Device.DeviceInfo.cs @@ -22,9 +22,8 @@ using Alphaleonis.Win32.Network; using System; using System.Security; -using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Device +namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] Provides access to information of a device. [Serializable] diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs index de0c2b535..2f2c3e16d 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs @@ -63,7 +63,7 @@ internal static IEnumerable EnumerateLogicalDrivesCore(bool fromEnvironm // Get through NativeMethod. - var allDrives = NativeMethods.GetLogicalDrives(); + var allDrives = Device.NativeMethods.GetLogicalDrives(); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs index 2c46668cf..30672f9db 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs @@ -36,14 +36,14 @@ internal static void CreateDirectoryJunction(SafeFileHandle safeHandle, string d { var targetDirBytes = Encoding.Unicode.GetBytes(Path.NonInterpretedPathPrefix + Path.GetRegularPathCore(directoryPath, GetFullPathOptions.AddTrailingDirectorySeparator, false)); - var header = new NativeMethods.ReparseDataBufferHeader + var header = new Filesystem.NativeMethods.ReparseDataBufferHeader { ReparseTag = ReparsePointTag.MountPoint, ReparseDataLength = (ushort) (targetDirBytes.Length + 12) }; - var mountPoint = new NativeMethods.MountPointReparseBuffer + var mountPoint = new Filesystem.NativeMethods.MountPointReparseBuffer { SubstituteNameOffset = 0, SubstituteNameLength = (ushort) targetDirBytes.Length, @@ -53,7 +53,7 @@ internal static void CreateDirectoryJunction(SafeFileHandle safeHandle, string d }; - var reparseDataBuffer = new NativeMethods.REPARSE_DATA_BUFFER + var reparseDataBuffer = new Filesystem.NativeMethods.REPARSE_DATA_BUFFER { ReparseTag = header.ReparseTag, ReparseDataLength = header.ReparseDataLength, diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs index ff95bd5be..066e7dc72 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs @@ -31,7 +31,7 @@ internal static partial class FileSystemHelper /// [AlphaFS] Deletes an NTFS directory junction. internal static void DeleteDirectoryJunction(SafeFileHandle safeHandle) { - var reparseDataBuffer = new NativeMethods.REPARSE_DATA_BUFFER + var reparseDataBuffer = new Filesystem.NativeMethods.REPARSE_DATA_BUFFER { ReparseTag = ReparsePointTag.MountPoint, ReparseDataLength = 0, diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs index a88d3b20e..c95285ac1 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs @@ -39,13 +39,13 @@ internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, stri { using (var safeBuffer = GetLinkTargetData(safeHandle, reparsePath)) { - var header = safeBuffer.PtrToStructure(); + var header = safeBuffer.PtrToStructure(); - var marshalReparseBuffer = (int)Marshal.OffsetOf(typeof(NativeMethods.ReparseDataBufferHeader), "data"); + var marshalReparseBuffer = (int)Marshal.OffsetOf(typeof(Filesystem.NativeMethods.ReparseDataBufferHeader), "data"); var dataOffset = (int)(marshalReparseBuffer + (header.ReparseTag == ReparsePointTag.MountPoint - ? Marshal.OffsetOf(typeof(NativeMethods.MountPointReparseBuffer), "data") - : Marshal.OffsetOf(typeof(NativeMethods.SymbolicLinkReparseBuffer), "data")).ToInt64()); + ? Marshal.OffsetOf(typeof(Filesystem.NativeMethods.MountPointReparseBuffer), "data") + : Marshal.OffsetOf(typeof(Filesystem.NativeMethods.SymbolicLinkReparseBuffer), "data")).ToInt64()); var dataBuffer = new byte[MAXIMUM_REPARSE_DATA_BUFFER_SIZE - dataOffset]; @@ -55,7 +55,7 @@ internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, stri // MountPoint can be a junction or mounted drive (mounted drive starts with "\??\Volume"). case ReparsePointTag.MountPoint: - var mountPoint = safeBuffer.PtrToStructure(marshalReparseBuffer); + var mountPoint = safeBuffer.PtrToStructure(marshalReparseBuffer); safeBuffer.CopyTo(dataOffset, dataBuffer); @@ -65,7 +65,7 @@ internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, stri case ReparsePointTag.SymLink: - var symLink = safeBuffer.PtrToStructure(marshalReparseBuffer); + var symLink = safeBuffer.PtrToStructure(marshalReparseBuffer); safeBuffer.CopyTo(dataOffset, dataBuffer); diff --git a/AlphaFS/Device/Local.EnumerateDevices.cs b/AlphaFS/Device/Local.EnumerateDevices.cs index afd8e302f..5a175fa1c 100644 --- a/AlphaFS/Device/Local.EnumerateDevices.cs +++ b/AlphaFS/Device/Local.EnumerateDevices.cs @@ -27,7 +27,6 @@ using System.Security; using System.Text; using Alphaleonis.Win32.Filesystem; -using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; namespace Alphaleonis.Win32.Device { @@ -153,7 +152,7 @@ private static string GetDeviceInstanceId(SafeCmConnectMachineHandle safeMachine NativeError.ThrowException(lastError, hostName); - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize / 8)) // 512 + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Filesystem.NativeMethods.DefaultFileBufferSize / 8)) // 512 { lastError = NativeMethods.CM_Get_Device_ID_Ex(diData.DevInst, safeBuffer, (uint) safeBuffer.Capacity, 0, safeMachineHandle); @@ -193,7 +192,7 @@ private static string GetDeviceBusReportedDeviceDescription(SafeHandle safeHandl return null; - var bufferSize = NativeMethods.DefaultFileBufferSize / 32; // 128 + var bufferSize = Filesystem.NativeMethods.DefaultFileBufferSize / 32; // 128 var descriptionBuffer = new byte[bufferSize]; ulong propertyType = 0; @@ -220,7 +219,7 @@ private static string GetDeviceBusReportedDeviceDescription(SafeHandle safeHandl [SecurityCritical] private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData, NativeMethods.SPDRP property) { - var bufferSize = NativeMethods.DefaultFileBufferSize / 8; // 512 + var bufferSize = Filesystem.NativeMethods.DefaultFileBufferSize / 8; // 512 while (true) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs b/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs similarity index 96% rename from AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs rename to AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs index e6d644a5c..0bd60eb38 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.DeviceManagement.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs @@ -25,7 +25,7 @@ using System.Security; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { @@ -107,7 +107,7 @@ internal static partial class NativeMethods /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. /// - /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. + /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. /// To specify a device name, use the following format: \\.\DeviceName /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 @@ -125,7 +125,7 @@ internal static partial class NativeMethods /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. /// - /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. + /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. /// To specify a device name, use the following format: \\.\DeviceName /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 @@ -143,7 +143,7 @@ internal static partial class NativeMethods /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. /// - /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. + /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. /// To specify a device name, use the following format: \\.\DeviceName /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 @@ -206,7 +206,7 @@ internal static partial class NativeMethods /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern SafeSetupDiClassDevsExHandle SetupDiGetClassDevsEx(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, [MarshalAs(UnmanagedType.U4)] DEVICE_INFORMATION_FLAGS devsExFlags, IntPtr deviceInfoSet, [MarshalAs(UnmanagedType.LPWStr)] string machineName, IntPtr reserved); + internal static extern NativeMethods.SafeSetupDiClassDevsExHandle SetupDiGetClassDevsEx(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, [MarshalAs(UnmanagedType.U4)] DEVICE_INFORMATION_FLAGS devsExFlags, IntPtr deviceInfoSet, [MarshalAs(UnmanagedType.LPWStr)] string machineName, IntPtr reserved); /// The SetupDiGetDeviceInterfaceDetail function returns details about a device interface. diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.DiskManagement.cs b/AlphaFS/Device/Native Methods/NativeMethods.DiskManagement.cs similarity index 99% rename from AlphaFS/Filesystem/Native Methods/NativeMethods.DiskManagement.cs rename to AlphaFS/Device/Native Methods/NativeMethods.DiskManagement.cs index e819ba41f..c39c4baf9 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.DiskManagement.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.DiskManagement.cs @@ -23,7 +23,7 @@ using System.Runtime.InteropServices; using System.Security; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs b/AlphaFS/Device/Native Methods/NativeMethods.DiskPartitionType.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/DiskPartitionType.cs rename to AlphaFS/Device/Native Methods/NativeMethods.DiskPartitionType.cs index 4cda85454..fce9ddabe 100644 --- a/AlphaFS/Filesystem/Native Other/DiskPartitionType.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.DiskPartitionType.cs @@ -19,7 +19,7 @@ * THE SOFTWARE. */ -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/EfiPartitionAttributes.cs b/AlphaFS/Device/Native Methods/NativeMethods.EfiPartitionAttributes.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/EfiPartitionAttributes.cs rename to AlphaFS/Device/Native Methods/NativeMethods.EfiPartitionAttributes.cs index b53b9f45a..0f5f7e60d 100644 --- a/AlphaFS/Filesystem/Native Other/EfiPartitionAttributes.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.EfiPartitionAttributes.cs @@ -21,7 +21,7 @@ using System; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs b/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs similarity index 98% rename from AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs rename to AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs index df6b2ac8a..dd3332fa7 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.VolumeManagement.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs @@ -27,7 +27,7 @@ using System.Security; using System.Text; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { @@ -193,7 +193,7 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool GetVolumeInformation([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, [MarshalAs(UnmanagedType.U4)] out VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); + internal static extern bool GetVolumeInformation([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, [MarshalAs(UnmanagedType.U4)] out Device.NativeMethods.VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); /// Retrieves information about the file system and volume associated with the specified file. @@ -208,7 +208,7 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationByHandleW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool GetVolumeInformationByHandle(SafeFileHandle hFile, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, out VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); + internal static extern bool GetVolumeInformationByHandle(SafeFileHandle hFile, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, out Device.NativeMethods.VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); /// Retrieves a volume path for the volume that is associated with the specified volume mount point (drive letter, volume path, or mounted folder). diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DEVICE_INFORMATION_FLAGS.cs b/AlphaFS/Device/Native Other/DEVICE_INFORMATION_FLAGS.cs similarity index 98% rename from AlphaFS/Filesystem/Structures, Enumerations/DEVICE_INFORMATION_FLAGS.cs rename to AlphaFS/Device/Native Other/DEVICE_INFORMATION_FLAGS.cs index 463954b2e..bdda24caf 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DEVICE_INFORMATION_FLAGS.cs +++ b/AlphaFS/Device/Native Other/DEVICE_INFORMATION_FLAGS.cs @@ -21,7 +21,7 @@ using System; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs b/AlphaFS/Device/Native Other/DEVPROPKEY.cs similarity index 99% rename from AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs rename to AlphaFS/Device/Native Other/DEVPROPKEY.cs index 6bc7b3004..dc2b569da 100644 --- a/AlphaFS/Filesystem/Native Other/DEVPROPKEY.cs +++ b/AlphaFS/Device/Native Other/DEVPROPKEY.cs @@ -22,7 +22,7 @@ using System; using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs b/AlphaFS/Device/Native Other/DISK_DETECTION_INFO.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs rename to AlphaFS/Device/Native Other/DISK_DETECTION_INFO.cs index dcf75320c..d7f58fe92 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_DETECTION_INFO.cs +++ b/AlphaFS/Device/Native Other/DISK_DETECTION_INFO.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs b/AlphaFS/Device/Native Other/DISK_EXTENT.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs rename to AlphaFS/Device/Native Other/DISK_EXTENT.cs index 6b75e4f8f..318af048d 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_EXTENT.cs +++ b/AlphaFS/Device/Native Other/DISK_EXTENT.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs b/AlphaFS/Device/Native Other/DISK_EX_INT13_INFO.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs rename to AlphaFS/Device/Native Other/DISK_EX_INT13_INFO.cs index e22fed401..91c8fe043 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_EX_INT13_INFO.cs +++ b/AlphaFS/Device/Native Other/DISK_EX_INT13_INFO.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs b/AlphaFS/Device/Native Other/DISK_GEOMETRY.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs rename to AlphaFS/Device/Native Other/DISK_GEOMETRY.cs index 040ebc003..165b76a1e 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY.cs +++ b/AlphaFS/Device/Native Other/DISK_GEOMETRY.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs b/AlphaFS/Device/Native Other/DISK_GEOMETRY_EX.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs rename to AlphaFS/Device/Native Other/DISK_GEOMETRY_EX.cs index 4f288d475..bfa978ea6 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_GEOMETRY_EX.cs +++ b/AlphaFS/Device/Native Other/DISK_GEOMETRY_EX.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs b/AlphaFS/Device/Native Other/DISK_INT13_INFO.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs rename to AlphaFS/Device/Native Other/DISK_INT13_INFO.cs index 8b7f98a79..75cbd628b 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_INT13_INFO.cs +++ b/AlphaFS/Device/Native Other/DISK_INT13_INFO.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs b/AlphaFS/Device/Native Other/DISK_PARTITION_INFO.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs rename to AlphaFS/Device/Native Other/DISK_PARTITION_INFO.cs index c53f0426c..15efc0fcc 100644 --- a/AlphaFS/Filesystem/Native Other/DISK_PARTITION_INFO.cs +++ b/AlphaFS/Device/Native Other/DISK_PARTITION_INFO.cs @@ -22,7 +22,7 @@ using System; using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs b/AlphaFS/Device/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs rename to AlphaFS/Device/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs index 5b3cc4c1a..809e25e91 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs +++ b/AlphaFS/Device/Native Other/DRIVE_LAYOUT_INFORMATION_EX.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs b/AlphaFS/Device/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs rename to AlphaFS/Device/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs index 92d55b7b5..1019f9e1e 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs +++ b/AlphaFS/Device/Native Other/DRIVE_LAYOUT_INFORMATION_GPT.cs @@ -22,7 +22,7 @@ using System; using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs b/AlphaFS/Device/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs similarity index 97% rename from AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs rename to AlphaFS/Device/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs index bcc7cd56b..036c02ca8 100644 --- a/AlphaFS/Filesystem/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs +++ b/AlphaFS/Device/Native Other/DRIVE_LAYOUT_INFORMATION_MBR.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs b/AlphaFS/Device/Native Other/DetectionType.cs similarity index 97% rename from AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs rename to AlphaFS/Device/Native Other/DetectionType.cs index 4ab90a488..5028f9ad3 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DetectionType.cs +++ b/AlphaFS/Device/Native Other/DetectionType.cs @@ -19,7 +19,7 @@ * THE SOFTWARE. */ -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// The DETECTION_TYPE enumeration type is used in conjunction with the IOCTL_DISK_GET_DRIVE_GEOMETRY_EX request and the DISK_GEOMETRY_EX structure to determine the type of formatting used by the BIOS to record the disk geometry. public enum DetectionType diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs b/AlphaFS/Device/Native Other/DeviceGuid.cs similarity index 99% rename from AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs rename to AlphaFS/Device/Native Other/DeviceGuid.cs index 08d04a854..4e1fdefaa 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DeviceGuid.cs +++ b/AlphaFS/Device/Native Other/DeviceGuid.cs @@ -22,7 +22,7 @@ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// System-Defined Device Interface Classes /// http://msdn.microsoft.com/en-us/library/windows/hardware/ff541389%28v=vs.85%29.aspx diff --git a/AlphaFS/Filesystem/Native Other/DiskInt13Union.cs b/AlphaFS/Device/Native Other/DiskInt13Union.cs similarity index 97% rename from AlphaFS/Filesystem/Native Other/DiskInt13Union.cs rename to AlphaFS/Device/Native Other/DiskInt13Union.cs index 4457bad31..ef2e49cdc 100644 --- a/AlphaFS/Filesystem/Native Other/DiskInt13Union.cs +++ b/AlphaFS/Device/Native Other/DiskInt13Union.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs b/AlphaFS/Device/Native Other/DiskPartitionType.cs similarity index 99% rename from AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs rename to AlphaFS/Device/Native Other/DiskPartitionType.cs index 354d03660..a4524a9ff 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DiskPartitionType.cs +++ b/AlphaFS/Device/Native Other/DiskPartitionType.cs @@ -21,7 +21,7 @@ using System.Diagnostics.CodeAnalysis; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// Valid partition types that are used by disk drivers. /// https://technet.microsoft.com/en-us/library/cc739412.aspx diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DosDeviceAttributes.cs b/AlphaFS/Device/Native Other/DosDeviceAttributes.cs similarity index 98% rename from AlphaFS/Filesystem/Structures, Enumerations/DosDeviceAttributes.cs rename to AlphaFS/Device/Native Other/DosDeviceAttributes.cs index 8a1994e3b..6bdccdb39 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DosDeviceAttributes.cs +++ b/AlphaFS/Device/Native Other/DosDeviceAttributes.cs @@ -20,7 +20,7 @@ */ using System; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// Defines the controllable aspects of the Volume.DefineDosDevice() method. [Flags] diff --git a/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs b/AlphaFS/Device/Native Other/EfiPartitionAttributes.cs similarity index 98% rename from AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs rename to AlphaFS/Device/Native Other/EfiPartitionAttributes.cs index 4625f22b8..d727e54fe 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/EfiPartitionAttributes.cs +++ b/AlphaFS/Device/Native Other/EfiPartitionAttributes.cs @@ -22,7 +22,7 @@ using System; using System.Diagnostics.CodeAnalysis; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// The Extensible Firmware Interface (EFI) partition attributes. [SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags")] diff --git a/AlphaFS/Filesystem/Native Other/IoControlCode.cs b/AlphaFS/Device/Native Other/IoControlCode.cs similarity index 99% rename from AlphaFS/Filesystem/Native Other/IoControlCode.cs rename to AlphaFS/Device/Native Other/IoControlCode.cs index 4c740bdf0..fa945e474 100644 --- a/AlphaFS/Filesystem/Native Other/IoControlCode.cs +++ b/AlphaFS/Device/Native Other/IoControlCode.cs @@ -22,7 +22,7 @@ using System; using System.IO; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/IoMethod.cs b/AlphaFS/Device/Native Other/IoMethod.cs similarity index 97% rename from AlphaFS/Filesystem/Native Other/IoMethod.cs rename to AlphaFS/Device/Native Other/IoMethod.cs index c164cfd5e..247517e3c 100644 --- a/AlphaFS/Filesystem/Native Other/IoMethod.cs +++ b/AlphaFS/Device/Native Other/IoMethod.cs @@ -19,7 +19,7 @@ * THE SOFTWARE. */ -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs b/AlphaFS/Device/Native Other/PARTITION_INFORMATION_EX.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs rename to AlphaFS/Device/Native Other/PARTITION_INFORMATION_EX.cs index 5f54d8390..d3014ef77 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_EX.cs +++ b/AlphaFS/Device/Native Other/PARTITION_INFORMATION_EX.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs b/AlphaFS/Device/Native Other/PARTITION_INFORMATION_GPT.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs rename to AlphaFS/Device/Native Other/PARTITION_INFORMATION_GPT.cs index 7c56e26dd..8df112bab 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_GPT.cs +++ b/AlphaFS/Device/Native Other/PARTITION_INFORMATION_GPT.cs @@ -22,7 +22,7 @@ using System; using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs b/AlphaFS/Device/Native Other/PARTITION_INFORMATION_MBR.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs rename to AlphaFS/Device/Native Other/PARTITION_INFORMATION_MBR.cs index 01bbda84b..dc4af9c4d 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_INFORMATION_MBR.cs +++ b/AlphaFS/Device/Native Other/PARTITION_INFORMATION_MBR.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs b/AlphaFS/Device/Native Other/PARTITION_STYLE.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs rename to AlphaFS/Device/Native Other/PARTITION_STYLE.cs index f0da68308..26f24f987 100644 --- a/AlphaFS/Filesystem/Native Other/PARTITION_STYLE.cs +++ b/AlphaFS/Device/Native Other/PARTITION_STYLE.cs @@ -19,7 +19,7 @@ * THE SOFTWARE. */ -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs b/AlphaFS/Device/Native Other/PartitionStyle.cs similarity index 98% rename from AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs rename to AlphaFS/Device/Native Other/PartitionStyle.cs index 7d88c918b..09fabf9fe 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionStyle.cs +++ b/AlphaFS/Device/Native Other/PartitionStyle.cs @@ -21,7 +21,7 @@ using System.Diagnostics.CodeAnalysis; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// Represents the format of a partition. /// diff --git a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs b/AlphaFS/Device/Native Other/PartitionType..cs similarity index 99% rename from AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs rename to AlphaFS/Device/Native Other/PartitionType..cs index e0560b0ca..c767a8590 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/PartitionType..cs +++ b/AlphaFS/Device/Native Other/PartitionType..cs @@ -23,7 +23,7 @@ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// Specifies the different types of partition GUIDs. /// https://en.wikipedia.org/wiki/GUID_Partition_Table diff --git a/AlphaFS/Filesystem/Structures, Enumerations/SPDRP.cs b/AlphaFS/Device/Native Other/SPDRP.cs similarity index 99% rename from AlphaFS/Filesystem/Structures, Enumerations/SPDRP.cs rename to AlphaFS/Device/Native Other/SPDRP.cs index 72656e936..b8982fe98 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/SPDRP.cs +++ b/AlphaFS/Device/Native Other/SPDRP.cs @@ -21,7 +21,7 @@ using System; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/SP_DEVICE_INTERFACE_DATA.cs b/AlphaFS/Device/Native Other/SP_DEVICE_INTERFACE_DATA.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/SP_DEVICE_INTERFACE_DATA.cs rename to AlphaFS/Device/Native Other/SP_DEVICE_INTERFACE_DATA.cs index 94ecb6881..d6a3392d5 100644 --- a/AlphaFS/Filesystem/Native Other/SP_DEVICE_INTERFACE_DATA.cs +++ b/AlphaFS/Device/Native Other/SP_DEVICE_INTERFACE_DATA.cs @@ -22,7 +22,7 @@ using System; using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/SP_DEVICE_INTERFACE_DETAIL_DATA.cs b/AlphaFS/Device/Native Other/SP_DEVICE_INTERFACE_DETAIL_DATA.cs similarity index 91% rename from AlphaFS/Filesystem/Native Other/SP_DEVICE_INTERFACE_DETAIL_DATA.cs rename to AlphaFS/Device/Native Other/SP_DEVICE_INTERFACE_DETAIL_DATA.cs index c44f25192..bc87ad94c 100644 --- a/AlphaFS/Filesystem/Native Other/SP_DEVICE_INTERFACE_DETAIL_DATA.cs +++ b/AlphaFS/Device/Native Other/SP_DEVICE_INTERFACE_DETAIL_DATA.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { @@ -33,7 +33,7 @@ internal struct SP_DEVICE_INTERFACE_DETAIL_DATA [MarshalAs(UnmanagedType.U4)] public uint cbSize; /// The device interface path. This path can be passed to Win32 functions such as CreateFile. - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MaxPath)] public readonly string DevicePath; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Filesystem.NativeMethods.MaxPath)] public readonly string DevicePath; } } } \ No newline at end of file diff --git a/AlphaFS/Filesystem/Native Other/SP_DEVINFO_DATA.cs b/AlphaFS/Device/Native Other/SP_DEVINFO_DATA.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/SP_DEVINFO_DATA.cs rename to AlphaFS/Device/Native Other/SP_DEVINFO_DATA.cs index 480ed6597..96d1abfe2 100644 --- a/AlphaFS/Filesystem/Native Other/SP_DEVINFO_DATA.cs +++ b/AlphaFS/Device/Native Other/SP_DEVINFO_DATA.cs @@ -22,7 +22,7 @@ using System; using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs b/AlphaFS/Device/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs similarity index 99% rename from AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs rename to AlphaFS/Device/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs index 25ab2476a..7d173cc6f 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs +++ b/AlphaFS/Device/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs @@ -22,7 +22,7 @@ using System; using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs b/AlphaFS/Device/Native Other/STORAGE_BUS_TYPE.cs similarity index 99% rename from AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs rename to AlphaFS/Device/Native Other/STORAGE_BUS_TYPE.cs index c70b42909..0d02dff4d 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_BUS_TYPE.cs +++ b/AlphaFS/Device/Native Other/STORAGE_BUS_TYPE.cs @@ -19,7 +19,7 @@ * THE SOFTWARE. */ -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs b/AlphaFS/Device/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs similarity index 99% rename from AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs rename to AlphaFS/Device/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs index fb2bb6468..ef753040d 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs +++ b/AlphaFS/Device/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs b/AlphaFS/Device/Native Other/STORAGE_DEVICE_NUMBER.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs rename to AlphaFS/Device/Native Other/STORAGE_DEVICE_NUMBER.cs index 701fbfdcd..cec0426f2 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_NUMBER.cs +++ b/AlphaFS/Device/Native Other/STORAGE_DEVICE_NUMBER.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs b/AlphaFS/Device/Native Other/STORAGE_DEVICE_TYPE.cs similarity index 99% rename from AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs rename to AlphaFS/Device/Native Other/STORAGE_DEVICE_TYPE.cs index 6ea4502e9..040c1088f 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_DEVICE_TYPE.cs +++ b/AlphaFS/Device/Native Other/STORAGE_DEVICE_TYPE.cs @@ -19,7 +19,7 @@ * THE SOFTWARE. */ -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs b/AlphaFS/Device/Native Other/STORAGE_MEDIA_TYPE.cs similarity index 99% rename from AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs rename to AlphaFS/Device/Native Other/STORAGE_MEDIA_TYPE.cs index 09817a841..3ff776e7c 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_MEDIA_TYPE.cs +++ b/AlphaFS/Device/Native Other/STORAGE_MEDIA_TYPE.cs @@ -19,7 +19,7 @@ * THE SOFTWARE. */ -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs b/AlphaFS/Device/Native Other/STORAGE_PROPERTY_ID.cs similarity index 99% rename from AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs rename to AlphaFS/Device/Native Other/STORAGE_PROPERTY_ID.cs index 66c6d730a..197fdb1cb 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_ID.cs +++ b/AlphaFS/Device/Native Other/STORAGE_PROPERTY_ID.cs @@ -19,7 +19,7 @@ * THE SOFTWARE. */ -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs b/AlphaFS/Device/Native Other/STORAGE_PROPERTY_QUERY.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs rename to AlphaFS/Device/Native Other/STORAGE_PROPERTY_QUERY.cs index 2be357e55..342e1e69b 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_PROPERTY_QUERY.cs +++ b/AlphaFS/Device/Native Other/STORAGE_PROPERTY_QUERY.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs b/AlphaFS/Device/Native Other/STORAGE_QUERY_TYPE.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs rename to AlphaFS/Device/Native Other/STORAGE_QUERY_TYPE.cs index 739153f30..7973aabbe 100644 --- a/AlphaFS/Filesystem/Native Other/STORAGE_QUERY_TYPE.cs +++ b/AlphaFS/Device/Native Other/STORAGE_QUERY_TYPE.cs @@ -19,7 +19,7 @@ * THE SOFTWARE. */ -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Safe Handles/SafeCmConnectMachineHandle.cs b/AlphaFS/Device/Native Other/SafeCmConnectMachineHandle.cs similarity index 98% rename from AlphaFS/Safe Handles/SafeCmConnectMachineHandle.cs rename to AlphaFS/Device/Native Other/SafeCmConnectMachineHandle.cs index a208a7a89..481c9436d 100644 --- a/AlphaFS/Safe Handles/SafeCmConnectMachineHandle.cs +++ b/AlphaFS/Device/Native Other/SafeCmConnectMachineHandle.cs @@ -22,7 +22,7 @@ using System.Security; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// Represents a wrapper class for a handle used by the CM_Connect_Machine/CM_Disconnect_Machine Win32 API functions. [SecurityCritical] diff --git a/AlphaFS/Safe Handles/SafeSetupDiClassDevsExHandle.cs b/AlphaFS/Device/Native Other/SafeSetupDiClassDevsExHandle.cs similarity index 98% rename from AlphaFS/Safe Handles/SafeSetupDiClassDevsExHandle.cs rename to AlphaFS/Device/Native Other/SafeSetupDiClassDevsExHandle.cs index 7af555740..52a1d7136 100644 --- a/AlphaFS/Safe Handles/SafeSetupDiClassDevsExHandle.cs +++ b/AlphaFS/Device/Native Other/SafeSetupDiClassDevsExHandle.cs @@ -22,7 +22,7 @@ using Microsoft.Win32.SafeHandles; using System.Security; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs b/AlphaFS/Device/Native Other/StorageBusType.cs similarity index 99% rename from AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs rename to AlphaFS/Device/Native Other/StorageBusType.cs index 6f7fdbce0..57603cb96 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageBusType.cs +++ b/AlphaFS/Device/Native Other/StorageBusType.cs @@ -21,7 +21,7 @@ using System.Diagnostics.CodeAnalysis; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// Provides a symbolic means of representing storage bus types. public enum StorageBusType diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs b/AlphaFS/Device/Native Other/StorageDeviceType.cs similarity index 99% rename from AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs rename to AlphaFS/Device/Native Other/StorageDeviceType.cs index 5b3f683d2..160e2f4f5 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageDeviceType.cs +++ b/AlphaFS/Device/Native Other/StorageDeviceType.cs @@ -21,7 +21,7 @@ using System.Diagnostics.CodeAnalysis; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// The type of device. Values from 0 through 32,767 are reserved for use by Microsoft. Values from 32,768 through 65,535 are reserved for use by other vendors. /// The following values are defined by Microsoft. diff --git a/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs b/AlphaFS/Device/Native Other/StorageMediaType.cs similarity index 99% rename from AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs rename to AlphaFS/Device/Native Other/StorageMediaType.cs index 7a3965d2d..b414c4fc4 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/StorageMediaType.cs +++ b/AlphaFS/Device/Native Other/StorageMediaType.cs @@ -21,7 +21,7 @@ using System.Diagnostics.CodeAnalysis; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { /// Specifies various types of storage media. [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] diff --git a/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs b/AlphaFS/Device/Native Other/VOLUME_DISK_EXTENTS.cs similarity index 98% rename from AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs rename to AlphaFS/Device/Native Other/VOLUME_DISK_EXTENTS.cs index 344cbb765..ef9f25787 100644 --- a/AlphaFS/Filesystem/Native Other/VOLUME_DISK_EXTENTS.cs +++ b/AlphaFS/Device/Native Other/VOLUME_DISK_EXTENTS.cs @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Filesystem/Native Other/VOLUME_INFO_FLAGS.cs b/AlphaFS/Device/Native Other/VOLUME_INFO_FLAGS.cs similarity index 99% rename from AlphaFS/Filesystem/Native Other/VOLUME_INFO_FLAGS.cs rename to AlphaFS/Device/Native Other/VOLUME_INFO_FLAGS.cs index 9a4037614..5e39fcb0c 100644 --- a/AlphaFS/Filesystem/Native Other/VOLUME_INFO_FLAGS.cs +++ b/AlphaFS/Device/Native Other/VOLUME_INFO_FLAGS.cs @@ -21,7 +21,7 @@ using System; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index 79ed01a7e..56020fa81 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -24,6 +24,7 @@ using System.Linq; using System.Security; using System.Security.AccessControl; +using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index c737e3864..70752c345 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -78,7 +78,7 @@ private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle saf // Get storage adapter info. - using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, NativeMethods.DefaultFileBufferSize / 8)) + using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) { if (null == safeBuffer) { diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index 5c2ac804b..c8990971d 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -88,7 +88,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri // Get storage device info. - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, Filesystem.NativeMethods.FILE_ANY_ACCESS)) { var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); @@ -145,7 +145,7 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH // Get storage device info. - using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, NativeMethods.DefaultFileBufferSize / 2)) + using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) { if (null == safeBuffer) { diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index e746faead..ee02e551c 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -54,7 +54,7 @@ public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) return null; - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, Filesystem.NativeMethods.FILE_ANY_ACCESS)) return GetStoragePartitionInfoNative(safeHandle, devicePath); } @@ -71,7 +71,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle // Get storage partition info. - using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, pathToDevice, NativeMethods.DefaultFileBufferSize / 4)) + using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, pathToDevice, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) { if (null == safeBuffer) { diff --git a/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs b/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs index 375900541..453cbe44e 100644 --- a/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs @@ -22,7 +22,6 @@ using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; -using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/Volume/Volume.DefineDosDevice.cs b/AlphaFS/Device/Volume/Volume.DefineDosDevice.cs index a9f1f7792..5d357afb9 100644 --- a/AlphaFS/Device/Volume/Volume.DefineDosDevice.cs +++ b/AlphaFS/Device/Volume/Volume.DefineDosDevice.cs @@ -22,6 +22,7 @@ using System; using System.Runtime.InteropServices; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -93,7 +94,7 @@ internal static void DefineDosDeviceCore(bool isDefine, string deviceName, strin using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { - var success = NativeMethods.DefineDosDevice(deviceAttributes, deviceName, targetPath); + var success = Device.NativeMethods.DefineDosDevice(deviceAttributes, deviceName, targetPath); var lastError = Marshal.GetLastWin32Error(); if (!success) diff --git a/AlphaFS/Device/Volume/Volume.DeleteDosDevice.cs b/AlphaFS/Device/Volume/Volume.DeleteDosDevice.cs index 60f7c6286..1ca2f1266 100644 --- a/AlphaFS/Device/Volume/Volume.DeleteDosDevice.cs +++ b/AlphaFS/Device/Volume/Volume.DeleteDosDevice.cs @@ -21,6 +21,7 @@ using System.Diagnostics.CodeAnalysis; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Device/Volume/Volume.DeleteVolumeMountPoint.cs b/AlphaFS/Device/Volume/Volume.DeleteVolumeMountPoint.cs index 820450398..6fe795f1a 100644 --- a/AlphaFS/Device/Volume/Volume.DeleteVolumeMountPoint.cs +++ b/AlphaFS/Device/Volume/Volume.DeleteVolumeMountPoint.cs @@ -76,7 +76,7 @@ internal static void DeleteVolumeMountPointCore(KernelTransaction transaction, s // 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 success = Device.NativeMethods.DeleteVolumeMountPoint(Path.AddTrailingDirectorySeparator(volumeMountPoint, false)); var lastError = Marshal.GetLastWin32Error(); if (!success && !continueOnException) diff --git a/AlphaFS/Device/Volume/Volume.DriveType.cs b/AlphaFS/Device/Volume/Volume.DriveType.cs index 8dfb8b23e..da9820b9f 100644 --- a/AlphaFS/Device/Volume/Volume.DriveType.cs +++ b/AlphaFS/Device/Volume/Volume.DriveType.cs @@ -52,7 +52,7 @@ public static DriveType GetDriveType(string drivePath) using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) - return NativeMethods.GetDriveType(drivePath); + return Device.NativeMethods.GetDriveType(drivePath); } } } diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs index 4a1800053..b5109fe4a 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs @@ -52,7 +52,7 @@ public static IEnumerable EnumerateVolumeMountPoints(string volumeGuid) using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) - using (var handle = NativeMethods.FindFirstVolumeMountPoint(volumeGuid, buffer, (uint)buffer.Capacity)) + using (var handle = Device.NativeMethods.FindFirstVolumeMountPoint(volumeGuid, buffer, (uint)buffer.Capacity)) { var lastError = Marshal.GetLastWin32Error(); @@ -73,7 +73,7 @@ public static IEnumerable EnumerateVolumeMountPoints(string volumeGuid) yield return buffer.ToString(); - while (NativeMethods.FindNextVolumeMountPoint(handle, buffer, (uint)buffer.Capacity)) + while (Device.NativeMethods.FindNextVolumeMountPoint(handle, buffer, (uint)buffer.Capacity)) { lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs index 570bef8ec..136f80b5e 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs @@ -52,7 +52,7 @@ public static IEnumerable EnumerateVolumePathNames(string volumeGuid) using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) - while (!NativeMethods.GetVolumePathNamesForVolumeName(volumeGuid, buffer, (uint) buffer.Length, out bufferSize)) + while (!Device.NativeMethods.GetVolumePathNamesForVolumeName(volumeGuid, buffer, (uint) buffer.Length, out bufferSize)) { var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs index 454b8ca8e..3c83beb02 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs @@ -36,7 +36,7 @@ public static IEnumerable EnumerateVolumes() var buffer = new StringBuilder(50); using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) - using (var handle = NativeMethods.FindFirstVolume(buffer, (uint) buffer.Capacity)) + using (var handle = Device.NativeMethods.FindFirstVolume(buffer, (uint) buffer.Capacity)) { var lastError = Marshal.GetLastWin32Error(); @@ -48,7 +48,7 @@ public static IEnumerable EnumerateVolumes() yield return buffer.ToString(); - while (NativeMethods.FindNextVolume(handle, buffer, (uint) buffer.Capacity)) + while (Device.NativeMethods.FindNextVolume(handle, buffer, (uint) buffer.Capacity)) { lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs b/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs index fd8349353..fd2cf247c 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs @@ -71,7 +71,7 @@ public static string GetVolumeGuid(string volumeMountPoint) // GetVolumeNameForVolumeMountPoint() // 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists. - success = NativeMethods.GetVolumeNameForVolumeMountPoint(volumeMountPoint, volumeGuid, (uint)volumeGuid.Capacity); + success = Device.NativeMethods.GetVolumeNameForVolumeMountPoint(volumeMountPoint, volumeGuid, (uint)volumeGuid.Capacity); lastError = Marshal.GetLastWin32Error(); @@ -81,7 +81,7 @@ public static string GetVolumeGuid(string volumeMountPoint) // The string must end with a trailing backslash. - success = NativeMethods.GetVolumeNameForVolumeMountPoint(Path.AddTrailingDirectorySeparator(volumeGuid.ToString(), false), uniqueName, (uint)uniqueName.Capacity); + success = Device.NativeMethods.GetVolumeNameForVolumeMountPoint(Path.AddTrailingDirectorySeparator(volumeGuid.ToString(), false), uniqueName, (uint)uniqueName.Capacity); lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs b/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs index 605a8dc4a..8824d4f08 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs @@ -51,7 +51,7 @@ public static string GetVolumePathName(string path) // 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 success = Device.NativeMethods.GetVolumePathName(pathLp, volumeRootPath, (uint) volumeRootPath.Capacity); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs b/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs index b3eb53f91..7a5f821fc 100644 --- a/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs +++ b/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs @@ -108,7 +108,7 @@ internal static IEnumerable QueryDosDeviceCore(string deviceName, bool s { var cBuffer = new char[bufferSize]; - returnedBufferSize = NativeMethods.QueryDosDevice(deviceName, cBuffer, bufferSize); + returnedBufferSize = Device.NativeMethods.QueryDosDevice(deviceName, cBuffer, bufferSize); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs b/AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs index f868a7297..bd9f751df 100644 --- a/AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs +++ b/AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs @@ -64,7 +64,7 @@ public static void SetVolumeMountPoint(string volumeMountPoint, string volumeGui // 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 success = Device.NativeMethods.SetVolumeMountPoint(volumeMountPoint, volumeGuid); var lastError = Marshal.GetLastWin32Error(); if (!success) diff --git a/AlphaFS/Device/Volume/Volume.VolumeLabel.cs b/AlphaFS/Device/Volume/Volume.VolumeLabel.cs index a523b4621..8994d1598 100644 --- a/AlphaFS/Device/Volume/Volume.VolumeLabel.cs +++ b/AlphaFS/Device/Volume/Volume.VolumeLabel.cs @@ -71,7 +71,7 @@ public static void SetCurrentVolumeLabel(string volumeName) throw new ArgumentNullException("volumeName"); - var success = NativeMethods.SetVolumeLabel(null, volumeName); + var success = Device.NativeMethods.SetVolumeLabel(null, volumeName); var lastError = Marshal.GetLastWin32Error(); if (!success) @@ -103,7 +103,7 @@ public static void SetVolumeLabel(string volumePath, string volumeName) // 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 success = Device.NativeMethods.SetVolumeLabel(volumePath, volumeName); var lastError = Marshal.GetLastWin32Error(); if (!success) diff --git a/AlphaFS/Device/Volume/VolumeInfo.cs b/AlphaFS/Device/Volume/VolumeInfo.cs index a914c8a1b..9bece9056 100644 --- a/AlphaFS/Device/Volume/VolumeInfo.cs +++ b/AlphaFS/Device/Volume/VolumeInfo.cs @@ -39,7 +39,7 @@ public sealed class VolumeInfo [NonSerialized] private readonly bool _continueOnAccessError; [NonSerialized] private readonly SafeFileHandle _volumeHandle; [NonSerialized] private string _guid; - [NonSerialized] private NativeMethods.VOLUME_INFO_FLAGS _volumeInfoAttributes; + [NonSerialized] private Device.NativeMethods.VOLUME_INFO_FLAGS _volumeInfoAttributes; #endregion // Private Fields @@ -134,28 +134,28 @@ public override string ToString() /// The specified volume supports preserved case of file names when it places a name on disk. public bool CasePreservedNames { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_CASE_PRESERVED_NAMES) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_CASE_PRESERVED_NAMES) != 0; } } /// The specified volume supports case-sensitive file names. public bool CaseSensitiveSearch { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_CASE_SENSITIVE_SEARCH) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_CASE_SENSITIVE_SEARCH) != 0; } } /// The specified volume supports file-based compression. public bool Compression { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_FILE_COMPRESSION) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_FILE_COMPRESSION) != 0; } } /// The specified volume is a direct access (DAX) volume. public bool DirectAccess { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_DAX_VOLUME) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_DAX_VOLUME) != 0; } } @@ -213,7 +213,7 @@ public string Guid /// The specified volume supports named streams. public bool NamedStreams { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_NAMED_STREAMS) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_NAMED_STREAMS) != 0; } } @@ -221,21 +221,21 @@ public bool NamedStreams [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Acls")] public bool PersistentAcls { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_PERSISTENT_ACLS) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_PERSISTENT_ACLS) != 0; } } /// The specified volume is read-only. public bool ReadOnlyVolume { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_READ_ONLY_VOLUME) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_READ_ONLY_VOLUME) != 0; } } /// The specified volume supports a single sequential write. public bool SequentialWriteOnce { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SEQUENTIAL_WRITE_ONCE) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_SEQUENTIAL_WRITE_ONCE) != 0; } } @@ -247,63 +247,63 @@ public bool SequentialWriteOnce /// The specified volume supports the Encrypted File System (EFS). public bool SupportsEncryption { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_ENCRYPTION) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_ENCRYPTION) != 0; } } /// The specified volume supports extended attributes. public bool SupportsExtendedAttributes { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_EXTENDED_ATTRIBUTES) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_EXTENDED_ATTRIBUTES) != 0; } } /// The specified volume supports hard links. public bool SupportsHardLinks { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_HARD_LINKS) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_HARD_LINKS) != 0; } } /// The specified volume supports object identifiers. public bool SupportsObjectIds { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_OBJECT_IDS) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_OBJECT_IDS) != 0; } } /// The file system supports open by FileID. public bool SupportsOpenByFileId { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_OPEN_BY_FILE_ID) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_OPEN_BY_FILE_ID) != 0; } } /// The specified volume supports remote storage. (This property does not appear on MSDN) public bool SupportsRemoteStorage { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_REMOTE_STORAGE) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_REMOTE_STORAGE) != 0; } } /// The specified volume supports re-parse points. public bool SupportsReparsePoints { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_REPARSE_POINTS) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_REPARSE_POINTS) != 0; } } /// The specified volume supports sparse files. public bool SupportsSparseFiles { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_SPARSE_FILES) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_SPARSE_FILES) != 0; } } /// The specified volume supports transactions. public bool SupportsTransactions { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_TRANSACTIONS) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_TRANSACTIONS) != 0; } } @@ -311,28 +311,28 @@ public bool SupportsTransactions [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usn")] public bool SupportsUsnJournal { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_USN_JOURNAL) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_SUPPORTS_USN_JOURNAL) != 0; } } /// The specified volume supports Unicode in file names as they appear on disk. public bool UnicodeOnDisk { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_UNICODE_ON_DISK) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_UNICODE_ON_DISK) != 0; } } /// The specified volume is a compressed volume, for example, a DoubleSpace volume. public bool VolumeIsCompressed { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_VOLUME_IS_COMPRESSED) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_VOLUME_IS_COMPRESSED) != 0; } } /// The specified volume supports disk quotas. public bool VolumeQuotas { - get { return (_volumeInfoAttributes & NativeMethods.VOLUME_INFO_FLAGS.FILE_VOLUME_QUOTAS) != 0; } + get { return (_volumeInfoAttributes & Device.NativeMethods.VOLUME_INFO_FLAGS.FILE_VOLUME_QUOTAS) != 0; } } #endregion // Properties @@ -356,10 +356,10 @@ public void Refresh() { var success = null != _volumeHandle && NativeMethods.IsAtLeastWindowsVista - ? NativeMethods.GetVolumeInformationByHandle(_volumeHandle, volumeNameBuffer, (uint) volumeNameBuffer.Capacity, out serialNumber, out maximumComponentLength, out _volumeInfoAttributes, fileSystemNameBuffer, (uint) fileSystemNameBuffer.Capacity) + ? Device.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); + : Device.NativeMethods.GetVolumeInformation(Path.AddTrailingDirectorySeparator(Name, false), volumeNameBuffer, (uint) volumeNameBuffer.Capacity, out serialNumber, out maximumComponentLength, out _volumeInfoAttributes, fileSystemNameBuffer, (uint) fileSystemNameBuffer.Capacity); lastError = (uint) Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs index e1f81a1f2..97c828f85 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs @@ -23,6 +23,7 @@ using System.Collections.Generic; using System.IO; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs b/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs index d4831786a..8fa0107e5 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs @@ -23,6 +23,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetLinkTargetInfo.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetLinkTargetInfo.cs index a55dd9b94..d37811eab 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetLinkTargetInfo.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetLinkTargetInfo.cs @@ -21,6 +21,7 @@ using System; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/DiskSpaceInfo.cs b/AlphaFS/Filesystem/DiskSpaceInfo.cs index 4635a9129..656bd4991 100644 --- a/AlphaFS/Filesystem/DiskSpaceInfo.cs +++ b/AlphaFS/Filesystem/DiskSpaceInfo.cs @@ -205,7 +205,7 @@ public void Refresh() { long freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes; - var success = NativeMethods.GetDiskFreeSpaceEx(DriveName, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes); + var success = Device.NativeMethods.GetDiskFreeSpaceEx(DriveName, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes); lastError = Marshal.GetLastWin32Error(); @@ -226,7 +226,7 @@ public void Refresh() int sectorsPerCluster, bytesPerSector, numberOfFreeClusters; uint totalNumberOfClusters; - var success = NativeMethods.GetDiskFreeSpace(DriveName, out sectorsPerCluster, out bytesPerSector, out numberOfFreeClusters, out totalNumberOfClusters); + var success = Device.NativeMethods.GetDiskFreeSpace(DriveName, out sectorsPerCluster, out bytesPerSector, out numberOfFreeClusters, out totalNumberOfClusters); lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs b/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs index f0e1404d7..5319dea77 100644 --- a/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs +++ b/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs @@ -25,6 +25,7 @@ using System.IO; using System.Runtime.InteropServices; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.GetLinkTargetInfo.cs b/AlphaFS/Filesystem/File Class/File.GetLinkTargetInfo.cs index 92a4fec8c..f127f9577 100644 --- a/AlphaFS/Filesystem/File Class/File.GetLinkTargetInfo.cs +++ b/AlphaFS/Filesystem/File Class/File.GetLinkTargetInfo.cs @@ -22,6 +22,7 @@ using System; using System.IO; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -108,7 +109,7 @@ internal static LinkTargetInfo GetLinkTargetInfoCore(KernelTransaction transacti using (var safeHandle = CreateFileCore(transaction, reparsePath, eAttributes, null, FileMode.Open, 0, FileShare.ReadWrite, pathFormat != PathFormat.LongFullPath, continueOnException, pathFormat)) - return null != safeHandle ? Device.FileSystemHelper.GetLinkTargetInfo(safeHandle, reparsePath) : null; + return null != safeHandle ? FileSystemHelper.GetLinkTargetInfo(safeHandle, reparsePath) : null; } } } diff --git a/AlphaFS/Filesystem/FileSystemEntryInfo.cs b/AlphaFS/Filesystem/FileSystemEntryInfo.cs index 061ea126b..1772401fc 100644 --- a/AlphaFS/Filesystem/FileSystemEntryInfo.cs +++ b/AlphaFS/Filesystem/FileSystemEntryInfo.cs @@ -22,6 +22,7 @@ using System; using System.IO; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs index a17ef5315..1e048819b 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs @@ -28,6 +28,7 @@ using System.Security; using System.Security.AccessControl; using System.Text; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Link Stream/LinkTargetInfo.cs b/AlphaFS/Filesystem/Native Other/LinkTargetInfo.cs similarity index 98% rename from AlphaFS/Filesystem/Link Stream/LinkTargetInfo.cs rename to AlphaFS/Filesystem/Native Other/LinkTargetInfo.cs index d822ca82e..a7d9a7a98 100644 --- a/AlphaFS/Filesystem/Link Stream/LinkTargetInfo.cs +++ b/AlphaFS/Filesystem/Native Other/LinkTargetInfo.cs @@ -19,6 +19,8 @@ * THE SOFTWARE. */ +using Alphaleonis.Win32.Filesystem; + namespace Alphaleonis.Win32.Filesystem { /// Information about the target of a symbolic link or mount point. diff --git a/AlphaFS/Filesystem/Structures, Enumerations/ReparsePointTag.cs b/AlphaFS/Filesystem/Native Other/ReparsePointTag.cs similarity index 100% rename from AlphaFS/Filesystem/Structures, Enumerations/ReparsePointTag.cs rename to AlphaFS/Filesystem/Native Other/ReparsePointTag.cs diff --git a/AlphaFS/Filesystem/Structures, Enumerations/SymbolicLinkTarget.cs b/AlphaFS/Filesystem/Native Other/SymbolicLinkTarget.cs similarity index 100% rename from AlphaFS/Filesystem/Structures, Enumerations/SymbolicLinkTarget.cs rename to AlphaFS/Filesystem/Native Other/SymbolicLinkTarget.cs diff --git a/AlphaFS/Filesystem/Link Stream/SymbolicLinkTargetInfo.cs b/AlphaFS/Filesystem/Native Other/SymbolicLinkTargetInfo.cs similarity index 100% rename from AlphaFS/Filesystem/Link Stream/SymbolicLinkTargetInfo.cs rename to AlphaFS/Filesystem/Native Other/SymbolicLinkTargetInfo.cs diff --git a/AlphaFS/Filesystem/Structures, Enumerations/SymbolicLinkType.cs b/AlphaFS/Filesystem/Native Other/SymbolicLinkType.cs similarity index 100% rename from AlphaFS/Filesystem/Structures, Enumerations/SymbolicLinkType.cs rename to AlphaFS/Filesystem/Native Other/SymbolicLinkType.cs diff --git a/AlphaFS/Safe Handles/SafeEncryptedFileRawHandle.cs b/AlphaFS/Safe Handles/SafeEncryptedFileRawHandle.cs index 135ca39df..a3f46b8d3 100644 --- a/AlphaFS/Safe Handles/SafeEncryptedFileRawHandle.cs +++ b/AlphaFS/Safe Handles/SafeEncryptedFileRawHandle.cs @@ -1,8 +1,9 @@ using System; using System.Security; +using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32 { /// Represents a wrapper class for a handle used by the OpenEncryptedFileRaw Win32 API functions. [SecurityCritical] diff --git a/AlphaFS/Safe Handles/SafeFindFileHandle.cs b/AlphaFS/Safe Handles/SafeFindFileHandle.cs index a0f0788a8..1890b9c98 100644 --- a/AlphaFS/Safe Handles/SafeFindFileHandle.cs +++ b/AlphaFS/Safe Handles/SafeFindFileHandle.cs @@ -21,9 +21,10 @@ using System; using System.Security; +using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32 { /// Represents a wrapper class for a handle used by the FindFirstFile/FindNextFile Win32 API functions. [SecurityCritical] diff --git a/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs b/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs index 062f50d90..616bd7715 100644 --- a/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs +++ b/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs @@ -21,9 +21,10 @@ using System; using System.Security; +using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32 { /// Represents a wrapper class for a handle used by the FindFirstVolume/FindNextVolume methods of the Win32 API. [SecurityCritical] @@ -50,7 +51,7 @@ public SafeFindVolumeHandle(IntPtr handle, bool callerHandle) : base(callerHandl /// protected override bool ReleaseHandle() { - return NativeMethods.FindVolumeClose(handle); + return Device.NativeMethods.FindVolumeClose(handle); } } } diff --git a/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs b/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs index 2bca379e9..13e15b166 100644 --- a/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs +++ b/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs @@ -21,9 +21,10 @@ using System; using System.Security; +using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32 { /// Represents a wrapper class for a handle used by the FindFirstVolumeMountPoint/FindNextVolumeMountPoint methods of the Win32 API. [SecurityCritical] @@ -51,7 +52,7 @@ public SafeFindVolumeMountPointHandle(IntPtr handle, bool callerHandle) : base(c /// protected override bool ReleaseHandle() { - return NativeMethods.FindVolumeMountPointClose(handle); + return Device.NativeMethods.FindVolumeMountPointClose(handle); } } } diff --git a/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs b/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs index 7943fd1b0..ab892d2e8 100644 --- a/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs +++ b/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs @@ -21,8 +21,9 @@ using Microsoft.Win32.SafeHandles; using System.Security; +using Alphaleonis.Win32.Filesystem; -namespace Alphaleonis.Win32.Filesystem +namespace Alphaleonis.Win32 { /// Provides a concrete implementation of SafeHandle supporting transactions. internal class SafeKernelTransactionHandle : SafeHandleMinusOneIsInvalid diff --git a/AlphaFS/Safe Handles/SafeLocalMemoryBufferHandle.cs b/AlphaFS/Safe Handles/SafeLocalMemoryBufferHandle.cs index b4690ca71..586ab165f 100644 --- a/AlphaFS/Safe Handles/SafeLocalMemoryBufferHandle.cs +++ b/AlphaFS/Safe Handles/SafeLocalMemoryBufferHandle.cs @@ -21,9 +21,10 @@ using System; using System.Runtime.InteropServices; +using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32.Security +namespace Alphaleonis.Win32 { /// An IntPtr wrapper which can be used as the result of a Marshal.AllocHGlobal operation. /// Calls Marshal.FreeHGlobal when disposed or finalized. diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f0c3846e..4082c7841 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,6 @@ Version 2.3 (2018-XX-XX) ### Breaking Changes - Issue #426: Correct casing of enum `STREAM_ATTRIBUTES` -- Issue #455: As a result, moved class `DeviceInfo` from `Alphaleonis.Win32.Filesystem` to `Alphaleonis.Win32.Device` namespace. Version 2.2.2 (2018-06-05) From d635901c03fcf8f7d7a4054a6a4c7982d0d7bc6d Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 7 Jun 2018 22:31:36 +0200 Subject: [PATCH 088/133] Removed obsolete references. --- AlphaFS/Device/Device.DeviceInfo.cs | 2 +- .../FilesystemHelper.Compression.cs | 3 +- ...ilesystemHelper.CreateDirectoryJunction.cs | 2 +- ...ilesystemHelper.DeleteDirectoryJunction.cs | 2 +- .../FilesystemHelper.GetDevicePath.cs | 26 ++++++++ .../FilesystemHelper.GetLinkTarget.cs | 2 +- .../FilesystemHelper.OpenPhysicalDrive.cs | 2 +- AlphaFS/Device/Local.EnumerateDevices.cs | 2 +- AlphaFS/Device/Local.InvokeDeviceIoData.cs | 1 - .../NativeMethods.DeviceManagement.cs | 12 ++-- .../NativeMethods.VolumeManagement.cs | 6 +- .../Native Other/DosDeviceAttributes.cs | 1 + .../Native Other/PARTITION_INFORMATION_GPT.cs | 9 +-- .../Native Other/STORAGE_PROPERTY_ID.cs | 2 +- .../Device/Native Other/STORAGE_QUERY_TYPE.cs | 2 +- .../SafeSetupDiClassDevsExHandle.cs | 2 +- AlphaFS/Device/Native Other/StorageBusType.cs | 2 +- .../Local.EnumeratePhysicalDisks.cs | 3 +- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 3 +- .../Storage/Device.StorageAdapterInfo.cs | 1 - .../Storage/Device.StorageDeviceInfo.cs | 1 - .../Storage/Device.StorageGptPartitionInfo.cs | 2 - .../Storage/Device.StorageMbrPartitionInfo.cs | 2 - .../Storage/Device.StoragePartitionInfo.cs | 4 +- .../Device/Storage/Local.GetDeviceIoData.cs | 1 - .../Storage/Local.GetStorageAdapterInfo.cs | 7 +- .../Storage/Local.GetStorageDeviceInfo.cs | 10 ++- .../Storage/Local.GetStoragePartitionInfo.cs | 7 +- AlphaFS/Device/Volume/VolumeInfo.cs | 2 +- .../Directory Class/Directory.Compress.cs | 5 +- .../Directory Class/Directory.Copy.cs | 1 - .../Directory.CreateDirectory.cs | 3 +- .../Directory.CreateJunction.cs | 3 +- .../Directory.CreateSymbolicLink.cs | 1 - .../Directory.DeleteJunction.cs | 3 +- .../Directory.DisableCompression.cs | 9 +-- .../Directory.EnableCompression.cs | 9 +-- .../Directory.EnumerateDirectories.cs | 1 - ...ectory.EnumerateFileIdBothDirectoryInfo.cs | 2 +- .../Directory.EnumerateFileSystemEntries.cs | 1 - .../Directory.EnumerateFiles.cs | 1 - .../Directory.GetChangeTime.cs | 2 +- .../Directory.GetDirectories.cs | 1 - .../Directory.GetFileSystemEntries.cs | 1 - .../Directory Class/Directory.GetFiles.cs | 1 - .../Directory.GetLinkTargetInfo.cs | 1 - .../DirectoryInfo.Compression.cs | 5 +- .../Exceptions/AlreadyExistsException.cs | 3 +- .../Exceptions/DeviceNotReadyException.cs | 3 +- .../Exceptions/DirectoryNotEmptyException.cs | 3 +- .../Exceptions/NotAReparsePointException.cs | 3 +- .../Exceptions/NotSameDeviceException.cs | 3 +- .../UnrecognizedReparsePointException.cs | 3 +- .../Filesystem/File Class/File.Compress.cs | 9 +-- AlphaFS/Filesystem/File Class/File.Create.cs | 5 +- .../File Class/File.CreateSymbolicLink.cs | 1 - .../Filesystem/File Class/File.CreateText.cs | 1 - .../Filesystem/File Class/File.Decompress.cs | 9 +-- .../File Class/File.GetChangeTime.cs | 2 +- .../File Class/File.GetFileIdInfo.cs | 2 +- .../File Class/File.GetFileInfoByHandle.cs | 2 +- AlphaFS/Filesystem/File Class/File.GetSize.cs | 2 +- AlphaFS/Filesystem/File Class/File.Open.cs | 5 +- .../Filesystem/File Class/File.OpenRead.cs | 1 - .../File Class/File.ReadAllBytes.cs | 1 - .../File Class/File.ReadAllLines.cs | 1 - .../Filesystem/File Class/File.ReadAllText.cs | 1 - .../Filesystem/File Class/File.ReadLines.cs | 1 - .../File Class/File.WriteAllBytes.cs | 1 - .../FileInfo Class/FileInfo.Compress.cs | 3 +- .../FileInfo Class/FileInfo.Decompress.cs | 3 +- AlphaFS/Filesystem/FileSystemEntryInfo.cs | 1 - AlphaFS/Filesystem/FindFileSystemEntryInfo.cs | 1 - AlphaFS/Filesystem/KernelTransaction.cs | 2 +- .../Link Stream/BackupFileStream.cs | 4 +- .../NativeMethods.BackupStreams.cs | 2 +- .../NativeMethods.FileManagement.cs | 7 +- .../Native Methods/NativeMethods.Handles.cs | 1 + .../NativeMethods.KernelTransactions.cs | 1 + .../NativeMethods.PathManagement.cs | 1 + .../Native Other/FILE_INFO_BY_HANDLE_CLASS.cs | 2 +- .../Filesystem/Native Other/LinkTargetInfo.cs | 2 - .../Path.GetFinalPathNameByHandle.cs | 2 +- .../Filesystem/Path Class/Path.LocalToUnc.cs | 2 +- .../DirectoryEnumerationFilters.cs | 1 - .../Structures, Enumerations/FileIdInfo.cs | 10 +-- AlphaFS/GlobalSuppressions.cs | 37 ++++++----- AlphaFS/NativeError.cs | 10 +-- AlphaFS/Network/DfsInfo.cs | 2 +- AlphaFS/Network/Host Class/Host.GetUncName.cs | 2 +- .../Host Class/Host.SMB.EnumerateDrives.cs | 2 +- .../Host.SMB.GetHostShareFromPath.cs | 2 +- AlphaFS/Network/Host Class/Host.cs | 2 +- AlphaFS/Network/OpenConnectionInfo.cs | 12 ++-- AlphaFS/Network/OpenResourceInfo.cs | 6 +- AlphaFS/Network/ShareInfo.cs | 2 +- AlphaFS/Safe Handles/SafeFindFileHandle.cs | 2 +- AlphaFS/Safe Handles/SafeFindVolumeHandle.cs | 6 +- .../SafeFindVolumeMountPointHandle.cs | 4 +- .../SafeKernelTransactionHandle.cs | 2 +- .../SafeNativeMemoryBufferHandle.cs | 2 +- .../Native Other/TOKEN_ELEVATION_TYPE.cs | 2 +- .../Native Other/TOKEN_INFORMATION_CLASS.cs | 2 +- AlphaFS/Utils.cs | 65 ++++++++++--------- 104 files changed, 230 insertions(+), 210 deletions(-) diff --git a/AlphaFS/Device/Device.DeviceInfo.cs b/AlphaFS/Device/Device.DeviceInfo.cs index e00eca849..c7df55b40 100644 --- a/AlphaFS/Device/Device.DeviceInfo.cs +++ b/AlphaFS/Device/Device.DeviceInfo.cs @@ -19,9 +19,9 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Network; using System; using System.Security; +using Alphaleonis.Win32.Network; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.Compression.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.Compression.cs index cbbda71e0..a176953e2 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.Compression.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.Compression.cs @@ -23,6 +23,7 @@ using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; +using File = Alphaleonis.Win32.Filesystem.File; namespace Alphaleonis.Win32.Device { @@ -36,7 +37,7 @@ internal static partial class FileSystemHelper [SecurityCritical] internal static void ToggleCompressionCore(KernelTransaction transaction, string path, bool compress, PathFormat pathFormat) { - using (var safeHandle = Win32.Filesystem.File.CreateFileCore(transaction, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.Modify, FileShare.None, true, false, pathFormat)) + using (var safeHandle = File.CreateFileCore(transaction, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.Modify, FileShare.None, true, false, pathFormat)) using (Local.InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.FSCTL_SET_COMPRESSION, compress ? 1 : 0, path)) { } } diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs index 30672f9db..0732bf2a7 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs @@ -19,12 +19,12 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; using Alphaleonis.Win32.Filesystem; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs index 066e7dc72..3093fbb68 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs @@ -19,10 +19,10 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; using Alphaleonis.Win32.Filesystem; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs index fe55ba76e..520079b6e 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System; using System.Globalization; using Alphaleonis.Win32.Filesystem; @@ -26,6 +27,31 @@ namespace Alphaleonis.Win32.Device { internal static partial class FileSystemHelper { + /// Determines and retrieves the such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + /// Returns the path string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + internal static string GetDevicePath(string devicePath) + { + string unused; + + return GetDevicePath(devicePath, out unused); + } + + + /// Determines and retrieves the such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// Returns the path string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + /// If is a logical drive, it is returned in internal static string GetDevicePath(string devicePath, out string logicalDrive) { bool isDrive; diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs index c95285ac1..f20980292 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs @@ -19,13 +19,13 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; using Alphaleonis.Win32.Filesystem; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs index 853e3e32f..ec2b5c533 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs @@ -20,11 +20,11 @@ */ using System; -using Microsoft.Win32.SafeHandles; using System.IO; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; +using Microsoft.Win32.SafeHandles; using File = Alphaleonis.Win32.Filesystem.File; namespace Alphaleonis.Win32.Device diff --git a/AlphaFS/Device/Local.EnumerateDevices.cs b/AlphaFS/Device/Local.EnumerateDevices.cs index 5a175fa1c..b425f30ba 100644 --- a/AlphaFS/Device/Local.EnumerateDevices.cs +++ b/AlphaFS/Device/Local.EnumerateDevices.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Network; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -27,6 +26,7 @@ using System.Security; using System.Text; using Alphaleonis.Win32.Filesystem; +using Alphaleonis.Win32.Network; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/Local.InvokeDeviceIoData.cs b/AlphaFS/Device/Local.InvokeDeviceIoData.cs index 94bad5199..2abab8f59 100644 --- a/AlphaFS/Device/Local.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Local.InvokeDeviceIoData.cs @@ -23,7 +23,6 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; -using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device diff --git a/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs b/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs index 0bd60eb38..7ed7fb348 100644 --- a/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs @@ -45,7 +45,7 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CM_Connect_MachineW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] - public static extern int CM_Connect_Machine([MarshalAs(UnmanagedType.LPWStr)] string uncServerName, out SafeCmConnectMachineHandle phMachine); + internal static extern int CM_Connect_Machine([MarshalAs(UnmanagedType.LPWStr)] string uncServerName, out SafeCmConnectMachineHandle phMachine); /// The CM_Get_Device_ID_Ex function retrieves the device instance ID for a specified device instance on a local or a remote machine. @@ -62,7 +62,7 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CM_Get_Device_ID_ExW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I4)] - public static extern int CM_Get_Device_ID_Ex([MarshalAs(UnmanagedType.U4)] uint dnDevInst, SafeGlobalMemoryBufferHandle buffer, [MarshalAs(UnmanagedType.U4)] uint bufferLen, [MarshalAs(UnmanagedType.U4)] uint ulFlags, SafeCmConnectMachineHandle hMachine); + internal static extern int CM_Get_Device_ID_Ex([MarshalAs(UnmanagedType.U4)] uint dnDevInst, SafeGlobalMemoryBufferHandle buffer, [MarshalAs(UnmanagedType.U4)] uint bufferLen, [MarshalAs(UnmanagedType.U4)] uint ulFlags, SafeCmConnectMachineHandle hMachine); /// The CM_Disconnect_Machine function removes a connection to a remote machine. @@ -107,7 +107,7 @@ internal static partial class NativeMethods /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. /// - /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. + /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. /// To specify a device name, use the following format: \\.\DeviceName /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 @@ -125,7 +125,7 @@ internal static partial class NativeMethods /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. /// - /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. + /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. /// To specify a device name, use the following format: \\.\DeviceName /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 @@ -143,7 +143,7 @@ internal static partial class NativeMethods /// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation. /// - /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. + /// To retrieve a handle to the device, you must call the function with either the name of a device or the name of the driver associated with a device. /// To specify a device name, use the following format: \\.\DeviceName /// Minimum supported client: Windows XP /// Minimum supported server: Windows Server 2003 @@ -206,7 +206,7 @@ internal static partial class NativeMethods /// [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern NativeMethods.SafeSetupDiClassDevsExHandle SetupDiGetClassDevsEx(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, [MarshalAs(UnmanagedType.U4)] DEVICE_INFORMATION_FLAGS devsExFlags, IntPtr deviceInfoSet, [MarshalAs(UnmanagedType.LPWStr)] string machineName, IntPtr reserved); + internal static extern SafeSetupDiClassDevsExHandle SetupDiGetClassDevsEx(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, [MarshalAs(UnmanagedType.U4)] DEVICE_INFORMATION_FLAGS devsExFlags, IntPtr deviceInfoSet, [MarshalAs(UnmanagedType.LPWStr)] string machineName, IntPtr reserved); /// The SetupDiGetDeviceInterfaceDetail function returns details about a device interface. diff --git a/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs b/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs index dd3332fa7..86870c4d0 100644 --- a/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs @@ -19,13 +19,13 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { @@ -193,7 +193,7 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool GetVolumeInformation([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, [MarshalAs(UnmanagedType.U4)] out Device.NativeMethods.VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); + internal static extern bool GetVolumeInformation([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, [MarshalAs(UnmanagedType.U4)] out VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); /// Retrieves information about the file system and volume associated with the specified file. @@ -208,7 +208,7 @@ internal static partial class NativeMethods [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationByHandleW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool GetVolumeInformationByHandle(SafeFileHandle hFile, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, out Device.NativeMethods.VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); + internal static extern bool GetVolumeInformationByHandle(SafeFileHandle hFile, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, out VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); /// Retrieves a volume path for the volume that is associated with the specified volume mount point (drive letter, volume path, or mounted folder). diff --git a/AlphaFS/Device/Native Other/DosDeviceAttributes.cs b/AlphaFS/Device/Native Other/DosDeviceAttributes.cs index 6bdccdb39..2e06e0874 100644 --- a/AlphaFS/Device/Native Other/DosDeviceAttributes.cs +++ b/AlphaFS/Device/Native Other/DosDeviceAttributes.cs @@ -18,6 +18,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + using System; namespace Alphaleonis.Win32.Device diff --git a/AlphaFS/Device/Native Other/PARTITION_INFORMATION_GPT.cs b/AlphaFS/Device/Native Other/PARTITION_INFORMATION_GPT.cs index 8df112bab..657c3f608 100644 --- a/AlphaFS/Device/Native Other/PARTITION_INFORMATION_GPT.cs +++ b/AlphaFS/Device/Native Other/PARTITION_INFORMATION_GPT.cs @@ -26,10 +26,11 @@ namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { - /// Contains GUID partition table (GPT) partition information. - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// Contains GUID partition table (GPT) partition information. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] internal struct PARTITION_INFORMATION_GPT { diff --git a/AlphaFS/Device/Native Other/STORAGE_PROPERTY_ID.cs b/AlphaFS/Device/Native Other/STORAGE_PROPERTY_ID.cs index 197fdb1cb..0ad8fbfa5 100644 --- a/AlphaFS/Device/Native Other/STORAGE_PROPERTY_ID.cs +++ b/AlphaFS/Device/Native Other/STORAGE_PROPERTY_ID.cs @@ -33,7 +33,7 @@ public enum STORAGE_PROPERTY_ID StorageDeviceProperty = 0, /// Indicates that the caller is querying for the adapter descriptor, . - StorageAdapterProperty, + StorageAdapterProperty ///// Indicates that the caller is querying for the device identifiers provided with the SCSI vital product data pages. Data is returned using the structure. //StorageDeviceIdProperty, diff --git a/AlphaFS/Device/Native Other/STORAGE_QUERY_TYPE.cs b/AlphaFS/Device/Native Other/STORAGE_QUERY_TYPE.cs index 7973aabbe..a428babb4 100644 --- a/AlphaFS/Device/Native Other/STORAGE_QUERY_TYPE.cs +++ b/AlphaFS/Device/Native Other/STORAGE_QUERY_TYPE.cs @@ -30,7 +30,7 @@ internal static partial class NativeMethods public enum STORAGE_QUERY_TYPE { /// Instructs the driver to return an appropriate descriptor. - PropertyStandardQuery = 0, + PropertyStandardQuery = 0 ///// Instructs the driver to report whether the descriptor is supported. //PropertyExistsQuery = 1, diff --git a/AlphaFS/Device/Native Other/SafeSetupDiClassDevsExHandle.cs b/AlphaFS/Device/Native Other/SafeSetupDiClassDevsExHandle.cs index 52a1d7136..d8428c50d 100644 --- a/AlphaFS/Device/Native Other/SafeSetupDiClassDevsExHandle.cs +++ b/AlphaFS/Device/Native Other/SafeSetupDiClassDevsExHandle.cs @@ -19,8 +19,8 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System.Security; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/Native Other/StorageBusType.cs b/AlphaFS/Device/Native Other/StorageBusType.cs index 57603cb96..582274b72 100644 --- a/AlphaFS/Device/Native Other/StorageBusType.cs +++ b/AlphaFS/Device/Native Other/StorageBusType.cs @@ -92,6 +92,6 @@ public enum StorageBusType /// Indicates a file-backed virtual bus type. /// Windows Server 2003 and Windows XP: This value is not supported before Windows Vista and Windows Server 2008. - FileBackedVirtual = NativeMethods.STORAGE_BUS_TYPE.BusTypeFileBackedVirtual, + FileBackedVirtual = NativeMethods.STORAGE_BUS_TYPE.BusTypeFileBackedVirtual } } diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 0382fa6cd..55cf2c31e 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -25,6 +25,7 @@ using System.Linq; using System.Security; using Alphaleonis.Win32.Filesystem; +using Alphaleonis.Win32.Security; using DriveInfo = Alphaleonis.Win32.Filesystem.DriveInfo; using Path = Alphaleonis.Win32.Filesystem.Path; @@ -37,7 +38,7 @@ public static partial class Local [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() { - return EnumeratePhysicalDisksCore(Security.ProcessContext.IsElevatedProcess); + return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess); } diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index 56020fa81..58a5597f1 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -25,6 +25,7 @@ using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; +using Alphaleonis.Win32.Security; namespace Alphaleonis.Win32.Device { @@ -53,7 +54,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) bool isVolume; bool isDeviceInfo; - var isElevated = Security.ProcessContext.IsElevatedProcess; + var isElevated = ProcessContext.IsElevatedProcess; devicePath = FileSystemHelper.ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); diff --git a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs index f8a1fd6e2..1ec4381cc 100644 --- a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs @@ -23,7 +23,6 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; -using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index b9705ea1f..5f66d0080 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -23,7 +23,6 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; -using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs b/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs index 859a87a08..334889dad 100644 --- a/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs @@ -23,8 +23,6 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; -using Alphaleonis.Win32.Filesystem; -using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs b/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs index 2f9549886..d0085683a 100644 --- a/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs @@ -23,8 +23,6 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; -using Alphaleonis.Win32.Filesystem; -using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index 8a76a1d9b..d0a8016da 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -26,8 +26,6 @@ using System.Globalization; using System.Linq; using System.Security; -using Alphaleonis.Win32.Filesystem; -using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; namespace Alphaleonis.Win32.Device { @@ -214,7 +212,7 @@ internal set public int PartitionCount { get; private set; } - /// The format of the partition. For a list of values, see . + /// The format of the partition. For a list of values, see . public PartitionStyle PartitionStyle { get; private set; } diff --git a/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs b/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs index 6ddd49176..a1fc9317f 100644 --- a/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs +++ b/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs @@ -23,7 +23,6 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; -using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index 70752c345..8d4b944a4 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -23,9 +23,8 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security.AccessControl; -using Microsoft.Win32.SafeHandles; using Alphaleonis.Win32.Filesystem; -using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { @@ -47,9 +46,7 @@ public static partial class Local /// public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) { - string unused; - - var pathToDevice = FileSystemHelper.GetDevicePath(devicePath, out unused); + var pathToDevice = FileSystemHelper.GetDevicePath(devicePath); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index c8990971d..782e74e85 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -23,9 +23,9 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security.AccessControl; -using Microsoft.Win32.SafeHandles; using Alphaleonis.Win32.Filesystem; -using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; +using Alphaleonis.Win32.Security; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { @@ -49,7 +49,7 @@ public static partial class Local /// public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { - return GetStorageDeviceInfoCore(Security.ProcessContext.IsElevatedProcess, devicePath); + return GetStorageDeviceInfoCore(ProcessContext.IsElevatedProcess, devicePath); } @@ -73,9 +73,7 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) /// internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, string devicePath) { - string unused; - - var pathToDevice = FileSystemHelper.GetDevicePath(devicePath, out unused); + var pathToDevice = FileSystemHelper.GetDevicePath(devicePath); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index ee02e551c..7455d4782 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -24,9 +24,8 @@ using System.Globalization; using System.Runtime.InteropServices; using System.Security.AccessControl; -using Microsoft.Win32.SafeHandles; using Alphaleonis.Win32.Filesystem; -using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { @@ -46,9 +45,7 @@ public static partial class Local /// public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) { - string unused; - - var pathToDevice = FileSystemHelper.GetDevicePath(devicePath, out unused); + var pathToDevice = FileSystemHelper.GetDevicePath(devicePath); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; diff --git a/AlphaFS/Device/Volume/VolumeInfo.cs b/AlphaFS/Device/Volume/VolumeInfo.cs index 9bece9056..6091b2500 100644 --- a/AlphaFS/Device/Volume/VolumeInfo.cs +++ b/AlphaFS/Device/Volume/VolumeInfo.cs @@ -19,13 +19,13 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Compress.cs b/AlphaFS/Filesystem/Directory Class/Directory.Compress.cs index 401863f9b..ed4219682 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Compress.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Compress.cs @@ -22,6 +22,7 @@ using System; using System.IO; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -343,10 +344,10 @@ internal static void CompressDecompressCore(KernelTransaction transaction, strin // Traverse the source folder, processing files and folders. foreach (var fsei in EnumerateFileSystemEntryInfosCore(null, transaction, pathLp, searchPattern, null, options | DirectoryEnumerationOptions.AsLongPath, filters, PathFormat.LongFullPath)) - Device.FileSystemHelper.ToggleCompressionCore(transaction, fsei, compress, PathFormat.LongFullPath); + FileSystemHelper.ToggleCompressionCore(transaction, fsei, compress, PathFormat.LongFullPath); // Compress the root directory, the given path. - Device.FileSystemHelper.ToggleCompressionCore(transaction, pathLp, compress, PathFormat.LongFullPath); + FileSystemHelper.ToggleCompressionCore(transaction, pathLp, compress, PathFormat.LongFullPath); } } } diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs index 97c828f85..e1f81a1f2 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs @@ -23,7 +23,6 @@ using System.Collections.Generic; using System.IO; using System.Security; -using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.CreateDirectory.cs b/AlphaFS/Filesystem/Directory Class/Directory.CreateDirectory.cs index 1f211390d..14dee7c9d 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.CreateDirectory.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.CreateDirectory.cs @@ -27,6 +27,7 @@ using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -781,7 +782,7 @@ internal static DirectoryInfo CreateDirectoryCore(KernelTransaction transaction, } else if (compress) - Device.FileSystemHelper.ToggleCompressionCore(transaction, folderLp, true, pathFormat); + FileSystemHelper.ToggleCompressionCore(transaction, folderLp, true, pathFormat); } diff --git a/AlphaFS/Filesystem/Directory Class/Directory.CreateJunction.cs b/AlphaFS/Filesystem/Directory Class/Directory.CreateJunction.cs index b56eaf40a..2fd7a8239 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.CreateJunction.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.CreateJunction.cs @@ -24,6 +24,7 @@ using System.IO; using System.Security; using System.Security.AccessControl; +using Alphaleonis.Win32.Device; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem @@ -439,7 +440,7 @@ internal static string CreateJunctionCore(KernelTransaction transaction, string CreateDirectoryCore(transaction, junctionPath, null, null, false, pathFormat); using (var safeHandle = OpenDirectoryJunction(transaction, junctionPath, pathFormat)) - Device.FileSystemHelper.CreateDirectoryJunction(safeHandle, directoryPath); + FileSystemHelper.CreateDirectoryJunction(safeHandle, directoryPath); // Copy the target date and time stamps to the directory junction. diff --git a/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs b/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs index 8fa0107e5..d4831786a 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.CreateSymbolicLink.cs @@ -23,7 +23,6 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; -using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.DeleteJunction.cs b/AlphaFS/Filesystem/Directory Class/Directory.DeleteJunction.cs index 3c7ae7499..0bad5a842 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.DeleteJunction.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.DeleteJunction.cs @@ -23,6 +23,7 @@ using System.Globalization; using System.IO; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -213,7 +214,7 @@ internal static void DeleteJunctionCore(KernelTransaction transaction, FileSyste // Remove the directory junction. using (var safeHandle = OpenDirectoryJunction(transaction, fsEntryInfo.LongFullPath, pathFormat)) - Device.FileSystemHelper.DeleteDirectoryJunction(safeHandle); + FileSystemHelper.DeleteDirectoryJunction(safeHandle); // Optionally the folder itself, which should and must be empty. diff --git a/AlphaFS/Filesystem/Directory Class/Directory.DisableCompression.cs b/AlphaFS/Filesystem/Directory Class/Directory.DisableCompression.cs index c2f4b39ad..5e9003003 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.DisableCompression.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.DisableCompression.cs @@ -22,6 +22,7 @@ using System; using System.IO; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -39,7 +40,7 @@ public static partial class Directory [SecurityCritical] public static void DisableCompression(string path) { - Device.FileSystemHelper.ToggleCompressionCore(null, path, false, PathFormat.RelativePath); + FileSystemHelper.ToggleCompressionCore(null, path, false, PathFormat.RelativePath); } @@ -56,7 +57,7 @@ public static void DisableCompression(string path) [SecurityCritical] public static void DisableCompression(string path, PathFormat pathFormat) { - Device.FileSystemHelper.ToggleCompressionCore(null, path, false, pathFormat); + FileSystemHelper.ToggleCompressionCore(null, path, false, pathFormat); } @@ -75,7 +76,7 @@ public static void DisableCompression(string path, PathFormat pathFormat) [SecurityCritical] public static void DisableCompressionTransacted(KernelTransaction transaction, string path) { - Device.FileSystemHelper.ToggleCompressionCore(transaction, path, false, PathFormat.RelativePath); + FileSystemHelper.ToggleCompressionCore(transaction, path, false, PathFormat.RelativePath); } @@ -93,7 +94,7 @@ public static void DisableCompressionTransacted(KernelTransaction transaction, s [SecurityCritical] public static void DisableCompressionTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { - Device.FileSystemHelper.ToggleCompressionCore(transaction, path, false, pathFormat); + FileSystemHelper.ToggleCompressionCore(transaction, path, false, pathFormat); } } } diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnableCompression.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnableCompression.cs index 21e63d625..84d95f499 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnableCompression.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnableCompression.cs @@ -22,6 +22,7 @@ using System; using System.IO; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -39,7 +40,7 @@ public static partial class Directory [SecurityCritical] public static void EnableCompression(string path) { - Device.FileSystemHelper.ToggleCompressionCore(null, path, true, PathFormat.RelativePath); + FileSystemHelper.ToggleCompressionCore(null, path, true, PathFormat.RelativePath); } /// [AlphaFS] Enables NTFS compression of the specified directory and the files in it. @@ -55,7 +56,7 @@ public static void EnableCompression(string path) [SecurityCritical] public static void EnableCompression(string path, PathFormat pathFormat) { - Device.FileSystemHelper.ToggleCompressionCore(null, path, true, pathFormat); + FileSystemHelper.ToggleCompressionCore(null, path, true, pathFormat); } @@ -74,7 +75,7 @@ public static void EnableCompression(string path, PathFormat pathFormat) [SecurityCritical] public static void EnableCompressionTransacted(KernelTransaction transaction, string path) { - Device.FileSystemHelper.ToggleCompressionCore(transaction, path, true, PathFormat.RelativePath); + FileSystemHelper.ToggleCompressionCore(transaction, path, true, PathFormat.RelativePath); } @@ -92,7 +93,7 @@ public static void EnableCompressionTransacted(KernelTransaction transaction, st [SecurityCritical] public static void EnableCompressionTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { - Device.FileSystemHelper.ToggleCompressionCore(transaction, path, true, pathFormat); + FileSystemHelper.ToggleCompressionCore(transaction, path, true, pathFormat); } } } diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateDirectories.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateDirectories.cs index 841916986..dd638c7cc 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateDirectories.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateDirectories.cs @@ -23,7 +23,6 @@ using System.Collections.Generic; using System.IO; using System.Security; -using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileIdBothDirectoryInfo.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileIdBothDirectoryInfo.cs index 084b7aa59..c4f16051a 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileIdBothDirectoryInfo.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileIdBothDirectoryInfo.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; using System.ComponentModel; @@ -28,6 +27,7 @@ using System.Security; using System.Security.AccessControl; using System.Text; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntries.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntries.cs index ee2444ee6..11df05fb1 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntries.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFileSystemEntries.cs @@ -23,7 +23,6 @@ using System.Collections.Generic; using System.IO; using System.Security; -using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFiles.cs b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFiles.cs index 487198033..af30b9cd0 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFiles.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.EnumerateFiles.cs @@ -23,7 +23,6 @@ using System.Collections.Generic; using System.IO; using System.Security; -using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetChangeTime.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetChangeTime.cs index e7f12258d..182715252 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetChangeTime.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetChangeTime.cs @@ -19,9 +19,9 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.Security; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetDirectories.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetDirectories.cs index cf1301818..15bb04099 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetDirectories.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetDirectories.cs @@ -23,7 +23,6 @@ using System.IO; using System.Linq; using System.Security; -using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntries.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntries.cs index 66dfc7c70..b8509edab 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntries.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetFileSystemEntries.cs @@ -23,7 +23,6 @@ using System.IO; using System.Linq; using System.Security; -using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetFiles.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetFiles.cs index 31fd31578..938430cbf 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetFiles.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetFiles.cs @@ -23,7 +23,6 @@ using System.IO; using System.Linq; using System.Security; -using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Directory Class/Directory.GetLinkTargetInfo.cs b/AlphaFS/Filesystem/Directory Class/Directory.GetLinkTargetInfo.cs index d37811eab..a55dd9b94 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.GetLinkTargetInfo.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.GetLinkTargetInfo.cs @@ -21,7 +21,6 @@ using System; using System.Security; -using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Compression.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Compression.cs index e25ac3a73..1a663191d 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Compression.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.Compression.cs @@ -22,6 +22,7 @@ using System; using System.IO; using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -103,7 +104,7 @@ public void Decompress(DirectoryEnumerationOptions options) [SecurityCritical] public void DisableCompression() { - Device.FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, false, PathFormat.LongFullPath); + FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, false, PathFormat.LongFullPath); } #endregion // DisableCompression @@ -118,7 +119,7 @@ public void DisableCompression() [SecurityCritical] public void EnableCompression() { - Device.FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, true, PathFormat.LongFullPath); + FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, true, PathFormat.LongFullPath); } #endregion // EnableCompression diff --git a/AlphaFS/Filesystem/Exceptions/AlreadyExistsException.cs b/AlphaFS/Filesystem/Exceptions/AlreadyExistsException.cs index 16ffb9fb3..aab6c884b 100644 --- a/AlphaFS/Filesystem/Exceptions/AlreadyExistsException.cs +++ b/AlphaFS/Filesystem/Exceptions/AlreadyExistsException.cs @@ -23,6 +23,7 @@ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using System.IO; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem @@ -31,7 +32,7 @@ namespace Alphaleonis.Win32.Filesystem /// Both ERROR_ALREADY_EXISTS and ERROR_FILE_EXISTS can cause this Exception. /// [Serializable] - public class AlreadyExistsException : System.IO.IOException + public class AlreadyExistsException : IOException { private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_ALREADY_EXISTS); private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_ALREADY_EXISTS, new Win32Exception((int) Win32Errors.ERROR_ALREADY_EXISTS).Message.Trim().TrimEnd('.').Trim()); diff --git a/AlphaFS/Filesystem/Exceptions/DeviceNotReadyException.cs b/AlphaFS/Filesystem/Exceptions/DeviceNotReadyException.cs index 686bb9b52..182468d12 100644 --- a/AlphaFS/Filesystem/Exceptions/DeviceNotReadyException.cs +++ b/AlphaFS/Filesystem/Exceptions/DeviceNotReadyException.cs @@ -23,13 +23,14 @@ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using System.IO; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The requested operation could not be completed because the device is not ready. [Serializable] - public class DeviceNotReadyException : System.IO.IOException + public class DeviceNotReadyException : 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()); diff --git a/AlphaFS/Filesystem/Exceptions/DirectoryNotEmptyException.cs b/AlphaFS/Filesystem/Exceptions/DirectoryNotEmptyException.cs index c94546afa..fdb071840 100644 --- a/AlphaFS/Filesystem/Exceptions/DirectoryNotEmptyException.cs +++ b/AlphaFS/Filesystem/Exceptions/DirectoryNotEmptyException.cs @@ -23,13 +23,14 @@ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using System.IO; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The operation could not be completed because the directory is not empty. [Serializable] - public class DirectoryNotEmptyException : System.IO.IOException + public class DirectoryNotEmptyException : IOException { private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_DIR_NOT_EMPTY); private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_DIR_NOT_EMPTY, new Win32Exception((int) Win32Errors.ERROR_DIR_NOT_EMPTY).Message.Trim().TrimEnd('.').Trim()); diff --git a/AlphaFS/Filesystem/Exceptions/NotAReparsePointException.cs b/AlphaFS/Filesystem/Exceptions/NotAReparsePointException.cs index 18da64069..ef3dac739 100644 --- a/AlphaFS/Filesystem/Exceptions/NotAReparsePointException.cs +++ b/AlphaFS/Filesystem/Exceptions/NotAReparsePointException.cs @@ -22,13 +22,14 @@ using System; using System.ComponentModel; using System.Globalization; +using System.IO; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The file or directory was not a reparse point. [Serializable] - public class NotAReparsePointException : System.IO.IOException + public class NotAReparsePointException : IOException { private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_NOT_A_REPARSE_POINT); private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_NOT_A_REPARSE_POINT, new Win32Exception((int) Win32Errors.ERROR_NOT_A_REPARSE_POINT).Message.Trim().TrimEnd('.').Trim()); diff --git a/AlphaFS/Filesystem/Exceptions/NotSameDeviceException.cs b/AlphaFS/Filesystem/Exceptions/NotSameDeviceException.cs index 3f9aa437f..b96ac4b2e 100644 --- a/AlphaFS/Filesystem/Exceptions/NotSameDeviceException.cs +++ b/AlphaFS/Filesystem/Exceptions/NotSameDeviceException.cs @@ -23,13 +23,14 @@ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using System.IO; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The exception that is thrown when an attempt perform an operation across difference devices when this is not supported. [Serializable] - public class NotSameDeviceException : System.IO.IOException + public class NotSameDeviceException : IOException { private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_NOT_SAME_DEVICE); private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_NOT_SAME_DEVICE, new Win32Exception((int)Win32Errors.ERROR_NOT_SAME_DEVICE).Message.Trim().TrimEnd('.').Trim()); diff --git a/AlphaFS/Filesystem/Exceptions/UnrecognizedReparsePointException.cs b/AlphaFS/Filesystem/Exceptions/UnrecognizedReparsePointException.cs index 04e2ff2b4..7f540d3ed 100644 --- a/AlphaFS/Filesystem/Exceptions/UnrecognizedReparsePointException.cs +++ b/AlphaFS/Filesystem/Exceptions/UnrecognizedReparsePointException.cs @@ -22,13 +22,14 @@ using System; using System.ComponentModel; using System.Globalization; +using System.IO; using System.Runtime.Serialization; namespace Alphaleonis.Win32.Filesystem { /// [AlphaFS] The function attempted to use a name that is reserved for use by another transaction. [Serializable] - public class UnrecognizedReparsePointException : System.IO.IOException + public class UnrecognizedReparsePointException : IOException { private static readonly int ErrorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_INVALID_REPARSE_DATA); private static readonly string ErrorText = string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_INVALID_REPARSE_DATA, new Win32Exception((int) Win32Errors.ERROR_INVALID_REPARSE_DATA).Message.Trim().TrimEnd('.').Trim()); diff --git a/AlphaFS/Filesystem/File Class/File.Compress.cs b/AlphaFS/Filesystem/File Class/File.Compress.cs index 85ecb9ecd..60852da1d 100644 --- a/AlphaFS/Filesystem/File Class/File.Compress.cs +++ b/AlphaFS/Filesystem/File Class/File.Compress.cs @@ -20,6 +20,7 @@ */ using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -30,7 +31,7 @@ public static partial class File [SecurityCritical] public static void Compress(string path) { - Device.FileSystemHelper.ToggleCompressionCore(null, path, true, PathFormat.RelativePath); + FileSystemHelper.ToggleCompressionCore(null, path, true, PathFormat.RelativePath); } @@ -40,7 +41,7 @@ public static void Compress(string path) [SecurityCritical] public static void Compress(string path, PathFormat pathFormat) { - Device.FileSystemHelper.ToggleCompressionCore(null, path, true, pathFormat); + FileSystemHelper.ToggleCompressionCore(null, path, true, pathFormat); } @@ -50,7 +51,7 @@ public static void Compress(string path, PathFormat pathFormat) [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path) { - Device.FileSystemHelper.ToggleCompressionCore(transaction, path, true, PathFormat.RelativePath); + FileSystemHelper.ToggleCompressionCore(transaction, path, true, PathFormat.RelativePath); } @@ -61,7 +62,7 @@ public static void CompressTransacted(KernelTransaction transaction, string path [SecurityCritical] public static void CompressTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { - Device.FileSystemHelper.ToggleCompressionCore(transaction, path, true, pathFormat); + FileSystemHelper.ToggleCompressionCore(transaction, path, true, pathFormat); } } } diff --git a/AlphaFS/Filesystem/File Class/File.Create.cs b/AlphaFS/Filesystem/File Class/File.Create.cs index a3b3a2c33..df1bc4c56 100644 --- a/AlphaFS/Filesystem/File Class/File.Create.cs +++ b/AlphaFS/Filesystem/File Class/File.Create.cs @@ -19,15 +19,14 @@ * 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; -using FileStream = System.IO.FileStream; +using Alphaleonis.Win32.Security; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs b/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs index 5319dea77..f0e1404d7 100644 --- a/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs +++ b/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs @@ -25,7 +25,6 @@ using System.IO; using System.Runtime.InteropServices; using System.Security; -using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.CreateText.cs b/AlphaFS/Filesystem/File Class/File.CreateText.cs index 50542982d..fa7d6eafd 100644 --- a/AlphaFS/Filesystem/File Class/File.CreateText.cs +++ b/AlphaFS/Filesystem/File Class/File.CreateText.cs @@ -23,7 +23,6 @@ using System.IO; using System.Security; using System.Text; -using StreamWriter = System.IO.StreamWriter; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.Decompress.cs b/AlphaFS/Filesystem/File Class/File.Decompress.cs index d6ab13554..04dfd93f7 100644 --- a/AlphaFS/Filesystem/File Class/File.Decompress.cs +++ b/AlphaFS/Filesystem/File Class/File.Decompress.cs @@ -20,6 +20,7 @@ */ using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -30,7 +31,7 @@ public static partial class File [SecurityCritical] public static void Decompress(string path) { - Device.FileSystemHelper.ToggleCompressionCore(null, path, false, PathFormat.RelativePath); + FileSystemHelper.ToggleCompressionCore(null, path, false, PathFormat.RelativePath); } @@ -40,7 +41,7 @@ public static void Decompress(string path) [SecurityCritical] public static void Decompress(string path, PathFormat pathFormat) { - Device.FileSystemHelper.ToggleCompressionCore(null, path, false, pathFormat); + FileSystemHelper.ToggleCompressionCore(null, path, false, pathFormat); } @@ -50,7 +51,7 @@ public static void Decompress(string path, PathFormat pathFormat) [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path) { - Device.FileSystemHelper.ToggleCompressionCore(transaction, path, false, PathFormat.RelativePath); + FileSystemHelper.ToggleCompressionCore(transaction, path, false, PathFormat.RelativePath); } @@ -61,7 +62,7 @@ public static void DecompressTransacted(KernelTransaction transaction, string pa [SecurityCritical] public static void DecompressTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { - Device.FileSystemHelper.ToggleCompressionCore(transaction, path, false, pathFormat); + FileSystemHelper.ToggleCompressionCore(transaction, path, false, pathFormat); } } } diff --git a/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs b/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs index ae7900fcb..adeb59998 100644 --- a/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs +++ b/AlphaFS/Filesystem/File Class/File.GetChangeTime.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; @@ -27,6 +26,7 @@ using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs b/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs index c2699bfd4..914ad6e98 100644 --- a/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs +++ b/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs @@ -20,10 +20,10 @@ */ using System.IO; -using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.GetFileInfoByHandle.cs b/AlphaFS/Filesystem/File Class/File.GetFileInfoByHandle.cs index 9393317d3..bf9767fcc 100644 --- a/AlphaFS/Filesystem/File Class/File.GetFileInfoByHandle.cs +++ b/AlphaFS/Filesystem/File Class/File.GetFileInfoByHandle.cs @@ -20,10 +20,10 @@ */ using System.IO; -using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.GetSize.cs b/AlphaFS/Filesystem/File Class/File.GetSize.cs index 4ce5bdd7c..e34e51ad0 100644 --- a/AlphaFS/Filesystem/File Class/File.GetSize.cs +++ b/AlphaFS/Filesystem/File Class/File.GetSize.cs @@ -20,13 +20,13 @@ */ using System.Collections.ObjectModel; -using Microsoft.Win32.SafeHandles; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.Open.cs b/AlphaFS/Filesystem/File Class/File.Open.cs index d7b84bce4..01d0a30fb 100644 --- a/AlphaFS/Filesystem/File Class/File.Open.cs +++ b/AlphaFS/Filesystem/File Class/File.Open.cs @@ -19,12 +19,11 @@ * 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; -using System.Diagnostics.CodeAnalysis; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.OpenRead.cs b/AlphaFS/Filesystem/File Class/File.OpenRead.cs index a7b3c2527..16391545d 100644 --- a/AlphaFS/Filesystem/File Class/File.OpenRead.cs +++ b/AlphaFS/Filesystem/File Class/File.OpenRead.cs @@ -21,7 +21,6 @@ using System.IO; using System.Security; -using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.ReadAllBytes.cs b/AlphaFS/Filesystem/File Class/File.ReadAllBytes.cs index 351312534..ddfa78cb3 100644 --- a/AlphaFS/Filesystem/File Class/File.ReadAllBytes.cs +++ b/AlphaFS/Filesystem/File Class/File.ReadAllBytes.cs @@ -22,7 +22,6 @@ using System.Globalization; using System.IO; using System.Security; -using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.ReadAllLines.cs b/AlphaFS/Filesystem/File Class/File.ReadAllLines.cs index acdaa3fd4..88860e258 100644 --- a/AlphaFS/Filesystem/File Class/File.ReadAllLines.cs +++ b/AlphaFS/Filesystem/File Class/File.ReadAllLines.cs @@ -25,7 +25,6 @@ using System.Linq; using System.Security; using System.Text; -using StreamReader = System.IO.StreamReader; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.ReadAllText.cs b/AlphaFS/Filesystem/File Class/File.ReadAllText.cs index d9aae97e4..37da74f33 100644 --- a/AlphaFS/Filesystem/File Class/File.ReadAllText.cs +++ b/AlphaFS/Filesystem/File Class/File.ReadAllText.cs @@ -23,7 +23,6 @@ using System.IO; using System.Security; using System.Text; -using StreamReader = System.IO.StreamReader; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.ReadLines.cs b/AlphaFS/Filesystem/File Class/File.ReadLines.cs index 1406a2723..9bfba65b9 100644 --- a/AlphaFS/Filesystem/File Class/File.ReadLines.cs +++ b/AlphaFS/Filesystem/File Class/File.ReadLines.cs @@ -24,7 +24,6 @@ using System.IO; using System.Security; using System.Text; -using StreamReader = System.IO.StreamReader; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/File Class/File.WriteAllBytes.cs b/AlphaFS/Filesystem/File Class/File.WriteAllBytes.cs index d6a9625ef..3a2ca939d 100644 --- a/AlphaFS/Filesystem/File Class/File.WriteAllBytes.cs +++ b/AlphaFS/Filesystem/File Class/File.WriteAllBytes.cs @@ -23,7 +23,6 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; -using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Compress.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Compress.cs index 0b9be20db..dafbb6d63 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Compress.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Compress.cs @@ -20,6 +20,7 @@ */ using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -31,7 +32,7 @@ partial class FileInfo [SecurityCritical] public void Compress() { - Device.FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, true, PathFormat.LongFullPath); + FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, true, PathFormat.LongFullPath); } #endregion // AlphaFS diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Decompress.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Decompress.cs index b387d43e7..b4c5697ff 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Decompress.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Decompress.cs @@ -20,6 +20,7 @@ */ using System.Security; +using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { @@ -31,7 +32,7 @@ partial class FileInfo [SecurityCritical] public void Decompress() { - Device.FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, false, PathFormat.LongFullPath); + FileSystemHelper.ToggleCompressionCore(Transaction, LongFullName, false, PathFormat.LongFullPath); } #endregion // AlphaFS diff --git a/AlphaFS/Filesystem/FileSystemEntryInfo.cs b/AlphaFS/Filesystem/FileSystemEntryInfo.cs index 1772401fc..061ea126b 100644 --- a/AlphaFS/Filesystem/FileSystemEntryInfo.cs +++ b/AlphaFS/Filesystem/FileSystemEntryInfo.cs @@ -22,7 +22,6 @@ using System; using System.IO; using System.Security; -using Alphaleonis.Win32.Device; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs b/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs index 1a72680b7..3514cf0fb 100644 --- a/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs +++ b/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs @@ -28,7 +28,6 @@ using System.Runtime.InteropServices; using System.Security; using System.Text.RegularExpressions; - #if !NET35 using System.Threading; #endif diff --git a/AlphaFS/Filesystem/KernelTransaction.cs b/AlphaFS/Filesystem/KernelTransaction.cs index ca288f41c..264c55743 100644 --- a/AlphaFS/Filesystem/KernelTransaction.cs +++ b/AlphaFS/Filesystem/KernelTransaction.cs @@ -151,7 +151,7 @@ public SafeHandle SafeHandle #region IDisposable Members /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - [SecurityPermissionAttribute(SecurityAction.Demand, UnmanagedCode = true)] + [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] public void Dispose() { _hTrans.Close(); diff --git a/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs b/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs index e5cc7b903..d3259f731 100644 --- a/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs +++ b/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs @@ -19,8 +19,6 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Security; -using Microsoft.Win32.SafeHandles; using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; @@ -29,6 +27,8 @@ using System.Security; using System.Security.AccessControl; using System.Text; +using Alphaleonis.Win32.Security; +using Microsoft.Win32.SafeHandles; using SecurityNativeMethods = Alphaleonis.Win32.Security.NativeMethods; namespace Alphaleonis.Win32.Filesystem diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.BackupStreams.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.BackupStreams.cs index 9ac31d85c..eea7abee6 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.BackupStreams.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.BackupStreams.cs @@ -19,11 +19,11 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs index 1e048819b..7c4076196 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs @@ -18,8 +18,7 @@ * 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.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -28,7 +27,7 @@ using System.Security; using System.Security.AccessControl; using System.Text; -using Alphaleonis.Win32.Device; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { @@ -338,7 +337,7 @@ internal static partial class NativeMethods internal static extern SafeFindFileHandle FindFirstFileTransacted([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FIND_FIRST_EX_FLAGS dwAdditionalFlags, SafeHandle hTransaction); /// - /// Returns an collection of all the hard links to the specified file. The FindFirstFileNameW function returns a handle to the + /// Returns an collection of all the hard links to the specified file. The FindFirstFileNameW function returns a handle to the /// enumeration that can be used on subsequent calls to the FindNextFileNameW function. /// /// Minimum supported client: Windows Vista [desktop apps only]. diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.Handles.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.Handles.cs index 2ec5a6cf2..4814c5a63 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.Handles.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.Handles.cs @@ -18,6 +18,7 @@ * 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; diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.KernelTransactions.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.KernelTransactions.cs index 74e935537..87cfff112 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.KernelTransactions.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.KernelTransactions.cs @@ -18,6 +18,7 @@ * 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; diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.PathManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.PathManagement.cs index 38e1889a3..0449649c5 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.PathManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.PathManagement.cs @@ -18,6 +18,7 @@ * 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; diff --git a/AlphaFS/Filesystem/Native Other/FILE_INFO_BY_HANDLE_CLASS.cs b/AlphaFS/Filesystem/Native Other/FILE_INFO_BY_HANDLE_CLASS.cs index f6dd82139..3e61bc103 100644 --- a/AlphaFS/Filesystem/Native Other/FILE_INFO_BY_HANDLE_CLASS.cs +++ b/AlphaFS/Filesystem/Native Other/FILE_INFO_BY_HANDLE_CLASS.cs @@ -132,7 +132,7 @@ internal enum FILE_INFO_BY_HANDLE_CLASS /// This value is not supported before Windows 8 and Windows Server 2012 /// /// - FILE_ID_INFO = 18, + FILE_ID_INFO = 18 ///// Files in the specified directory should be retrieved. Used for directory handles. Use only when calling GetFileInformationByHandleEx. diff --git a/AlphaFS/Filesystem/Native Other/LinkTargetInfo.cs b/AlphaFS/Filesystem/Native Other/LinkTargetInfo.cs index a7d9a7a98..d822ca82e 100644 --- a/AlphaFS/Filesystem/Native Other/LinkTargetInfo.cs +++ b/AlphaFS/Filesystem/Native Other/LinkTargetInfo.cs @@ -19,8 +19,6 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Filesystem; - namespace Alphaleonis.Win32.Filesystem { /// Information about the target of a symbolic link or mount point. diff --git a/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs b/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs index c805255f2..5da137b66 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -27,6 +26,7 @@ using System.Runtime.InteropServices; using System.Security; using System.Text; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Path Class/Path.LocalToUnc.cs b/AlphaFS/Filesystem/Path Class/Path.LocalToUnc.cs index 802d0e6d8..607154ff7 100644 --- a/AlphaFS/Filesystem/Path Class/Path.LocalToUnc.cs +++ b/AlphaFS/Filesystem/Path Class/Path.LocalToUnc.cs @@ -19,12 +19,12 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Network; using System; using System.Globalization; using System.IO; using System.Net.NetworkInformation; using System.Security; +using Alphaleonis.Win32.Network; namespace Alphaleonis.Win32.Filesystem { diff --git a/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs b/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs index 717256bd4..971e60757 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/DirectoryEnumerationFilters.cs @@ -20,7 +20,6 @@ */ using System; - #if !NET35 using System.Threading; #endif diff --git a/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs b/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs index 2092b7f35..ccd895574 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs @@ -185,13 +185,13 @@ public override string ToString() 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), + ((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)); + ((uint) (_fileIdLowPart >> 32)).ToString("X", CultureInfo.InvariantCulture), + ((uint) _fileIdLowPart).ToString("X", CultureInfo.InvariantCulture)); } } } diff --git a/AlphaFS/GlobalSuppressions.cs b/AlphaFS/GlobalSuppressions.cs index 080cfa0d3..d09e715ae 100644 --- a/AlphaFS/GlobalSuppressions.cs +++ b/AlphaFS/GlobalSuppressions.cs @@ -27,22 +27,25 @@ // Error List, point to "Suppress Message(s)", and click // "In Project Suppression File". // You do not need to add suppressions to this file manually. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Alphaleonis", Scope = "namespace", Target = "Alphaleonis.Win32.Network")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Alphaleonis", Scope = "namespace", Target = "Alphaleonis.Win32.Security")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Alphaleonis.Win32.Security")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Filesystem", Scope = "namespace", Target = "Alphaleonis.Win32.Filesystem")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Alphaleonis", Scope = "namespace", Target = "Alphaleonis.Win32.Filesystem")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.AlreadyExistsException.#.cctor()")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.DirectoryNotEmptyException.#.cctor()")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.DirectoryReadOnlyException.#.cctor()")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.FileReadOnlyException.#.cctor()")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.NotAReparsePointException.#.cctor()")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.DeviceNotReadyException.#.cctor()")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.UnrecognizedReparsePointException.#.cctor()")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.NotSameDeviceException.#.cctor()")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "Dir", Scope = "resource", Target = "Alphaleonis.Win32.Resources.resources")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Filesystem.NativeMethods+PARTITION_INFORMATION_GPT")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Filesystem.NativeMethods+PARTITION_INFORMATION_EX")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Alphaleonis", Scope = "namespace", Target = "Alphaleonis.Win32.Device")] +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Alphaleonis", Scope = "namespace", Target = "Alphaleonis.Win32.Network")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Alphaleonis", Scope = "namespace", Target = "Alphaleonis.Win32.Security")] +[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Alphaleonis.Win32.Security")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Filesystem", Scope = "namespace", Target = "Alphaleonis.Win32.Filesystem")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Alphaleonis", Scope = "namespace", Target = "Alphaleonis.Win32.Filesystem")] +[assembly: SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.AlreadyExistsException.#.cctor()")] +[assembly: SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.DirectoryNotEmptyException.#.cctor()")] +[assembly: SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.DirectoryReadOnlyException.#.cctor()")] +[assembly: SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.FileReadOnlyException.#.cctor()")] +[assembly: SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.NotAReparsePointException.#.cctor()")] +[assembly: SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.DeviceNotReadyException.#.cctor()")] +[assembly: SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.UnrecognizedReparsePointException.#.cctor()")] +[assembly: SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.NotSameDeviceException.#.cctor()")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "Dir", Scope = "resource", Target = "Alphaleonis.Win32.Resources.resources")] + +[assembly: SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Filesystem.NativeMethods+PARTITION_INFORMATION_GPT")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Filesystem.NativeMethods+PARTITION_INFORMATION_EX")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Alphaleonis", Scope = "namespace", Target = "Alphaleonis.Win32.Device")] diff --git a/AlphaFS/NativeError.cs b/AlphaFS/NativeError.cs index b5913957c..592809e72 100644 --- a/AlphaFS/NativeError.cs +++ b/AlphaFS/NativeError.cs @@ -23,9 +23,11 @@ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using System.IO; using System.Runtime.InteropServices; using System.Security.Policy; using Alphaleonis.Win32.Filesystem; +using Path = Alphaleonis.Win32.Filesystem.Path; namespace Alphaleonis.Win32 { @@ -87,7 +89,7 @@ public static void ThrowException(uint errorCode, string readPath, string writeP switch (errorCode) { case Win32Errors.ERROR_INVALID_DRIVE: - throw new System.IO.DriveNotFoundException(errorMessage); + throw new DriveNotFoundException(errorMessage); case Win32Errors.ERROR_OPERATION_ABORTED: @@ -95,11 +97,11 @@ public static void ThrowException(uint errorCode, string readPath, string writeP case Win32Errors.ERROR_FILE_NOT_FOUND: - throw new System.IO.FileNotFoundException(errorMessage); + throw new FileNotFoundException(errorMessage); case Win32Errors.ERROR_PATH_NOT_FOUND: - throw new System.IO.DirectoryNotFoundException(errorMessage); + throw new DirectoryNotFoundException(errorMessage); case Win32Errors.ERROR_BAD_RECOVERY_POLICY: @@ -167,7 +169,7 @@ public static void ThrowException(uint errorCode, string readPath, string writeP default: // We don't have a specific exception to generate for this error. - throw new System.IO.IOException(errorMessage, Win32Errors.GetHrFromWin32Error(errorCode)); + throw new IOException(errorMessage, Win32Errors.GetHrFromWin32Error(errorCode)); } } } diff --git a/AlphaFS/Network/DfsInfo.cs b/AlphaFS/Network/DfsInfo.cs index 572235a24..da0f6289b 100644 --- a/AlphaFS/Network/DfsInfo.cs +++ b/AlphaFS/Network/DfsInfo.cs @@ -19,11 +19,11 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Filesystem; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; +using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network { diff --git a/AlphaFS/Network/Host Class/Host.GetUncName.cs b/AlphaFS/Network/Host Class/Host.GetUncName.cs index a0f41b17c..425e3c9ce 100644 --- a/AlphaFS/Network/Host Class/Host.GetUncName.cs +++ b/AlphaFS/Network/Host Class/Host.GetUncName.cs @@ -23,7 +23,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; -using Path = Alphaleonis.Win32.Filesystem.Path; +using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network { diff --git a/AlphaFS/Network/Host Class/Host.SMB.EnumerateDrives.cs b/AlphaFS/Network/Host Class/Host.SMB.EnumerateDrives.cs index 944fdfec5..fabe1a205 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.EnumerateDrives.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.EnumerateDrives.cs @@ -19,13 +19,13 @@ * 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; +using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network { diff --git a/AlphaFS/Network/Host Class/Host.SMB.GetHostShareFromPath.cs b/AlphaFS/Network/Host Class/Host.SMB.GetHostShareFromPath.cs index cda42d177..809b2595b 100644 --- a/AlphaFS/Network/Host Class/Host.SMB.GetHostShareFromPath.cs +++ b/AlphaFS/Network/Host Class/Host.SMB.GetHostShareFromPath.cs @@ -19,10 +19,10 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Filesystem; using System; using System.Diagnostics.CodeAnalysis; using System.Security; +using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network { diff --git a/AlphaFS/Network/Host Class/Host.cs b/AlphaFS/Network/Host Class/Host.cs index 40b13cbca..161cb6994 100644 --- a/AlphaFS/Network/Host Class/Host.cs +++ b/AlphaFS/Network/Host Class/Host.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Filesystem; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -30,6 +29,7 @@ using System.Runtime.InteropServices; using System.Security; using System.Text; +using Alphaleonis.Win32.Filesystem; using Path = Alphaleonis.Win32.Filesystem.Path; namespace Alphaleonis.Win32.Network diff --git a/AlphaFS/Network/OpenConnectionInfo.cs b/AlphaFS/Network/OpenConnectionInfo.cs index cd077737f..8347fcff0 100644 --- a/AlphaFS/Network/OpenConnectionInfo.cs +++ b/AlphaFS/Network/OpenConnectionInfo.cs @@ -41,13 +41,11 @@ public sealed class OpenConnectionInfo /// Create an OpenConnectionInfo instance. internal OpenConnectionInfo(string hostName, NativeMethods.CONNECTION_INFO_1 connectionInfo) { - Host = hostName; HostName = hostName; Id = connectionInfo.coni1_id; ShareType = connectionInfo.coni1_type; TotalOpenFiles = connectionInfo.coni1_num_opens; TotalUsers = connectionInfo.coni1_num_users; - ConnectedSeconds = connectionInfo.coni1_time; ConnectedTime = TimeSpan.FromSeconds(connectionInfo.coni1_time); UserName = connectionInfo.coni1_username; NetName = connectionInfo.oni1_netname; @@ -72,7 +70,10 @@ public override string ToString() /// The local or remote Host. [Obsolete("Use HostName")] - public string Host { get; private set; } + public string Host + { + get { return HostName; } + } /// The host name of this connection information. public string HostName { get; private set; } @@ -91,7 +92,10 @@ public override string ToString() /// Specifies the number of seconds that the connection has been established. [Obsolete("Use ConnectedTime property.")] - public long ConnectedSeconds { get; private set; } + public long ConnectedSeconds + { + get { return ConnectedTime.Seconds; } + } /// Specifies duration that the connection has been established. public TimeSpan ConnectedTime { get; private set; } diff --git a/AlphaFS/Network/OpenResourceInfo.cs b/AlphaFS/Network/OpenResourceInfo.cs index 2f0f41c2e..dec2f1e42 100644 --- a/AlphaFS/Network/OpenResourceInfo.cs +++ b/AlphaFS/Network/OpenResourceInfo.cs @@ -34,7 +34,6 @@ public sealed class OpenResourceInfo /// Create an OpenResourceInfo instance. internal OpenResourceInfo(string hostName, NativeMethods.FILE_INFO_3 fileInfo) { - Host = hostName; HostName = hostName; Id = fileInfo.fi3_id; Permissions = fileInfo.fi3_permissions; @@ -73,7 +72,10 @@ public override string ToString() /// The local or remote Host. [Obsolete("Use HostName")] - public string Host { get; private set; } + public string Host + { + get { return HostName; } + } /// The host name of this resource information. public string HostName { get; private set; } diff --git a/AlphaFS/Network/ShareInfo.cs b/AlphaFS/Network/ShareInfo.cs index 72291a392..91bd2f27f 100644 --- a/AlphaFS/Network/ShareInfo.cs +++ b/AlphaFS/Network/ShareInfo.cs @@ -19,9 +19,9 @@ * THE SOFTWARE. */ -using Alphaleonis.Win32.Filesystem; using System; using System.Globalization; +using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Network { diff --git a/AlphaFS/Safe Handles/SafeFindFileHandle.cs b/AlphaFS/Safe Handles/SafeFindFileHandle.cs index 1890b9c98..3d75bcafe 100644 --- a/AlphaFS/Safe Handles/SafeFindFileHandle.cs +++ b/AlphaFS/Safe Handles/SafeFindFileHandle.cs @@ -28,7 +28,7 @@ namespace Alphaleonis.Win32 { /// Represents a wrapper class for a handle used by the FindFirstFile/FindNextFile Win32 API functions. [SecurityCritical] - public sealed class SafeFindFileHandle : SafeHandleZeroOrMinusOneIsInvalid + internal sealed class SafeFindFileHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Constructor that prevents a default instance of this class from being created. private SafeFindFileHandle() : base(true) diff --git a/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs b/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs index 616bd7715..526466dc5 100644 --- a/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs +++ b/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs @@ -21,14 +21,14 @@ using System; using System.Security; -using Alphaleonis.Win32.Filesystem; +using Alphaleonis.Win32.Device; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32 { /// Represents a wrapper class for a handle used by the FindFirstVolume/FindNextVolume methods of the Win32 API. [SecurityCritical] - public sealed class SafeFindVolumeHandle : SafeHandleZeroOrMinusOneIsInvalid + internal sealed class SafeFindVolumeHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Constructor that prevents a default instance of this class from being created. private SafeFindVolumeHandle() : base(true) @@ -51,7 +51,7 @@ public SafeFindVolumeHandle(IntPtr handle, bool callerHandle) : base(callerHandl /// protected override bool ReleaseHandle() { - return Device.NativeMethods.FindVolumeClose(handle); + return NativeMethods.FindVolumeClose(handle); } } } diff --git a/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs b/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs index 13e15b166..4c03efa79 100644 --- a/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs +++ b/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs @@ -21,7 +21,7 @@ using System; using System.Security; -using Alphaleonis.Win32.Filesystem; +using Alphaleonis.Win32.Device; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32 @@ -52,7 +52,7 @@ public SafeFindVolumeMountPointHandle(IntPtr handle, bool callerHandle) : base(c /// protected override bool ReleaseHandle() { - return Device.NativeMethods.FindVolumeMountPointClose(handle); + return NativeMethods.FindVolumeMountPointClose(handle); } } } diff --git a/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs b/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs index ab892d2e8..2dc00701d 100644 --- a/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs +++ b/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs @@ -19,9 +19,9 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System.Security; using Alphaleonis.Win32.Filesystem; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32 { diff --git a/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs b/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs index b42d04141..74b620a91 100644 --- a/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs +++ b/AlphaFS/Safe Handles/SafeNativeMemoryBufferHandle.cs @@ -19,9 +19,9 @@ * THE SOFTWARE. */ -using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32 { diff --git a/AlphaFS/Security/Native Other/TOKEN_ELEVATION_TYPE.cs b/AlphaFS/Security/Native Other/TOKEN_ELEVATION_TYPE.cs index ddd62756e..b28356ba0 100644 --- a/AlphaFS/Security/Native Other/TOKEN_ELEVATION_TYPE.cs +++ b/AlphaFS/Security/Native Other/TOKEN_ELEVATION_TYPE.cs @@ -34,7 +34,7 @@ internal enum TOKEN_ELEVATION_TYPE //TokenElevationTypeDefault = 1, /// The token is an elevated token: UAC is enabled and User is elevated. - TokenElevationTypeFull = 2, + TokenElevationTypeFull = 2 ///// The token is a limited token: UAC is enabled but User is not elevated. //TokenElevationTypeLimited = 3 diff --git a/AlphaFS/Security/Native Other/TOKEN_INFORMATION_CLASS.cs b/AlphaFS/Security/Native Other/TOKEN_INFORMATION_CLASS.cs index 7ba196962..2efa4082d 100644 --- a/AlphaFS/Security/Native Other/TOKEN_INFORMATION_CLASS.cs +++ b/AlphaFS/Security/Native Other/TOKEN_INFORMATION_CLASS.cs @@ -85,7 +85,7 @@ internal enum TOKEN_INFORMATION_CLASS //TokenOrigin = 17, /// The buffer receives a TOKEN_ELEVATION_TYPE value that specifies the elevation level of the token. - TokenElevationType = 18, + TokenElevationType = 18 ///// The buffer receives a TOKEN_LINKED_TOKEN structure that contains a handle to another token that is linked to this token. //TokenLinkedToken = 19, diff --git a/AlphaFS/Utils.cs b/AlphaFS/Utils.cs index 89887612f..6ab9acbb5 100644 --- a/AlphaFS/Utils.cs +++ b/AlphaFS/Utils.cs @@ -28,6 +28,7 @@ using System.Runtime.InteropServices; using System.Security; using Alphaleonis.Win32; +using Alphaleonis.Win32.Device; using Alphaleonis.Win32.Security; using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; @@ -56,7 +57,7 @@ internal static int GetDoubledBufferSizeOrThrowException(SafeHandle safeBuffer, default: - IsValidHandle(safeBuffer, lastError, String.Format(CultureInfo.InvariantCulture, "Buffer size: {0}. Path: {1}", bufferSize.ToString(CultureInfo.InvariantCulture), pathForException)); + IsValidHandle(safeBuffer, lastError, string.Format(CultureInfo.InvariantCulture, "Buffer size: {0}. Path: {1}", bufferSize.ToString(CultureInfo.InvariantCulture), pathForException)); break; } @@ -67,9 +68,9 @@ internal static int GetDoubledBufferSizeOrThrowException(SafeHandle safeBuffer, /// Gets an attribute on an enum field value. /// The description belonging to the enum option, as a string - /// One of the enum types. + /// One of the enum types. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public static string GetEnumDescription(Enum enumValue) + internal static string GetEnumDescription(Enum enumValue) { var enumValueString = enumValue.ToString(); @@ -82,7 +83,7 @@ public static string GetEnumDescription(Enum enumValue) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - public static T[] EnumToArray() + internal static T[] EnumToArray() { var enumType = typeof(T); @@ -101,7 +102,7 @@ public static T[] EnumToArray() /// Checks that the object is not null. - public static bool IsNotNull(T obj) + internal static bool IsNotNull(T obj) { return !Equals(null, obj); } @@ -110,7 +111,7 @@ public static bool IsNotNull(T obj) /// Indicates whether a specified string is null, empty, or consists only of white-space characters. /// true if the parameter is null or , or if consists exclusively of white-space characters. /// The string to test. - public static bool IsNullOrWhiteSpace(string value) + internal static bool IsNullOrWhiteSpace(string value) { #if NET35 if (null != value) @@ -163,7 +164,7 @@ internal static bool IsValidHandle(SafeHandle handle, int lastError, bool throwE handle.Close(); if (throwException) - throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, Resources.Handle_Is_Invalid_Win32Error, lastError.ToString(CultureInfo.InvariantCulture)), "handle"); + throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Handle_Is_Invalid_Win32Error, lastError.ToString(CultureInfo.InvariantCulture)), "handle"); return false; } @@ -198,7 +199,7 @@ internal static bool IsValidHandle(SafeHandle handle, int lastError, string path /// Converts a number of type T to string formated using , suffixed with a unit size. - public static string UnitSizeToText(T numberOfBytes) + internal static string UnitSizeToText(T numberOfBytes) { // CultureInfo.CurrentCulture uses the culture as set in the Region applet. @@ -207,7 +208,7 @@ public static string UnitSizeToText(T numberOfBytes) /// Converts a number of type T to string formated using the specified , suffixed with a unit size. - public static string UnitSizeToText(T numberOfBytes, CultureInfo cultureInfo) + internal static string UnitSizeToText(T numberOfBytes, CultureInfo cultureInfo) { var sizeFormats = new[] {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}; const int kb = 1024; @@ -232,37 +233,37 @@ public static string UnitSizeToText(T numberOfBytes, CultureInfo cultureInfo) } - public static int CombineHashCodesOf(T1 arg1, T2 arg2) - { - unchecked - { - var hash = 17; + //internal static int CombineHashCodesOf(T1 arg1, T2 arg2) + //{ + // unchecked + // { + // var hash = 17; - hash = hash * 23 + (null != arg1 ? arg1.GetHashCode() : 0); - hash = hash * 23 + (null != arg2 ? arg2.GetHashCode() : 0); + // hash = hash * 23 + (null != arg1 ? arg1.GetHashCode() : 0); + // hash = hash * 23 + (null != arg2 ? arg2.GetHashCode() : 0); - return hash; - } - } + // return hash; + // } + //} - public static int CombineHashCodesOf(T1 arg1, T2 arg2, T3 arg3) - { - unchecked - { - var hash = CombineHashCodesOf(arg1, arg2); + //internal static int CombineHashCodesOf(T1 arg1, T2 arg2, T3 arg3) + //{ + // unchecked + // { + // var hash = CombineHashCodesOf(arg1, arg2); - hash = hash * 23 + (null != arg3 ? arg3.GetHashCode() : 0); + // hash = hash * 23 + (null != arg3 ? arg3.GetHashCode() : 0); - return hash; - } - } + // return hash; + // } + //} - public static int CombineHashCodesOf(T1 arg1, T2 arg2, T3 arg3, T4 arg4) - { - return CombineHashCodesOf(CombineHashCodesOf(arg1, arg2), CombineHashCodesOf(arg3, arg4)); - } + //internal static int CombineHashCodesOf(T1 arg1, T2 arg2, T3 arg3, T4 arg4) + //{ + // return CombineHashCodesOf(CombineHashCodesOf(arg1, arg2), CombineHashCodesOf(arg3, arg4)); + //} #region Bitmasking From 15b9ba3c94a8c58dd6bdddddadcd42f08c4216c4 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 8 Jun 2018 10:40:58 +0200 Subject: [PATCH 089/133] -Restored SafeHandles namespaces; -Split OperatingSystem class; --- AlphaFS/AlphaFS.csproj | 6 +- .../NativeMethods.VolumeManagement.cs | 1 + .../NativeMethods.FileManagement.cs | 1 + AlphaFS/OperatingSystem/EnumOsName.cs | 81 +++++++ .../EnumProcessorArchitecture.cs | 57 +++++ AlphaFS/OperatingSystem/IsAtLeast.cs | 45 ++++ .../NativeMethods.OperatingSystem.cs | 107 +++++++++ .../{ => OperatingSystem}/OperatingSystem.cs | 222 ++---------------- .../SafeEncryptedFileRawHandle.cs | 3 +- AlphaFS/Safe Handles/SafeFindFileHandle.cs | 5 +- AlphaFS/Safe Handles/SafeFindVolumeHandle.cs | 7 +- .../SafeFindVolumeMountPointHandle.cs | 5 +- .../SafeKernelTransactionHandle.cs | 3 +- .../SafeLocalMemoryBufferHandle.cs | 3 +- 14 files changed, 327 insertions(+), 219 deletions(-) create mode 100644 AlphaFS/OperatingSystem/EnumOsName.cs create mode 100644 AlphaFS/OperatingSystem/EnumProcessorArchitecture.cs create mode 100644 AlphaFS/OperatingSystem/IsAtLeast.cs create mode 100644 AlphaFS/OperatingSystem/NativeMethods.OperatingSystem.cs rename AlphaFS/{ => OperatingSystem}/OperatingSystem.cs (53%) diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 8fa1a6540..c69d19033 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -549,6 +549,10 @@ + + + + @@ -642,7 +646,7 @@ - + True diff --git a/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs b/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs index 86870c4d0..257823df0 100644 --- a/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs @@ -25,6 +25,7 @@ using System.Runtime.InteropServices; using System.Security; using System.Text; +using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs index 7c4076196..86646078b 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs @@ -27,6 +27,7 @@ using System.Security; using System.Security.AccessControl; using System.Text; +using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Filesystem diff --git a/AlphaFS/OperatingSystem/EnumOsName.cs b/AlphaFS/OperatingSystem/EnumOsName.cs new file mode 100644 index 000000000..f39a3354c --- /dev/null +++ b/AlphaFS/OperatingSystem/EnumOsName.cs @@ -0,0 +1,81 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// [AlphaFS] Static class providing access to information about the operating system under which the assembly is executing. + public static partial class OperatingSystem + { + /// [AlphaFS] A set of flags that describe the named Windows versions. + /// The values of the enumeration are ordered. A later released operating system version has a higher number, so comparisons between named versions are meaningful. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] + public enum EnumOsName + { + /// A Windows version earlier than Windows 2000. + Earlier = -1, + + /// Windows 2000 (Server or Professional). + Windows2000 = 0, + + /// Windows XP. + WindowsXP = 1, + + /// Windows Server 2003. + WindowsServer2003 = 2, + + /// Windows Vista. + WindowsVista = 3, + + /// Windows Server 2008. + WindowsServer2008 = 4, + + /// Windows 7. + Windows7 = 5, + + /// Windows Server 2008 R2. + WindowsServer2008R2 = 6, + + /// Windows 8. + Windows8 = 7, + + /// Windows Server 2012. + WindowsServer2012 = 8, + + /// Windows 8.1. + Windows81 = 9, + + /// Windows Server 2012 R2 + WindowsServer2012R2 = 10, + + /// Windows 10 + Windows10 = 11, + + /// Windows Server 2016 + WindowsServer2016 = 12, + + /// A later version of Windows than currently installed. + Later = 65535 + } + } +} diff --git a/AlphaFS/OperatingSystem/EnumProcessorArchitecture.cs b/AlphaFS/OperatingSystem/EnumProcessorArchitecture.cs new file mode 100644 index 000000000..e90612db6 --- /dev/null +++ b/AlphaFS/OperatingSystem/EnumProcessorArchitecture.cs @@ -0,0 +1,57 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// [AlphaFS] Static class providing access to information about the operating system under which the assembly is executing. + public static partial class OperatingSystem + { + /// [AlphaFS] A set of flags to indicate the current processor architecture for which the operating system is targeted and running. + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pa")] + [SuppressMessage("Microsoft.Design", "CA1028:EnumStorageShouldBeInt32")] + public enum EnumProcessorArchitecture + { + /// PROCESSOR_ARCHITECTURE_INTEL + /// The system is running a 32-bit version of Windows. + /// + X86 = 0, + + /// PROCESSOR_ARCHITECTURE_IA64 + /// The system is running on a Itanium processor. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] + [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] + IA64 = 6, + + /// PROCESSOR_ARCHITECTURE_AMD64 + /// The system is running a 64-bit version of Windows. + /// + X64 = 9, + + /// PROCESSOR_ARCHITECTURE_UNKNOWN + /// Unknown architecture. + /// + Unknown = 65535 + } + } +} diff --git a/AlphaFS/OperatingSystem/IsAtLeast.cs b/AlphaFS/OperatingSystem/IsAtLeast.cs new file mode 100644 index 000000000..14f0ac382 --- /dev/null +++ b/AlphaFS/OperatingSystem/IsAtLeast.cs @@ -0,0 +1,45 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// [AlphaFS] Static class providing access to information about the operating system under which the assembly is executing. + public static partial class OperatingSystem + { + /// [AlphaFS] Determines whether the operating system is of the specified version or later. + /// true if the operating system is of the specified or later; otherwise, false. + /// The lowest version for which to return true. + public static bool IsAtLeast(EnumOsName version) + { + return VersionName >= version; + } + + + /// [AlphaFS] Determines whether the operating system is of the specified version or later, allowing specification of a minimum service pack that must be installed on the lowest version. + /// true if the operating system matches the specified with the specified service pack, or if the operating system is of a later version; otherwise, false. + /// The minimum required version. + /// The major version of the service pack that must be installed on the minimum required version to return true. This can be 0 to indicate that no service pack is required. + public static bool IsAtLeast(EnumOsName version, int servicePackVersion) + { + return IsAtLeast(version) && ServicePackVersion.Major >= servicePackVersion; + } + } +} diff --git a/AlphaFS/OperatingSystem/NativeMethods.OperatingSystem.cs b/AlphaFS/OperatingSystem/NativeMethods.OperatingSystem.cs new file mode 100644 index 000000000..04214dc4e --- /dev/null +++ b/AlphaFS/OperatingSystem/NativeMethods.OperatingSystem.cs @@ -0,0 +1,107 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 +{ + /// [AlphaFS] Static class providing access to information about the operating system under which the assembly is executing. + public static partial class OperatingSystem + { + private static class NativeMethods + { + internal const short VER_NT_WORKSTATION = 1; + internal const short VER_NT_DOMAIN_CONTROLLER = 2; + internal const short VER_NT_SERVER = 3; + + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct RTL_OSVERSIONINFOEXW + { + public int dwOSVersionInfoSize; + public readonly int dwMajorVersion; + public readonly int dwMinorVersion; + public readonly int dwBuildNumber; + public readonly int dwPlatformId; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] + public readonly string szCSDVersion; + public readonly ushort wServicePackMajor; + public readonly ushort wServicePackMinor; + public readonly ushort wSuiteMask; + public readonly byte wProductType; + public readonly byte wReserved; + } + + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct SYSTEM_INFO + { + public readonly EnumProcessorArchitecture wProcessorArchitecture; + public readonly ushort wReserved; + public readonly uint dwPageSize; + public readonly IntPtr lpMinimumApplicationAddress; + public readonly IntPtr lpMaximumApplicationAddress; + public readonly IntPtr dwActiveProcessorMask; + public readonly uint dwNumberOfProcessors; + public readonly uint dwProcessorType; + public readonly uint dwAllocationGranularity; + public readonly ushort wProcessorLevel; + public readonly ushort wProcessorRevision; + } + + + /// The RtlGetVersion routine returns version information about the currently running operating system. + /// RtlGetVersion returns STATUS_SUCCESS. + /// Available starting with Windows 2000. + [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule"), DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool RtlGetVersion([MarshalAs(UnmanagedType.Struct)] ref RTL_OSVERSIONINFOEXW lpVersionInformation); + + + /// Retrieves information about the current system to an application running under WOW64. + /// If the function is called from a 64-bit application, it is equivalent to the GetSystemInfo function. + /// + /// This function does not return a value. + /// To determine whether a Win32-based application is running under WOW64, call the function. + /// Minimum supported client: Windows XP [desktop apps | Windows Store apps] + /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps] + [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] + internal static extern void GetNativeSystemInfo([MarshalAs(UnmanagedType.Struct)] ref SYSTEM_INFO lpSystemInfo); + + + /// Determines whether the specified process is running under WOW64. + /// + /// If the function succeeds, the return value is a nonzero value. + /// If the function fails, the return value is zero. To get extended error information, call GetLastError. + /// + /// Minimum supported client: Windows Vista, Windows XP with SP2 [desktop apps only] + /// Minimum supported server: Windows Server 2008, Windows Server 2003 with SP1 [desktop apps only] + [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 IsWow64Process([In] IntPtr hProcess, [Out, MarshalAs(UnmanagedType.Bool)] out bool lpSystemInfo); + } + } +} diff --git a/AlphaFS/OperatingSystem.cs b/AlphaFS/OperatingSystem/OperatingSystem.cs similarity index 53% rename from AlphaFS/OperatingSystem.cs rename to AlphaFS/OperatingSystem/OperatingSystem.cs index 958bb9a91..d4e6470a1 100644 --- a/AlphaFS/OperatingSystem.cs +++ b/AlphaFS/OperatingSystem/OperatingSystem.cs @@ -24,101 +24,27 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; -using System.Security; namespace Alphaleonis.Win32 { - /// Static class providing access to information about the operating system under which the assembly is executing. - public static class OperatingSystem + /// [AlphaFS] Static class providing access to information about the operating system under which the assembly is executing. + public static partial class OperatingSystem { - /// A set of flags that describe the named Windows versions. - /// The values of the enumeration are ordered. A later released operating system version has a higher number, so comparisons between named versions are meaningful. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] - public enum EnumOsName - { - /// A Windows version earlier than Windows 2000. - Earlier = -1, - - /// Windows 2000 (Server or Professional). - Windows2000 = 0, - - /// Windows XP. - WindowsXP = 1, - - /// Windows Server 2003. - WindowsServer2003 = 2, - - /// Windows Vista. - WindowsVista = 3, - - /// Windows Server 2008. - WindowsServer2008 = 4, - - /// Windows 7. - Windows7 = 5, - - /// Windows Server 2008 R2. - WindowsServer2008R2 = 6, - - /// Windows 8. - Windows8 = 7, - - /// Windows Server 2012. - WindowsServer2012 = 8, - - /// Windows 8.1. - Windows81 = 9, - - /// Windows Server 2012 R2 - WindowsServer2012R2 = 10, - - /// Windows 10 - Windows10 = 11, - - /// Windows Server 2016 - WindowsServer2016 = 12, - - /// A later version of Windows than currently installed. - Later = 65535 - } + #region Private Fields + private static bool _isServer; + private static bool? _isWow64Process; + private static Version _osVersion; + private static EnumOsName _enumOsName = EnumOsName.Later; + private static EnumProcessorArchitecture _processorArchitecture; + private static Version _servicePackVersion; - /// A set of flags to indicate the current processor architecture for which the operating system is targeted and running. - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pa")] - [SuppressMessage("Microsoft.Design", "CA1028:EnumStorageShouldBeInt32")] - public enum EnumProcessorArchitecture - { - /// PROCESSOR_ARCHITECTURE_INTEL - /// The system is running a 32-bit version of Windows. - /// - X86 = 0, - - /// PROCESSOR_ARCHITECTURE_IA64 - /// The system is running on a Itanium processor. - /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] - IA64 = 6, - - /// PROCESSOR_ARCHITECTURE_AMD64 - /// The system is running a 64-bit version of Windows. - /// - X64 = 9, - - /// PROCESSOR_ARCHITECTURE_UNKNOWN - /// Unknown architecture. - /// - Unknown = 65535 - } + #endregion // Private Fields - - #region Properties - private static bool _isServer; - /// Gets a value indicating whether the operating system is a server operating system. + /// [AlphaFS] Gets a value indicating whether the operating system is a server operating system. /// true if the current operating system is a server operating system; otherwise, false. public static bool IsServer { @@ -131,9 +57,8 @@ public static bool IsServer } } - - private static bool? _isWow64Process; - /// Gets a value indicating whether the current process is running under WOW64. + + /// [AlphaFS] Gets a value indicating whether the current process is running under WOW64. /// true if the current process is running under WOW64; otherwise, false. public static bool IsWow64Process { @@ -159,8 +84,7 @@ public static bool IsWow64Process } - private static Version _osVersion; - /// Gets the numeric version of the operating system. + /// [AlphaFS] Gets the numeric version of the operating system. /// The numeric version of the operating system. public static Version OSVersion { @@ -173,9 +97,8 @@ public static Version OSVersion } } - - private static EnumOsName _enumOsName = EnumOsName.Later; - /// Gets the named version of the operating system. + + /// [AlphaFS] Gets the named version of the operating system. /// The named version of the operating system. public static EnumOsName VersionName { @@ -188,9 +111,8 @@ public static EnumOsName VersionName } } - - private static EnumProcessorArchitecture _processorArchitecture; - /// Gets the processor architecture for which the operating system is targeted. + + /// [AlphaFS] Gets the processor architecture for which the operating system is targeted. /// The processor architecture for which the operating system is targeted. /// If running under WOW64 this will return a 32-bit processor. Use to determine if this is the case. public static EnumProcessorArchitecture ProcessorArchitecture @@ -204,9 +126,8 @@ public static EnumProcessorArchitecture ProcessorArchitecture } } - - private static Version _servicePackVersion; - /// Gets the version of the service pack currently installed on the operating system. + + /// [AlphaFS] Gets the version of the service pack currently installed on the operating system. /// The version of the service pack currently installed on the operating system. /// Only the and fields are used. public static Version ServicePackVersion @@ -221,32 +142,7 @@ public static Version ServicePackVersion } #endregion // Properties - - - #region Methods - - /// Determines whether the operating system is of the specified version or later. - /// true if the operating system is of the specified or later; otherwise, false. - /// The lowest version for which to return true. - public static bool IsAtLeast(EnumOsName version) - { - return VersionName >= version; - } - - /// Determines whether the operating system is of the specified version or later, allowing specification of a minimum service pack that must be installed on the lowest version. - /// true if the operating system matches the specified with the specified service pack, or if the operating system is of a later version; otherwise, false. - /// The minimum required version. - /// The major version of the service pack that must be installed on the minimum required version to return true. This can be 0 to indicate that no service pack is required. - public static bool IsAtLeast(EnumOsName version, int servicePackVersion) - { - return IsAtLeast(version) && ServicePackVersion.Major >= servicePackVersion; - } - - #endregion // Methods - - - #region Private [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "RtlGetVersion")] private static void UpdateData() @@ -405,83 +301,5 @@ private static void UpdateData() break; } } - - - private static class NativeMethods - { - internal const short VER_NT_WORKSTATION = 1; - internal const short VER_NT_DOMAIN_CONTROLLER = 2; - internal const short VER_NT_SERVER = 3; - - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct RTL_OSVERSIONINFOEXW - { - public int dwOSVersionInfoSize; - public readonly int dwMajorVersion; - public readonly int dwMinorVersion; - public readonly int dwBuildNumber; - public readonly int dwPlatformId; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - public readonly string szCSDVersion; - public readonly ushort wServicePackMajor; - public readonly ushort wServicePackMinor; - public readonly ushort wSuiteMask; - public readonly byte wProductType; - public readonly byte wReserved; - } - - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct SYSTEM_INFO - { - public readonly EnumProcessorArchitecture wProcessorArchitecture; - private readonly ushort wReserved; - public readonly uint dwPageSize; - public readonly IntPtr lpMinimumApplicationAddress; - public readonly IntPtr lpMaximumApplicationAddress; - public readonly IntPtr dwActiveProcessorMask; - public readonly uint dwNumberOfProcessors; - public readonly uint dwProcessorType; - public readonly uint dwAllocationGranularity; - public readonly ushort wProcessorLevel; - public readonly ushort wProcessorRevision; - } - - - /// The RtlGetVersion routine returns version information about the currently running operating system. - /// RtlGetVersion returns STATUS_SUCCESS. - /// Available starting with Windows 2000. - [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule"), DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool RtlGetVersion([MarshalAs(UnmanagedType.Struct)] ref RTL_OSVERSIONINFOEXW lpVersionInformation); - - - /// Retrieves information about the current system to an application running under WOW64. - /// If the function is called from a 64-bit application, it is equivalent to the GetSystemInfo function. - /// - /// This function does not return a value. - /// To determine whether a Win32-based application is running under WOW64, call the function. - /// Minimum supported client: Windows XP [desktop apps | Windows Store apps] - /// Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps] - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] - [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern void GetNativeSystemInfo([MarshalAs(UnmanagedType.Struct)] ref SYSTEM_INFO lpSystemInfo); - - - /// Determines whether the specified process is running under WOW64. - /// - /// If the function succeeds, the return value is a nonzero value. - /// If the function fails, the return value is zero. To get extended error information, call GetLastError. - /// - /// Minimum supported client: Windows Vista, Windows XP with SP2 [desktop apps only] - /// Minimum supported server: Windows Server 2008, Windows Server 2003 with SP1 [desktop apps only] - [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 IsWow64Process([In] IntPtr hProcess, [Out, MarshalAs(UnmanagedType.Bool)] out bool lpSystemInfo); - } - - #endregion // Private } } diff --git a/AlphaFS/Safe Handles/SafeEncryptedFileRawHandle.cs b/AlphaFS/Safe Handles/SafeEncryptedFileRawHandle.cs index a3f46b8d3..135ca39df 100644 --- a/AlphaFS/Safe Handles/SafeEncryptedFileRawHandle.cs +++ b/AlphaFS/Safe Handles/SafeEncryptedFileRawHandle.cs @@ -1,9 +1,8 @@ using System; using System.Security; -using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32 +namespace Alphaleonis.Win32.Filesystem { /// Represents a wrapper class for a handle used by the OpenEncryptedFileRaw Win32 API functions. [SecurityCritical] diff --git a/AlphaFS/Safe Handles/SafeFindFileHandle.cs b/AlphaFS/Safe Handles/SafeFindFileHandle.cs index 3d75bcafe..a0f0788a8 100644 --- a/AlphaFS/Safe Handles/SafeFindFileHandle.cs +++ b/AlphaFS/Safe Handles/SafeFindFileHandle.cs @@ -21,14 +21,13 @@ using System; using System.Security; -using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32 +namespace Alphaleonis.Win32.Filesystem { /// Represents a wrapper class for a handle used by the FindFirstFile/FindNextFile Win32 API functions. [SecurityCritical] - internal sealed class SafeFindFileHandle : SafeHandleZeroOrMinusOneIsInvalid + public sealed class SafeFindFileHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Constructor that prevents a default instance of this class from being created. private SafeFindFileHandle() : base(true) diff --git a/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs b/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs index 526466dc5..0c5e8a2ff 100644 --- a/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs +++ b/AlphaFS/Safe Handles/SafeFindVolumeHandle.cs @@ -21,14 +21,13 @@ using System; using System.Security; -using Alphaleonis.Win32.Device; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32 +namespace Alphaleonis.Win32.Filesystem { /// Represents a wrapper class for a handle used by the FindFirstVolume/FindNextVolume methods of the Win32 API. [SecurityCritical] - internal sealed class SafeFindVolumeHandle : SafeHandleZeroOrMinusOneIsInvalid + public sealed class SafeFindVolumeHandle : SafeHandleZeroOrMinusOneIsInvalid { /// Constructor that prevents a default instance of this class from being created. private SafeFindVolumeHandle() : base(true) @@ -51,7 +50,7 @@ public SafeFindVolumeHandle(IntPtr handle, bool callerHandle) : base(callerHandl /// protected override bool ReleaseHandle() { - return NativeMethods.FindVolumeClose(handle); + return Device.NativeMethods.FindVolumeClose(handle); } } } diff --git a/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs b/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs index 4c03efa79..35e02a29f 100644 --- a/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs +++ b/AlphaFS/Safe Handles/SafeFindVolumeMountPointHandle.cs @@ -21,10 +21,9 @@ using System; using System.Security; -using Alphaleonis.Win32.Device; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32 +namespace Alphaleonis.Win32.Filesystem { /// Represents a wrapper class for a handle used by the FindFirstVolumeMountPoint/FindNextVolumeMountPoint methods of the Win32 API. [SecurityCritical] @@ -52,7 +51,7 @@ public SafeFindVolumeMountPointHandle(IntPtr handle, bool callerHandle) : base(c /// protected override bool ReleaseHandle() { - return NativeMethods.FindVolumeMountPointClose(handle); + return Device.NativeMethods.FindVolumeMountPointClose(handle); } } } diff --git a/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs b/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs index 2dc00701d..a9abe93f4 100644 --- a/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs +++ b/AlphaFS/Safe Handles/SafeKernelTransactionHandle.cs @@ -20,10 +20,9 @@ */ using System.Security; -using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32 +namespace Alphaleonis.Win32.Filesystem { /// Provides a concrete implementation of SafeHandle supporting transactions. internal class SafeKernelTransactionHandle : SafeHandleMinusOneIsInvalid diff --git a/AlphaFS/Safe Handles/SafeLocalMemoryBufferHandle.cs b/AlphaFS/Safe Handles/SafeLocalMemoryBufferHandle.cs index 586ab165f..b4690ca71 100644 --- a/AlphaFS/Safe Handles/SafeLocalMemoryBufferHandle.cs +++ b/AlphaFS/Safe Handles/SafeLocalMemoryBufferHandle.cs @@ -21,10 +21,9 @@ using System; using System.Runtime.InteropServices; -using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; -namespace Alphaleonis.Win32 +namespace Alphaleonis.Win32.Security { /// An IntPtr wrapper which can be used as the result of a Marshal.AllocHGlobal operation. /// Calls Marshal.FreeHGlobal when disposed or finalized. From cfe4ac9c524932e9799e778acd5d469f4e9baf35 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 8 Jun 2018 14:01:28 +0200 Subject: [PATCH 090/133] Fixed method Local.GetVolumeDiskExtents to return valid results. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 2 +- AlphaFS/Device/Native Other/DISK_EXTENT.cs | 30 +++++++++++++---- .../Native Other/VOLUME_DISK_EXTENTS.cs | 2 +- .../Storage/Device.StoragePartitionInfo.cs | 8 ++--- .../Storage/Local.GetStoragePartitionInfo.cs | 2 +- .../Storage/Local.GetVolumeDiskExtents.cs | 32 +++++++++++++------ AlphaFS/GlobalSuppressions.cs | 4 +-- AlphaFS/Utils.cs | 2 +- 8 files changed, 56 insertions(+), 26 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index a6305d445..cab66b780 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -25,7 +25,7 @@ namespace AlphaFS.UnitTest { - public partial class AlphaFS_PhysicalDiskInfoTest + public partial class EnumerationTest { // Pattern: ___ diff --git a/AlphaFS/Device/Native Other/DISK_EXTENT.cs b/AlphaFS/Device/Native Other/DISK_EXTENT.cs index 318af048d..ad036d62f 100644 --- a/AlphaFS/Device/Native Other/DISK_EXTENT.cs +++ b/AlphaFS/Device/Native Other/DISK_EXTENT.cs @@ -25,22 +25,38 @@ namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { - /// Represents a disk extent. - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// Represents a disk extent. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct DISK_EXTENT { /// The number of the disk that contains this extent. This is the same number that is used to construct the name of the disk, /// for example, the X in "\\.\PhysicalDriveX" or "\\?\HarddiskX". - [MarshalAs(UnmanagedType.U4)] public readonly uint DiskNumber; + [MarshalAs(UnmanagedType.U4)] public uint DiskNumber; /// The offset from the beginning of the disk to the extent, in bytes. - [MarshalAs(UnmanagedType.I8)] public readonly long StartingOffset; + [MarshalAs(UnmanagedType.I8)] public long StartingOffset; /// The number of bytes in this extent. - [MarshalAs(UnmanagedType.I8)] public readonly long ExtentLength; + [MarshalAs(UnmanagedType.I8)] public long ExtentLength; + } + + + /// Represents a disk extent. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct DISK_EXTENT_SINGLE + { + /// The number of disks in the volume (a volume can span multiple disks). + [MarshalAs(UnmanagedType.U4)] public readonly uint NumberOfDiskExtents; + + public readonly DISK_EXTENT Extent; } } } diff --git a/AlphaFS/Device/Native Other/VOLUME_DISK_EXTENTS.cs b/AlphaFS/Device/Native Other/VOLUME_DISK_EXTENTS.cs index ef9f25787..66dbab8e0 100644 --- a/AlphaFS/Device/Native Other/VOLUME_DISK_EXTENTS.cs +++ b/AlphaFS/Device/Native Other/VOLUME_DISK_EXTENTS.cs @@ -30,7 +30,7 @@ internal static partial class NativeMethods internal struct VOLUME_DISK_EXTENTS { /// The number of disks in the volume (a volume can span multiple disks). - [MarshalAs(UnmanagedType.U4)] public readonly uint NumberOfDiskExtents; + [MarshalAs(UnmanagedType.U4)] public uint NumberOfDiskExtents; /// An array of structures. [MarshalAs(UnmanagedType.ByValArray)] public DISK_EXTENT[] Extents; diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index d0a8016da..2eb693573 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -101,16 +101,16 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods // MSDN: PartitionCount: On hard disks with the MBR layout, this value will always be a multiple of 4. // Any partitions that are actually unused will have a partition type of PARTITION_ENTRY_UNUSED (0). - if (partition.Mbr.PartitionType == (NativeMethods.DiskPartitionType) DiskPartitionType.UnusedEntry) - continue; + //if (partition.Mbr.PartitionType == (NativeMethods.DiskPartitionType) DiskPartitionType.UnusedEntry) + // continue; MbrPartitionInfo.Add(new StorageMbrPartitionInfo(partition)); } - // Update to reflect the real number of used partition entries. - PartitionCount = MbrPartitionInfo.Count; + //// Update to reflect the real number of used partition entries. + //PartitionCount = MbrPartitionInfo.Count; break; } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 7455d4782..6791e9f25 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -192,7 +192,7 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHa if (success) { var typeOf = typeof(NativeMethods.DISK_GEOMETRY); - var sizeOf = Marshal.SizeOf(typeOf); + var sizeOf = Marshal.SizeOf(typeOf); // 24 var diskGeometryEx = new NativeMethods.DISK_GEOMETRY_EX { diff --git a/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs b/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs index 453cbe44e..9d86da057 100644 --- a/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs @@ -27,12 +27,11 @@ namespace Alphaleonis.Win32.Device { public static partial class Local { - /// Retrieves the physical location of a specified volume on one or more disks. + /// Retrieves the physical location and disk number of a specified volume on one or more disks. private static NativeMethods.VOLUME_DISK_EXTENTS? GetVolumeDiskExtents(SafeFileHandle safeHandle, string pathForException) { - var structSize = Marshal.SizeOf(typeof(NativeMethods.VOLUME_DISK_EXTENTS)); - var numberOfExtents = 1; - var bufferSize = structSize * numberOfExtents; + var structSize = Marshal.SizeOf(typeof(NativeMethods.DISK_EXTENT_SINGLE)); + var bufferSize = structSize; while(true) @@ -44,20 +43,35 @@ public static partial class Local if (success) { - numberOfExtents = safeBuffer.ReadInt32(); + var numberOfExtents = safeBuffer.ReadInt64(); var diskExtent = new NativeMethods.DISK_EXTENT[numberOfExtents]; + for (int i = 0, itemOffset = 0; i < numberOfExtents; i++, itemOffset = structSize * i) + { + var single = safeBuffer.PtrToStructure(itemOffset); - for (int i = 0, itemOffset = 0; i < numberOfExtents - 1; i++, itemOffset = structSize * i) + diskExtent[i].DiskNumber = single.Extent.DiskNumber; + diskExtent[i].ExtentLength = single.Extent.ExtentLength; + diskExtent[i].StartingOffset = single.Extent.StartingOffset; + } - diskExtent[i] = safeBuffer.PtrToStructure(itemOffset); + return new NativeMethods.VOLUME_DISK_EXTENTS + { + NumberOfDiskExtents = (uint) numberOfExtents, + Extents = diskExtent + }; + } - return new NativeMethods.VOLUME_DISK_EXTENTS {Extents = diskExtent}; - } + // When lastError = ERROR_MORE_DATA the drive is part of a mirror or volume, or the volume is on multiple disks. + + // Encountered a drive such as a CDRom/mounted .iso file. + if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) + return null; + bufferSize = Utils.GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); } } diff --git a/AlphaFS/GlobalSuppressions.cs b/AlphaFS/GlobalSuppressions.cs index d09e715ae..e31894ab3 100644 --- a/AlphaFS/GlobalSuppressions.cs +++ b/AlphaFS/GlobalSuppressions.cs @@ -45,7 +45,7 @@ [assembly: SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Scope = "member", Target = "Alphaleonis.Win32.Filesystem.NotSameDeviceException.#.cctor()")] [assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "Dir", Scope = "resource", Target = "Alphaleonis.Win32.Resources.resources")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Filesystem.NativeMethods+PARTITION_INFORMATION_GPT")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Filesystem.NativeMethods+PARTITION_INFORMATION_EX")] [assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Alphaleonis", Scope = "namespace", Target = "Alphaleonis.Win32.Device")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Device.NativeMethods+PARTITION_INFORMATION_EX")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "Name", Scope = "type", Target = "Alphaleonis.Win32.Device.NativeMethods+PARTITION_INFORMATION_GPT")] diff --git a/AlphaFS/Utils.cs b/AlphaFS/Utils.cs index 6ab9acbb5..5642633c1 100644 --- a/AlphaFS/Utils.cs +++ b/AlphaFS/Utils.cs @@ -43,7 +43,7 @@ internal static int GetDoubledBufferSizeOrThrowException(SafeHandle safeBuffer, safeBuffer.Close(); - switch ((uint)lastError) + switch ((uint) lastError) { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: From 79e5316a098852ada593bc2d904aeef2de23f11c Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 8 Jun 2018 17:45:10 +0200 Subject: [PATCH 091/133] Code improvement, renamed physical disk unit tests. --- ...iskInfo_UsingDevicePathFromSystemDrive.cs} | 2 +- ...o_UsingLogicalDrivePathFromSystemDrive.cs} | 4 +- ...iskInfo_UsingVolumePathFromSystemDrive.cs} | 4 +- ...torageAdapterInfo_FromLogicalDrivePath.cs} | 2 +- ...StorageDeviceInfo_FromLogicalDrivePath.cs} | 2 +- ...ragePartitionInfo_FromLogicalDrivePath.cs} | 28 ++++- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 12 +- .../FilesystemHelper.GetDevicePath.cs | 4 +- .../Storage/Device.StorageAdapterInfo.cs | 10 ++ .../Storage/Device.StorageDeviceInfo.cs | 7 ++ .../Storage/Device.StorageGptPartitionInfo.cs | 11 +- .../Storage/Device.StorageMbrPartitionInfo.cs | 13 +- .../Storage/Device.StoragePartitionInfo.cs | 18 ++- .../Storage/Local.GetStorageDeviceInfo.cs | 20 ++-- .../Storage/Local.GetStoragePartitionInfo.cs | 112 +++--------------- 15 files changed, 123 insertions(+), 126 deletions(-) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs => AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs} (96%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs => AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs} (93%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs => AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs} (93%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs => AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrivePath.cs} (99%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs => AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrivePath.cs} (99%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs => AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrivePath.cs} (83%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs similarity index 96% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs index 88c7d5c0c..9cc561117 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_DevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs @@ -31,7 +31,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetPhysicalDiskInfo_DevicePathFromSystemDrive_Success() + public void AlphaFS_Device_GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs similarity index 93% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs index 1be331c85..0b01d70d2 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_LogicalDriveFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetPhysicalDiskInfo_LogicalDriveFromSystemDrive_Success() + public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -50,6 +50,8 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_LogicalDriveFromSystemDrive_Succe UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + + UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs similarity index 93% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs index 63622b837..4bed98055 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_VolumeFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetPhysicalDiskInfo_VolumeFromSystemDrive_Success() + public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -54,6 +54,8 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_VolumeFromSystemDrive_Success() UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + + UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrivePath.cs similarity index 99% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrivePath.cs index 18f7bb424..9d7fba1d6 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrivePath.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrive_Success() + public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrivePath_Success() { UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrivePath.cs similarity index 99% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrivePath.cs index b02c3c245..bf8744dca 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrivePath.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrive_Success() + public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrivePath_Success() { UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrivePath.cs similarity index 83% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrivePath.cs index f64bd2072..fe3d51f99 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrivePath.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrive_Success() + public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrivePath_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -40,18 +40,36 @@ public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrive_Success() foreach (var driveInfo in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { - if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory || driveInfo.DriveType == System.IO.DriveType.Network) + if (driveInfo.DriveType == System.IO.DriveType.CDRom) + { + Console.WriteLine("\tSkipped CDRom drive: [{0}]", driveInfo.Name); continue; + } - var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(driveInfo.Name); + if (driveInfo.DriveType == System.IO.DriveType.Network) + { + Console.WriteLine("\tSkipped Network drive: [{0}]", driveInfo.Name); + continue; + } - Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storagePartitionInfo.ToString()); + if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) + { + Console.WriteLine("\tSkipped NoRootDirectory drive: [{0}]", driveInfo.Name); + continue; + } - UnitTestConstants.Dump(storagePartitionInfo); + var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(driveInfo.Name); + + if (null == storagePartitionInfo) + Console.WriteLine(); Assert.IsNotNull(storagePartitionInfo); + Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storagePartitionInfo.ToString()); + + UnitTestConstants.Dump(storagePartitionInfo); + if (null != storagePartitionInfo.GptPartitionInfo) { diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index f730f7669..4b815d044 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -144,12 +144,12 @@ AssemblyVersionInfo.cs - - - - - - + + + + + + diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs index 520079b6e..bc5978833 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs @@ -37,9 +37,9 @@ internal static partial class FileSystemHelper /// Returns the path string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} internal static string GetDevicePath(string devicePath) { - string unused; + string unusedLogicalDrive; - return GetDevicePath(devicePath, out unused); + return GetDevicePath(devicePath, out unusedLogicalDrive); } diff --git a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs index 1ec4381cc..42a6e4360 100644 --- a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs @@ -94,6 +94,16 @@ internal StorageAdapterInfo(NativeMethods.STORAGE_ADAPTER_DESCRIPTOR adapter) : /// Specifies the maximum number of bytes the storage adapter can transfer in a single operation. public int MaximumTransferBytes { get; internal set; } + +#if DEBUG + /// + public string MaximumTransferBytesUnitSize + { + get { return Utils.UnitSizeToText(MaximumTransferBytes); } + } +#endif + + #endregion // Properties diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 5f66d0080..1750b30f7 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -98,6 +98,13 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() /// The total size of the physical disk. public long TotalSize { get; internal set; } +#if DEBUG + /// + public string TotalSizeUnitSize + { + get { return Utils.UnitSizeToText(TotalSize); } + } +#endif /// The Vendor ID of the physical disk. public string VendorId { get; internal set; } diff --git a/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs b/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs index 334889dad..998a0e12d 100644 --- a/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs @@ -117,7 +117,7 @@ internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio public Guid PartitionId { get; private set; } - /// The starting offset of the partition. + /// The size of the partition. public long PartitionLength { get @@ -138,6 +138,15 @@ internal set } +#if DEBUG + /// + public string PartitionLengthUnitSize + { + get { return Utils.UnitSizeToText(PartitionLength); } + } +#endif + + /// The storage partition number, starting at 1. public int PartitionNumber { get; private set; } diff --git a/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs b/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs index d0085683a..6aef85312 100644 --- a/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs @@ -88,9 +88,9 @@ internal StorageMbrPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio /// The number of hidden sectors to be allocated when the partition table is created. public int HiddenSectors { get; private set; } - - /// The starting offset of the partition. + + /// The size of the partition. public long PartitionLength { get @@ -111,6 +111,15 @@ internal set } +#if DEBUG + /// + public string PartitionLengthUnitSize + { + get { return Utils.UnitSizeToText(PartitionLength); } + } +#endif + + /// The storage partition number, starting at 1. public int PartitionNumber { get; private set; } diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index 2eb693573..08b6957bd 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -54,8 +54,10 @@ public StoragePartitionInfo() } - internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods.DRIVE_LAYOUT_INFORMATION_EX drive, NativeMethods.PARTITION_INFORMATION_EX[] partitions) : this() + internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods.DRIVE_LAYOUT_INFORMATION_EX drive, NativeMethods.PARTITION_INFORMATION_EX[] partitions) : this() { + DeviceNumber = diskNumber; + MbrSignature = disk.PartitionInformation.MbrSignature; GptDiskId = disk.PartitionInformation.DiskId; @@ -113,6 +115,11 @@ internal StoragePartitionInfo(NativeMethods.DISK_GEOMETRY_EX disk, NativeMethods //PartitionCount = MbrPartitionInfo.Count; break; + + + default: + Console.WriteLine(PartitionStyle.ToString()); + break; } @@ -219,6 +226,15 @@ internal set /// The total size of the storage partition. public long TotalSize { get; private set; } + +#if DEBUG + /// + public string TotalSizeUnitSize + { + get { return Utils.UnitSizeToText(TotalSize); } + } +#endif + #endregion // Properties diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index 782e74e85..7b4775bf0 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -141,6 +141,8 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH StartGetData: + StorageDeviceInfo newStorageDeviceInfo; + // Get storage device info. using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) @@ -175,7 +177,7 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH var deviceDescriptor = safeBuffer.PtrToStructure(); - storageDeviceInfo = new StorageDeviceInfo + newStorageDeviceInfo = new StorageDeviceInfo { DeviceType = storageDeviceInfo.DeviceType, @@ -200,26 +202,26 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH }; - if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.ProductRevision) || storageDeviceInfo.ProductRevision.Length == 1) - storageDeviceInfo.ProductRevision = null; + if (Utils.IsNullOrWhiteSpace(newStorageDeviceInfo.ProductRevision) || newStorageDeviceInfo.ProductRevision.Length == 1) + newStorageDeviceInfo.ProductRevision = null; - if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.SerialNumber) || storageDeviceInfo.SerialNumber.Length == 1) - storageDeviceInfo.SerialNumber = null; + if (Utils.IsNullOrWhiteSpace(newStorageDeviceInfo.SerialNumber) || newStorageDeviceInfo.SerialNumber.Length == 1) + newStorageDeviceInfo.SerialNumber = null; - if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.VendorId) || storageDeviceInfo.VendorId.Length == 1) - storageDeviceInfo.VendorId = null; + if (Utils.IsNullOrWhiteSpace(newStorageDeviceInfo.VendorId) || newStorageDeviceInfo.VendorId.Length == 1) + newStorageDeviceInfo.VendorId = null; } using (var safeBuffer = GetDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, pathToDevice)) - storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; + newStorageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; if (isRetry && !safeHandleRetry.IsClosed) safeHandleRetry.Close(); - return storageDeviceInfo; + return newStorageDeviceInfo; } } } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 6791e9f25..53fddf431 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -57,123 +57,45 @@ public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) } - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandle, string pathToDevice) + private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandle, string pathForException) { - SafeFileHandle safeHandleRetry = null; - var isRetry = false; + var volDiskExtents = GetVolumeDiskExtents(safeHandle, pathForException); + if (null == volDiskExtents || volDiskExtents.Value.NumberOfDiskExtents == 0) + return null; + - StartGetData: - - // Get storage partition info. - - using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, pathToDevice, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, pathForException, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) { - if (null == safeBuffer) - { - // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - - - var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle, pathToDevice); - - if (volDiskExtents.HasValue) - { - // Use the first disk extent. - - pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - - - safeHandleRetry = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); - - isRetry = Utils.IsValidHandle(safeHandleRetry, false); - } - - - if (isRetry) - goto StartGetData; - - return null; - } - - - if (isRetry && !safeHandleRetry.IsClosed) - safeHandleRetry.Close(); - - var layout = safeBuffer.PtrToStructure(); // Sanity check. if (layout.PartitionCount <= 256) { var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 + var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 + var partitions = new NativeMethods.PARTITION_INFORMATION_EX[layout.PartitionCount]; + for (var i = 0; i <= layout.PartitionCount - 1; i++) partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); - var disk = GetDiskGeometryExNative(safeHandle, pathToDevice); - - return new StoragePartitionInfo(disk, layout, partitions); - } - - return null; - } - } - - - - //private static StoragePartitionInfo GetStoragePartitionInfoNative0(SafeFileHandle safeHandle, string pathForException) - //{ - // var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 - // var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 - // var partitionCount = 1; - - // var bufferSize = driveStructureSize + partitionCount * partitionStructureSize; - - // while (true) - // using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) - // { - // var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); - - // var lastError = Marshal.GetLastWin32Error(); - - - // if (success) - // { - // var drive = safeBuffer.PtrToStructure(); - - // var partitions = new NativeMethods.PARTITION_INFORMATION_EX[drive.PartitionCount]; + var disk = GetDiskGeometryExNative(safeHandle, pathForException); - // for (partitionCount = 0; partitionCount <= drive.PartitionCount - 1; partitionCount++) - - // partitions[partitionCount] = safeBuffer.PtrToStructure(driveStructureSize + partitionCount * partitionStructureSize); - - - // var disk = GetDiskGeometryExNative(safeHandle, pathForException); - - // return new StoragePartitionInfo(disk, drive, partitions); - // } - - - // if (lastError == Win32Errors.ERROR_NOT_READY || - - // // Dynamic disk. - // lastError == Win32Errors.ERROR_INVALID_FUNCTION || - - // // Request device number from a DeviceGuid.Image device. - // lastError == Win32Errors.ERROR_NOT_SUPPORTED) - - // return null; + // Use the first disk extent. + var diskNumber = volDiskExtents.Value.Extents[0].DiskNumber; + return new StoragePartitionInfo((int)diskNumber, disk, layout, partitions); + } + } - // bufferSize = GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); - // } - //} + return null; + } /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). From 8bb89a5f09ffa556552e0bbdef5689a231d16f59 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 8 Jun 2018 22:45:16 +0200 Subject: [PATCH 092/133] -Added Volume.GetVolumeInfo(string volumePath, bool continueOnException) overloaded method; -Code improvement, renamed some unit tests; --- ...DiskInfo_UsingDevicePathFromSystemDrive.cs | 13 ++-- ...fo_UsingLogicalDrivePathFromSystemDrive.cs | 13 ++-- ...DiskInfo_UsingVolumePathFromSystemDrive.cs | 13 ++-- ...orageAdapterInfo_UsingLogicalDrivePath.cs} | 17 ++++- ...torageDeviceInfo_UsingLogicalDrivePath.cs} | 17 ++++- ...agePartitionInfo_UsingLogicalDrivePath.cs} | 21 ++---- .../AlphaFS_Volume.GetDriveFormat.cs | 19 +---- ...me.GetVolumeInfo_UsingLogicalDrivePath.cs} | 40 ++++++----- ...e.GetVolumeLabel_UsingLogicalDrivePath.cs} | 2 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 10 +-- .../Local.EnumeratePhysicalDisks.cs | 12 +++- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 28 +++++--- .../Storage/Device.StorageDeviceInfo.cs | 9 ++- .../Storage/Device.StoragePartitionInfo.cs | 70 +++++++++++-------- .../Storage/Local.GetStoragePartitionInfo.cs | 3 - AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs | 11 +++ 16 files changed, 175 insertions(+), 123 deletions(-) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrivePath.cs => AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs} (79%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrivePath.cs => AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs} (81%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrivePath.cs => AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs} (79%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/{AlphaFS_Volume.GetVolumeInfo.cs => AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs} (70%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/{AlphaFS_Volume.GetVolumeLabel.cs => AlphaFS_Volume.GetVolumeLabel_UsingLogicalDrivePath.cs} (96%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs index 9cc561117..1dc807cae 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs @@ -59,17 +59,16 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive_Su Assert.IsNotNull(pDisk); - - - Assert.IsNotNull(pDisk.VolumeGuids); - Assert.IsTrue(pDisk.VolumeGuids.ToList().Contains(sourceVolume, StringComparer.OrdinalIgnoreCase)); - Assert.IsNotNull(pDisk.LogicalDrives); - Assert.IsTrue(pDisk.LogicalDrives.Contains(sourceDrive)); + Assert.IsNotNull(pDisk.VolumeGuids); + + Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + + Assert.AreEqual(pDisk.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceDrive)); - Assert.IsTrue(pDisk.ContainsVolume(sourceDrive[0].ToString())); + Assert.AreEqual(pDisk.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceVolume)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs index 0b01d70d2..8dc5708fe 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs @@ -20,6 +20,7 @@ */ using System; +using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -37,8 +38,7 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDr var driveCount = 0; - // Use lowercase drive letter because .Contains() is case sensitive by default. - var sourceDrive = UnitTestConstants.SysDrive.ToLowerInvariant() + System.IO.Path.DirectorySeparatorChar; + var sourceDrive = UnitTestConstants.SysDrive; var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive); @@ -57,10 +57,13 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDr Assert.IsNotNull(pDisk); - Assert.IsNotNull(pDisk.LogicalDrives); - //Assert.IsTrue(pDisk.LogicalDrives.Contains(sourceDrive)); - Assert.IsTrue(pDisk.ContainsVolume(sourceDrive)); + + Assert.IsNotNull(pDisk.VolumeGuids); + + Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + + Assert.AreEqual(pDisk.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceDrive)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs index 4bed98055..a4b96e32e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs @@ -20,6 +20,7 @@ */ using System; +using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -37,8 +38,7 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Su var volumeCount = 0; - // Use lowercase drive letter because .Contains() is case sensitive by default. - var sourceDrive = UnitTestConstants.SysDrive.ToLowerInvariant(); + var sourceDrive = UnitTestConstants.SysDrive; var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); @@ -61,10 +61,15 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Su Assert.IsNotNull(pDisk); + Assert.IsNotNull(pDisk.LogicalDrives); Assert.IsNotNull(pDisk.VolumeGuids); - //Assert.IsTrue(pDisk.VolumeGuids.Contains(sourceVolume)); - Assert.IsTrue(pDisk.ContainsVolume(sourceVolume)); + + Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + + Assert.AreEqual(pDisk.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceDrive)); + + Assert.AreEqual(pDisk.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceVolume)); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs similarity index 79% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrivePath.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs index 9d7fba1d6..313edbaff 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_FromLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrivePath_Success() + public void AlphaFS_Device_GetStorageAdapterInfo_UsingLogicalDrivePath_Success() { UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); @@ -41,8 +41,21 @@ public void AlphaFS_Device_GetStorageAdapterInfo_FromLogicalDrivePath_Success() foreach (var driveInfo in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { - if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory || driveInfo.DriveType == System.IO.DriveType.Network) + // Works with System.IO.DriveType.CDRom. + + // System.UnauthorizedAccessException: (5) Access is denied. + if (driveInfo.DriveType == System.IO.DriveType.Network) + { + Console.WriteLine("#{0:000}\tSkipped Network drive: [{1}]\n", ++driveCount, driveInfo.Name); + continue; + } + + if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) + { + Console.WriteLine("#{0:000}\tSkipped NoRootDirectory drive: [{1}]\n", ++driveCount, driveInfo.Name); continue; + } + var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(driveInfo.Name); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs similarity index 81% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrivePath.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs index bf8744dca..c2ffe83a4 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_FromLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrivePath_Success() + public void AlphaFS_Device_GetStorageDeviceInfo_UsingLogicalDrivePath_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -40,8 +40,21 @@ public void AlphaFS_Device_GetStorageDeviceInfo_FromLogicalDrivePath_Success() foreach (var driveInfo in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { - if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory || driveInfo.DriveType == System.IO.DriveType.Network) + // Works with System.IO.DriveType.CDRom. + + // System.UnauthorizedAccessException: (5) Access is denied. + if (driveInfo.DriveType == System.IO.DriveType.Network) + { + Console.WriteLine("#{0:000}\tSkipped Network drive: [{1}]\n", ++driveCount, driveInfo.Name); + continue; + } + + if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) + { + Console.WriteLine("#{0:000}\tSkipped NoRootDirectory drive: [{1}]\n", ++driveCount, driveInfo.Name); continue; + } + var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(driveInfo.Name); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs similarity index 79% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrivePath.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs index fe3d51f99..24a6d201c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_FromLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrivePath_Success() + public void AlphaFS_Device_GetStoragePartitionInfo_UsingLogicalDrivePath_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -40,21 +40,23 @@ public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrivePath_Success( foreach (var driveInfo in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) { + // System.IO.DriveType.CDRom = null. if (driveInfo.DriveType == System.IO.DriveType.CDRom) { - Console.WriteLine("\tSkipped CDRom drive: [{0}]", driveInfo.Name); + Console.WriteLine("#{0:000}\tSkipped CDRom drive: [{1}]\n", ++driveCount, driveInfo.Name); continue; } + // System.UnauthorizedAccessException: (5) Access is denied. if (driveInfo.DriveType == System.IO.DriveType.Network) { - Console.WriteLine("\tSkipped Network drive: [{0}]", driveInfo.Name); + Console.WriteLine("#{0:000}\tSkipped Network drive: [{1}]\n", ++driveCount, driveInfo.Name); continue; } if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) { - Console.WriteLine("\tSkipped NoRootDirectory drive: [{0}]", driveInfo.Name); + Console.WriteLine("#{0:000}\tSkipped NoRootDirectory drive: [{1}]\n", ++driveCount, driveInfo.Name); continue; } @@ -89,17 +91,6 @@ public void AlphaFS_Device_GetStoragePartitionInfo_FromLogicalDrivePath_Success( } - //if (drive.DriveType == System.IO.DriveType.Fixed) - //{ - // gotDisk = true; - // Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.Disk, storagePartitionInfo.DeviceType); - //} - - - //if (drive.DriveType == System.IO.DriveType.CDRom) - // Assert.AreEqual(Alphaleonis.Win32.Filesystem.StorageDeviceType.CDRom, storagePartitionInfo.DeviceType); - - Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs index be8788828..029e3b15f 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs @@ -51,31 +51,16 @@ private void AlphaFS_Volume_GetDriveFormat(bool isNetwork) Console.Write("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveName); - // Skip mapped drives and CDRom drives. - - if (logicalDrive.DriveType == System.IO.DriveType.NoRootDirectory || logicalDrive.DriveType == System.IO.DriveType.CDRom) - { - Console.WriteLine(); - continue; - } - - var driveFormat = Alphaleonis.Win32.Filesystem.Volume.GetDriveFormat(driveName); Console.WriteLine("\t\tDrive Format: [{0}]", driveFormat); - if (isNetwork) + if (!Alphaleonis.Utils.IsNullOrWhiteSpace(driveFormat)) { // Some USB drives do not report drive format. - - if (null != driveFormat) - Assert.AreEqual(logicalDrive.DriveFormat, driveFormat); - } - - else Assert.AreEqual(logicalDrive.DriveFormat, driveFormat); - + } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs similarity index 70% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs index c47e5bacf..e71f445ae 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs @@ -30,14 +30,14 @@ public partial class AlphaFS_VolumeTest [TestMethod] - public void AlphaFS_Volume_GetVolumeInfo_LocalAndNetwork_Success() + public void AlphaFS_Volume_GetVolumeInfo_UsingLogicalDrivePath_LocalAndNetwork_Success() { - AlphaFS_Volume_GetVolumeInfo_FromLogicalDrive(false); - AlphaFS_Volume_GetVolumeInfo_FromLogicalDrive(true); + AlphaFS_Volume_GetVolumeInfo_UsingLogicalDrivePath(false); + AlphaFS_Volume_GetVolumeInfo_UsingLogicalDrivePath(true); } - private void AlphaFS_Volume_GetVolumeInfo_FromLogicalDrive(bool isNetwork) + private void AlphaFS_Volume_GetVolumeInfo_UsingLogicalDrivePath(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); @@ -51,13 +51,13 @@ private void AlphaFS_Volume_GetVolumeInfo_FromLogicalDrive(bool isNetwork) Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveName); - // Skip mapped drives and CDRom drives. + //// Skip mapped drives and CDRom drives. - if (logicalDrive.DriveType == System.IO.DriveType.NoRootDirectory || logicalDrive.DriveType == System.IO.DriveType.CDRom) - { - Console.WriteLine(); - continue; - } + //if (logicalDrive.DriveType == System.IO.DriveType.NoRootDirectory || logicalDrive.DriveType == System.IO.DriveType.CDRom) + //{ + // Console.WriteLine(); + // continue; + //} if (isNetwork) @@ -87,7 +87,7 @@ private void AlphaFS_Volume_GetVolumeInfo_FromLogicalDrive(bool isNetwork) else { - var volInfo = Alphaleonis.Win32.Filesystem.Volume.GetVolumeInfo(driveName); + var volInfo = Alphaleonis.Win32.Filesystem.Volume.GetVolumeInfo(driveName, true); UnitTestConstants.Dump(volInfo); @@ -96,15 +96,21 @@ private void AlphaFS_Volume_GetVolumeInfo_FromLogicalDrive(bool isNetwork) var driveInfo2 = new System.IO.DriveInfo(driveName); - Assert.AreEqual(driveInfo2.VolumeLabel, volInfo.Name); - Assert.AreEqual(driveInfo2.DriveFormat, volInfo.FileSystemName); - Assert.AreEqual(driveInfo2.Name, volInfo.FullPath); + + // Prevent System.IO.IOException: (1005) The volume does not contain a recognized file system. - if (logicalDrive.DriveType != System.IO.DriveType.Network) + if (null != volInfo && null != volInfo.FileSystemName) { - Assert.IsNotNull(volInfo.Guid); + Assert.AreEqual(driveInfo2.VolumeLabel, volInfo.Name); + Assert.AreEqual(driveInfo2.DriveFormat, volInfo.FileSystemName); + Assert.AreEqual(driveInfo2.Name, volInfo.FullPath); + + if (logicalDrive.DriveType != System.IO.DriveType.Network) + { + Assert.IsNotNull(volInfo.Guid); - Assert.IsTrue(volInfo.Guid.StartsWith(Alphaleonis.Win32.Filesystem.Path.VolumePrefix)); + Assert.IsTrue(volInfo.Guid.StartsWith(Alphaleonis.Win32.Filesystem.Path.VolumePrefix)); + } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeLabel.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeLabel_UsingLogicalDrivePath.cs similarity index 96% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeLabel.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeLabel_UsingLogicalDrivePath.cs index 0bb7f3c8c..9d8fdc518 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeLabel.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeLabel_UsingLogicalDrivePath.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_VolumeTest [TestMethod] - public void AlphaFS_Volume_GetVolumeLabel_Local_Success() + public void AlphaFS_Volume_GetVolumeLabel_UsingLogicalDrivePath_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 4b815d044..8c44aa28b 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -147,9 +147,9 @@ - - - + + + @@ -250,7 +250,7 @@ - + @@ -490,7 +490,7 @@ - + diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 55cf2c31e..e6dfa433b 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -115,7 +115,11 @@ private static void PopulateVolumeDetails(PhysicalDiskInfo pDiskInfo, int partit private static PhysicalDiskInfo PopulatePhysicalCDRom(PhysicalDiskInfo pCdRom, PhysicalDiskInfo[] pVolumes, PhysicalDiskInfo[] pLogicalDrives) { - var pDiskInfo = new PhysicalDiskInfo(pCdRom) {StorageDeviceInfo = pCdRom.StorageDeviceInfo}; + var pDiskInfo = new PhysicalDiskInfo(pCdRom) + { + StorageDeviceInfo = pCdRom.StorageDeviceInfo, + StoragePartitionInfo = pCdRom.StoragePartitionInfo + }; // Get volume from CDRom matching DeviceNumber. @@ -142,7 +146,11 @@ private static PhysicalDiskInfo PopulatePhysicalCDRom(PhysicalDiskInfo pCdRom, P private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, PhysicalDiskInfo[] pVolumes, PhysicalDiskInfo[] pLogicalDrives) { - var pDiskInfo = new PhysicalDiskInfo(pDisk) {StorageDeviceInfo = pDisk.StorageDeviceInfo}; + var pDiskInfo = new PhysicalDiskInfo(pDisk) + { + StorageDeviceInfo = pDisk.StorageDeviceInfo, + StoragePartitionInfo = pDisk.StoragePartitionInfo + }; foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber)) diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index 58a5597f1..04076e143 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -56,19 +56,18 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) var isElevated = ProcessContext.IsElevatedProcess; - devicePath = FileSystemHelper.ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + var validatedDevicePath = FileSystemHelper.ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, devicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, validatedDevicePath); if (null == storageDeviceInfo) return null; - - - // Use logical drive path. + if (isDrive) - FileSystemHelper.GetDevicePath(devicePath, out devicePath); + // Use logical drive path. + FileSystemHelper.GetDevicePath(validatedDevicePath, out validatedDevicePath); var pDiskInfo = isDeviceInfo @@ -76,15 +75,24 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => pDisk.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber && pDisk.StorageDeviceInfo.PartitionNumber == storageDeviceInfo.PartitionNumber) : isVolume - ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => null != pDisk.VolumeGuids && pDisk.VolumeGuids.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) + ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => null != pDisk.VolumeGuids && pDisk.ContainsVolume(validatedDevicePath)) : isDrive - ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => null != pDisk.LogicalDrives && pDisk.LogicalDrives.Contains(devicePath, StringComparer.OrdinalIgnoreCase)) + ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => null != pDisk.LogicalDrives && pDisk.ContainsVolume(validatedDevicePath)) : null; - if (null != pDiskInfo && null != pDiskInfo.StorageDeviceInfo) - pDiskInfo.StorageDeviceInfo.PartitionNumber = storageDeviceInfo.PartitionNumber; + if (null != pDiskInfo) + { + // Use the storageDeviceInfo created earlier using validatedDevicePath. + pDiskInfo.StorageDeviceInfo = storageDeviceInfo; + + + if (isDeviceInfo) + // Accessing the device by its path: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + // does not relate to any drive or volume, so the default PartitionNumber of 0 is misleading. + pDiskInfo.StorageDeviceInfo.PartitionNumber = -1; + } return pDiskInfo; diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 1750b30f7..6607fd402 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -75,7 +75,10 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public int DeviceNumber { get; internal set; } - /// The partition number of the storage device, starting at 1. If the device cannot be partitioned, like a CDROM, -1 is returned. + /// + /// The partition number of the storage device, starting at 1. If the device cannot be partitioned, like a CDROM, -1 is returned. + /// -1 is also returned if the device is accessed by its path: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} instead of a logical drive- or volume path. + /// public int PartitionNumber { get; internal set; } @@ -114,11 +117,11 @@ public string TotalSizeUnitSize #region Methods - /// Returns storage device as: "VendorId ProductId DeviceType DeviceNumber:PartitionNumber". + /// Returns storage device as: "DeviceType DeviceNumber:PartitionNumber VendorId ProductId". /// Returns a string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "{0} {1}:{2} {3}", DeviceType.ToString(), DeviceNumber.ToString(CultureInfo.InvariantCulture), PartitionNumber.ToString(CultureInfo.InvariantCulture), (VendorId + " " + ProductId + " " + ProductRevision).Trim()).Trim(); + return string.Format(CultureInfo.CurrentCulture, "Device: {0}:{1} {2}", DeviceNumber.ToString(CultureInfo.InvariantCulture), PartitionNumber.ToString(CultureInfo.InvariantCulture), (VendorId + " " + ProductId + " " + ProductRevision).Trim()).Trim(); } diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index 08b6957bd..bd55c143e 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -37,6 +37,7 @@ public sealed class StoragePartitionInfo #region Private Fields private ulong _gptStartingUsableOffset; + private ulong _gptUsableLength; #endregion // Private Fields @@ -78,6 +79,7 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis GptMaxPartitionCount = (int) drive.Gpt.MaxPartitionCount; _gptStartingUsableOffset = drive.Gpt.StartingUsableOffset; + _gptUsableLength = drive.Gpt.UsableLength; GptPartitionInfo = new Collection(); @@ -103,16 +105,16 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis // MSDN: PartitionCount: On hard disks with the MBR layout, this value will always be a multiple of 4. // Any partitions that are actually unused will have a partition type of PARTITION_ENTRY_UNUSED (0). - //if (partition.Mbr.PartitionType == (NativeMethods.DiskPartitionType) DiskPartitionType.UnusedEntry) - // continue; - + if (partition.Mbr.PartitionType == (NativeMethods.DiskPartitionType)DiskPartitionType.UnusedEntry) + continue; + MbrPartitionInfo.Add(new StorageMbrPartitionInfo(partition)); } - - //// Update to reflect the real number of used partition entries. - //PartitionCount = MbrPartitionInfo.Count; + + // Update to reflect the real number of used partition entries. + PartitionCount = MbrPartitionInfo.Count; break; @@ -121,7 +123,7 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis Console.WriteLine(PartitionStyle.ToString()); break; } - + IsOnDynamicDisk = null != GptPartitionInfo && GptPartitionInfo.Any(partition => @@ -138,7 +140,7 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis /// The GUID of the disk. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] public Guid GptDiskId { get; private set; } - + /// The device number of the storage partition, starting at 0. public int DeviceNumber { get; private set; } @@ -176,25 +178,36 @@ internal set } - ///// The size of the usable blocks on the disk, in bytes. - //public long GptUsableLength - //{ - // get - // { - // unchecked - // { - // return (long) _gptUsableLength; - // } - // } + /// The size of the usable blocks on the disk, in bytes. + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] + public long GptUsableLength + { + get + { + unchecked + { + return (long) _gptUsableLength; + } + } - // internal set - // { - // unchecked - // { - // _gptUsableLength = (ulong) value; - // } - // } - //} + internal set + { + unchecked + { + _gptUsableLength = (ulong) value; + } + } + } + + +#if DEBUG + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] + public string GptUsableLengthUnitSize + { + get { return Utils.UnitSizeToText(GptUsableLength); } + } +#endif /// true if the partition is on a dynamic disk. @@ -244,10 +257,7 @@ public string TotalSizeUnitSize /// Returns a string that represents this instance. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "{0}:{1} {2}", - - DeviceNumber.ToString(CultureInfo.InvariantCulture), "?".ToString(CultureInfo.InvariantCulture), PartitionStyle.ToString()).Trim(); - //DeviceNumber.ToString(CultureInfo.InvariantCulture), PartitionNumber.ToString(CultureInfo.InvariantCulture), PartitionStyle.ToString()).Trim(); + return string.Format(CultureInfo.CurrentCulture, "Device: {0} PartitionStyle: {1}", DeviceNumber.ToString(CultureInfo.InvariantCulture), PartitionStyle.ToString().ToUpperInvariant()).Trim(); } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 53fddf431..4f14fd710 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -20,10 +20,7 @@ */ using System; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; using System.Runtime.InteropServices; -using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs b/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs index dcbd618f7..3e0b26c4a 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs @@ -36,6 +36,17 @@ public static VolumeInfo GetVolumeInfo(string volumePath) } + /// [AlphaFS] Retrieves information about the file system and volume associated with the specified root file or directorystream. + /// Returns a instance describing the volume associatied with the specified root directory. + /// A path that contains the root directory. + /// true suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. + [SecurityCritical] + public static VolumeInfo GetVolumeInfo(string volumePath, bool continueOnException) + { + return new VolumeInfo(volumePath, true, continueOnException); + } + + /// [AlphaFS] Retrieves information about the file system and volume associated with the specified root file or directorystream. /// An instance to a handle. /// Returns a instance describing the volume associatied with the specified root directory. From bb736329bd6d571216ac8cfc0adb639b7c121927 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 9 Jun 2018 00:28:03 +0200 Subject: [PATCH 093/133] Fixed unit test Volume.GetUniqueVolumeNameForPath to handle mount points and iproved some others. --- ...torageAdapterInfo_UsingLogicalDrivePath.cs | 2 +- ...StorageDeviceInfo_UsingLogicalDrivePath.cs | 2 +- ...ragePartitionInfo_UsingLogicalDrivePath.cs | 2 +- .../AlphaFS_Volume.GetDriveFormat.cs | 12 ++++---- ...haFS_Volume.GetDriveNameForNtDeviceName.cs | 6 ++-- .../AlphaFS_Volume.GetDriveType.cs | 8 +++--- ...phaFS_Volume.GetUniqueVolumeNameForPath.cs | 28 +++++++++++++------ ...ume.GetVolumeInfo_UsingLogicalDrivePath.cs | 8 +++--- .../AlphaFS_Volume.GetXxx.cs | 18 ++++++------ .../DriveInfo Class/DriveInfo.GetDrives.cs | 24 ++++------------ ...ry.GetFileSystemEntryInfo_LogicalDrives.cs | 2 +- 11 files changed, 56 insertions(+), 56 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs index 313edbaff..4a059eb0c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs @@ -39,7 +39,7 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingLogicalDrivePath_Success() var driveCount = 0; - foreach (var driveInfo in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) + foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { // Works with System.IO.DriveType.CDRom. diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs index c2ffe83a4..472bcb73b 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs @@ -38,7 +38,7 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingLogicalDrivePath_Success() var driveCount = 0; - foreach (var driveInfo in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) + foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { // Works with System.IO.DriveType.CDRom. diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs index 24a6d201c..467b56044 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs @@ -38,7 +38,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingLogicalDrivePath_Success var driveCount = 0; - foreach (var driveInfo in Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives()) + foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { // System.IO.DriveType.CDRom = null. if (driveInfo.DriveType == System.IO.DriveType.CDRom) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs index 029e3b15f..2f2414316 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs @@ -44,9 +44,9 @@ private void AlphaFS_Volume_GetDriveFormat(bool isNetwork) var logicalDriveCount = 0; - foreach (var logicalDrive in System.IO.DriveInfo.GetDrives()) + foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { - var driveName = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(logicalDrive.Name) : logicalDrive.Name; + var driveName = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(driveInfo.Name) : driveInfo.Name; Console.Write("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveName); @@ -56,11 +56,11 @@ private void AlphaFS_Volume_GetDriveFormat(bool isNetwork) Console.WriteLine("\t\tDrive Format: [{0}]", driveFormat); + // Some USB drives do not report drive format when path is UNC. + if (!Alphaleonis.Utils.IsNullOrWhiteSpace(driveFormat)) - { - // Some USB drives do not report drive format. - Assert.AreEqual(logicalDrive.DriveFormat, driveFormat); - } + + Assert.AreEqual(driveInfo.DriveFormat, driveFormat); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs index b47d25d70..18105a0bf 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs @@ -37,15 +37,15 @@ public void AlphaFS_Volume_GetDriveNameForNtDeviceName_And_GetVolumeGuidForNtDev var logicalDriveCount = 0; - foreach (var drive in System.IO.DriveInfo.GetDrives()) + foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { // Skip mapped drives and network drives. - if (drive.DriveType == System.IO.DriveType.NoRootDirectory || drive.DriveType == System.IO.DriveType.Network) + if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory || driveInfo.DriveType == System.IO.DriveType.Network) continue; - var driveName = drive.Name; + var driveName = driveInfo.Name; var dosDeviceName = Alphaleonis.Win32.Filesystem.Volume.GetVolumeDeviceName(driveName); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveType.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveType.cs index 7fa7162c8..c30e4475e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveType.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveType.cs @@ -44,13 +44,13 @@ private void AlphaFS_Volume_GetDriveType(bool isNetwork) var logicalDriveCount = 0; - foreach (var logicalDrive in System.IO.DriveInfo.GetDrives()) + foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { - var driveName = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(logicalDrive.Name) : logicalDrive.Name; + var driveName = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(driveInfo.Name) : driveInfo.Name; Console.Write("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveName); - if (logicalDrive.DriveType == System.IO.DriveType.CDRom) + if (driveInfo.DriveType == System.IO.DriveType.CDRom) { Console.WriteLine(); continue; @@ -68,7 +68,7 @@ private void AlphaFS_Volume_GetDriveType(bool isNetwork) } else - Assert.AreEqual(logicalDrive.DriveType, driveType); + Assert.AreEqual(driveInfo.DriveType, driveType); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs index 23af4945c..93eb96d7c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs @@ -38,15 +38,15 @@ public void AlphaFS_Volume_GetUniqueVolumeNameForPath_Local_Success() var logicalDriveCount = 0; - foreach (var drive in System.IO.DriveInfo.GetDrives()) + foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { // Skip mapped drives and network drives. - if (drive.DriveType == System.IO.DriveType.NoRootDirectory || drive.DriveType == System.IO.DriveType.Network) + if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory || driveInfo.DriveType == System.IO.DriveType.Network) continue; - var driveName = drive.Name; + var driveName = driveInfo.Name; var deviceGuid = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(driveName); @@ -65,16 +65,28 @@ public void AlphaFS_Volume_GetUniqueVolumeNameForPath_Local_Success() var pathNames = Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumePathNames(volumeNameResult).ToArray(); - foreach (var displayName in pathNames) + foreach (var uniqueName in pathNames) { - Console.WriteLine("\n\t(Input Volume GUID Path) EnumerateVolumePathNames: Volume points to logcal drive: [{0}]\n", displayName); + Console.WriteLine("\n\tUnique name: [{0}]", uniqueName); - // Volumes don't always have drive letters. + try + { + var targetInfo = Alphaleonis.Win32.Filesystem.Directory.GetLinkTargetInfo(uniqueName); - if (!string.IsNullOrWhiteSpace(displayName)) - Assert.AreEqual(driveName, displayName); + UnitTestConstants.Dump(targetInfo); + + Assert.AreEqual(deviceGuid, Alphaleonis.Win32.Filesystem.Path.LongPathPrefix + targetInfo.SubstituteName.Replace(Alphaleonis.Win32.Filesystem.Path.NonInterpretedPathPrefix, string.Empty)); + } + catch + { + if (!string.IsNullOrWhiteSpace(uniqueName)) + Assert.AreEqual(driveName, uniqueName); + } } + + + Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs index e71f445ae..03e719600 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs @@ -44,9 +44,9 @@ private void AlphaFS_Volume_GetVolumeInfo_UsingLogicalDrivePath(bool isNetwork) var logicalDriveCount = 0; - foreach (var logicalDrive in System.IO.DriveInfo.GetDrives()) + foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { - var driveName = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(logicalDrive.Name) : logicalDrive.Name; + var driveName = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(driveInfo.Name) : driveInfo.Name; Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveName); @@ -79,7 +79,7 @@ private void AlphaFS_Volume_GetVolumeInfo_UsingLogicalDrivePath(bool isNetwork) Assert.AreEqual(driveInfo2.VolumeLabel, volInfo.Name); Assert.AreEqual(driveInfo2.DriveFormat, volInfo.FileSystemName); - if (logicalDrive.DriveType != System.IO.DriveType.Network) + if (driveInfo.DriveType != System.IO.DriveType.Network) Assert.AreEqual(driveInfo2.Name, volInfo.FullPath); Assert.IsNull(volInfo.Guid); @@ -105,7 +105,7 @@ private void AlphaFS_Volume_GetVolumeInfo_UsingLogicalDrivePath(bool isNetwork) Assert.AreEqual(driveInfo2.DriveFormat, volInfo.FileSystemName); Assert.AreEqual(driveInfo2.Name, volInfo.FullPath); - if (logicalDrive.DriveType != System.IO.DriveType.Network) + if (driveInfo.DriveType != System.IO.DriveType.Network) { Assert.IsNotNull(volInfo.Guid); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs index b8161234f..c3cce6a3a 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs @@ -42,11 +42,11 @@ public void AlphaFS_Volume_GetXxx_Local_Success() var logicalDriveCount = 0; - foreach (var logicalDrive in System.IO.DriveInfo.GetDrives()) + foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\n", ++logicalDriveCount, logicalDrive.Name); + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\n", ++logicalDriveCount, driveInfo.Name); - if (logicalDrive.DriveType == System.IO.DriveType.CDRom) + if (driveInfo.DriveType == System.IO.DriveType.CDRom) { Console.WriteLine(); continue; @@ -57,7 +57,7 @@ public void AlphaFS_Volume_GetXxx_Local_Success() // GetVolumeDeviceName: "C:\" --> "\Device\HarddiskVolume4" - var deviceNameFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumeDeviceName(logicalDrive.Name); + var deviceNameFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumeDeviceName(driveInfo.Name); Console.WriteLine("\tGetVolumeDeviceName\t\t\t: [{0}]", deviceNameFromLogicalDrive); @@ -67,14 +67,14 @@ public void AlphaFS_Volume_GetXxx_Local_Success() // Skip mapped drives and network drives. - if (logicalDrive.DriveType != System.IO.DriveType.NoRootDirectory && logicalDrive.DriveType != System.IO.DriveType.Network) + if (driveInfo.DriveType != System.IO.DriveType.NoRootDirectory && driveInfo.DriveType != System.IO.DriveType.Network) { Assert.IsTrue(deviceNameFromLogicalDrive.StartsWith(deviceNamePrefix)); // GetVolumeGuid: "C:\" --> "\\?\Volume{db5044f9-bd1f-4243-ab97-4b985eb29e80}\" - var volumeGuidFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(logicalDrive.Name); + var volumeGuidFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(driveInfo.Name); Console.WriteLine("\tGetVolumeGuid\t\t\t\t: [{0}]", volumeGuidFromLogicalDrive); @@ -87,7 +87,7 @@ public void AlphaFS_Volume_GetXxx_Local_Success() // GetUniqueVolumeNameForPath: "C:\" --> "\\?\Volume{db5044f9-bd1f-4243-ab97-4b985eb29e80}\" - var uniqueVolumeNameFromlDriveInputPath = Alphaleonis.Win32.Filesystem.Volume.GetUniqueVolumeNameForPath(logicalDrive.Name); + var uniqueVolumeNameFromlDriveInputPath = Alphaleonis.Win32.Filesystem.Volume.GetUniqueVolumeNameForPath(driveInfo.Name); Console.WriteLine("\tGetUniqueVolumeNameForPath\t: [{0}]", uniqueVolumeNameFromlDriveInputPath); @@ -99,13 +99,13 @@ public void AlphaFS_Volume_GetXxx_Local_Success() // GetVolumePathName: "C:\" or "C:\Windows" --> "C:\" - var volumePathNameFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumePathName(logicalDrive.Name); + var volumePathNameFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumePathName(driveInfo.Name); Console.WriteLine("\tGetVolumePathName\t\t\t: [{0}]\n", volumePathNameFromLogicalDrive); Assert.IsNotNull(volumePathNameFromLogicalDrive); - Assert.AreEqual(logicalDrive.Name, volumePathNameFromLogicalDrive); + Assert.AreEqual(driveInfo.Name, volumePathNameFromLogicalDrive); } if (logicalDriveCount == 0) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/DriveInfo.GetDrives.cs b/AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/DriveInfo.GetDrives.cs index 7e001dce5..ca6cca1dc 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/DriveInfo.GetDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/DriveInfo.GetDrives.cs @@ -34,28 +34,16 @@ public partial class DriveInfoTest public void DriveInfo_GetDrives_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); - - - var drives = Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives().ToList(); - - foreach (var driveInfo in drives) - { - Console.WriteLine("Logical Drive: [{0}]", driveInfo.Name); - - UnitTestConstants.Dump(driveInfo); + var drivesSystemIO = System.IO.DriveInfo.GetDrives().Select(drive => drive.Name).ToArray(); - if (null != driveInfo.DiskSpaceInfo) - UnitTestConstants.Dump(driveInfo.DiskSpaceInfo, true); + var drivesAlphaFS = Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives().Select(drive => drive.Name).ToArray(); + foreach (var drivePath in drivesAlphaFS) + Console.WriteLine("Logical Drive: [{0}]\n", drivePath); + - Console.WriteLine(); - } - - - Assert.IsTrue(drives.Count > 0); - - Assert.AreEqual(drives[0].Name[0], UnitTestConstants.SysDrive[0]); + CollectionAssert.AreEqual(drivesSystemIO, drivesAlphaFS); } } } diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs index 35da9f84b..f20ae16bf 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs @@ -41,7 +41,7 @@ private void AlphaFS_Directory_GetFileSystemEntryInfo_LogicalDrives() { UnitTestConstants.PrintUnitTestHeader(false); - var drives = Alphaleonis.Win32.Filesystem.DriveInfo.GetDrives().ToArray(); + var drives = System.IO.DriveInfo.GetDrives().ToArray(); foreach (var driveInfo in drives) { From 243735c902766c0ad8fabee1aee121e2918d8d02 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 9 Jun 2018 14:09:33 +0200 Subject: [PATCH 094/133] Updated changelog. --- AlphaFS/Filesystem/Directory Class/Directory.Copy.cs | 2 +- CHANGELOG.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs index ab110206a..35eec6679 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs @@ -814,7 +814,7 @@ private static CopyMoveResult CopyDeleteDirectoryCore(KernelTransaction transact { var fileParentFolder = Path.GetLongPathCore(parentFolder.FullName, GetFullPathOptions.None); - CreateDirectoryCore(transaction, fileParentFolder, null, null, false, PathFormat.LongFullPath); + CreateDirectoryCore(true, transaction, fileParentFolder, null, null, false, PathFormat.LongFullPath); } diff --git a/CHANGELOG.md b/CHANGELOG.md index d3d06f1c3..eee2a864e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ Version 2.3 (2018-XX-XX) ### Improvements - Issue #426: Correct casing of enum `STREAM_ATTRIBUTES` +- Issue #459: Modify method `Directory.CreateDirectoryCore` to return null as well as DirectoryInfo instance. ### Breaking Changes From 63cc0e101f36789fc29c73d0809acafff60dd1c1 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 9 Jun 2018 23:28:43 +0200 Subject: [PATCH 095/133] Code improvement. --- ...DiskInfo_UsingDevicePathFromSystemDrive.cs | 3 + ...tPhysicalDiskInfo_UsingLogicalDrivePath.cs | 114 ++++++++++++++ ...DiskInfo_UsingVolumePathFromSystemDrive.cs | 22 ++- ...pterInfo_UsingDevicePathFromSystemDrive.cs | 64 ++++++++ ...torageAdapterInfo_UsingLogicalDrivePath.cs | 2 +- ...terInfo_UsingVolumePathFromSystemDrive.cs} | 28 ++-- ...StorageDeviceInfo_UsingLogicalDrivePath.cs | 2 +- ...ragePartitionInfo_UsingLogicalDrivePath.cs | 2 +- ...ry.GetFileSystemEntryInfo_LogicalDrives.cs | 2 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 4 +- AlphaFS.sln | 1 - AlphaFS/Device/Device.Local.cs | 3 + .../Local.EnumeratePhysicalDisks.cs | 145 ++++++++++-------- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 26 ++-- .../Storage/Device.StoragePartitionInfo.cs | 15 +- .../Storage/Local.GetStorageAdapterInfo.cs | 30 ++-- .../Storage/Local.GetStorageDeviceInfo.cs | 55 +++---- .../Storage/Local.GetStoragePartitionInfo.cs | 2 +- AlphaFS/Filesystem/File Class/File.Create.cs | 2 +- .../File Class/File.GetAccessControl.cs | 10 +- .../File Class/File.GetCompressedSize.cs | 2 +- .../File Class/File.GetEncryptionStatus.cs | 4 +- AlphaFS/Filesystem/File Class/File.Open.cs | 2 +- .../File Class/File.OpenBackupRead.cs | 2 +- AlphaFS/Filesystem/Shell32Info.cs | 2 +- .../Structures, Enumerations/FileIdInfo.cs | 4 +- AlphaFS/OperatingSystem/IsAtLeast.cs | 4 +- CHANGELOG.md | 1 + 28 files changed, 380 insertions(+), 173 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs => AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs} (67%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs index 1dc807cae..b19fb49d3 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs @@ -58,6 +58,9 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive_Su Console.WriteLine(); + Assert.IsNull(pDisk.StoragePartitionInfo); + + Assert.IsNotNull(pDisk); Assert.IsNotNull(pDisk.LogicalDrives); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs new file mode 100644 index 000000000..6c8380cc5 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs @@ -0,0 +1,114 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_PhysicalDiskInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePath_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + var driveCount = 0; + + foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) + { + // Works with System.IO.DriveType.CDRom. + + // System.UnauthorizedAccessException: (5) Access is denied. + if (driveInfo.DriveType == System.IO.DriveType.Network) + { + Console.WriteLine("#{0:000}\tSkipped Network drive: [{1}]\n", ++driveCount, driveInfo.Name); + continue; + } + + if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) + { + Console.WriteLine("#{0:000}\tSkipped NoRootDirectory drive: [{1}]\n", ++driveCount, driveInfo.Name); + continue; + } + + + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(driveInfo.Name); + + + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, pDisk.StorageAdapterInfo.ToString()); + + UnitTestConstants.Dump(pDisk); + + UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); + + UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + + UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + + + Assert.IsNotNull(pDisk); + + Assert.IsNotNull(pDisk.LogicalDrives); + + Assert.IsNotNull(pDisk.VolumeGuids); + + + if (pDisk.StorageDeviceInfo.PartitionNumber == -1) + Assert.IsNull(pDisk.StoragePartitionInfo); + else + Assert.IsNotNull(pDisk.StoragePartitionInfo); + + + // For CDRom, the PartitionNumber is always -1. + + if (pDisk.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) + Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + else + Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + + + Assert.AreEqual(pDisk.LogicalDrives.Contains(driveInfo.Name.TrimEnd('\\'), StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(driveInfo.Name)); + + + // Show all partition information. + + if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) + { + foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, true); + } + + if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) + { + foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, true); + } + + Console.WriteLine(); + } + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs index a4b96e32e..67925160a 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs @@ -46,7 +46,7 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Su var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); - Console.WriteLine("#{0:000}\tInput Volume: [{1}]\t\t{2}\t\t{3}", ++volumeCount, sourceVolume, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]\t\t{2}\t\t{3}", ++volumeCount, sourceVolume, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); UnitTestConstants.Dump(pDisk); @@ -56,8 +56,7 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Su UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); - Console.WriteLine(); - + Assert.IsNotNull(pDisk); @@ -70,6 +69,23 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Su Assert.AreEqual(pDisk.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceDrive)); Assert.AreEqual(pDisk.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceVolume)); + + + // Show all partition information. + + if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) + { + foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, true); + } + + if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) + { + foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, true); + } + + Console.WriteLine(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs new file mode 100644 index 000000000..e5639f654 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs @@ -0,0 +1,64 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_GetStorageAdapterInfo_UsingDevicePathFromSystemDrive_Success() + { + UnitTestAssert.IsElevatedProcess(); + UnitTestConstants.PrintUnitTestHeader(false); + + + var deviceCount = 0; + + var sourceDrive = UnitTestConstants.SysDrive; + var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; + + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); + + + Console.WriteLine("#{0:000}\tInput Device Path: [{1}]\t\t{2}", ++deviceCount, devicePath, pDisk.StorageAdapterInfo.ToString()); + + + var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(devicePath); + + + UnitTestConstants.Dump(storageAdapterInfo); + + Assert.IsNotNull(storageAdapterInfo); + + Assert.IsNotNull(pDisk); + + Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + + Assert.AreEqual(storageAdapterInfo, pDisk.StorageAdapterInfo); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs index 4a059eb0c..2bcd824ef 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs @@ -59,7 +59,7 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingLogicalDrivePath_Success() var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(driveInfo.Name); - Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageAdapterInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageAdapterInfo.ToString()); UnitTestConstants.Dump(storageAdapterInfo); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs similarity index 67% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs index 8dc5708fe..64bcb233c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs @@ -20,7 +20,6 @@ */ using System; -using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -31,39 +30,36 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePathFromSystemDrive_Success() + public void AlphaFS_Device_GetStorageAdapterInfo_UsingVolumePathFromSystemDrive_Success() { + UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); - - var driveCount = 0; + + var volumeCount = 0; var sourceDrive = UnitTestConstants.SysDrive; - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive); + var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}\t\t{3}", ++driveCount, sourceDrive, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); - UnitTestConstants.Dump(pDisk); + Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]\t\t{2}", ++volumeCount, sourceVolume, pDisk.StorageAdapterInfo.ToString()); - UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); - UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(sourceVolume); - UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); - Console.WriteLine(); + + UnitTestConstants.Dump(storageAdapterInfo); + Assert.IsNotNull(storageAdapterInfo); Assert.IsNotNull(pDisk); - Assert.IsNotNull(pDisk.LogicalDrives); - - Assert.IsNotNull(pDisk.VolumeGuids); - Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(pDisk.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceDrive)); + Assert.AreEqual(storageAdapterInfo, pDisk.StorageAdapterInfo); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs index 472bcb73b..69df2f322 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs @@ -58,7 +58,7 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingLogicalDrivePath_Success() var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(driveInfo.Name); - Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageDeviceInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageDeviceInfo.ToString()); UnitTestConstants.Dump(storageDeviceInfo); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs index 467b56044..eb8a8734e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs @@ -68,7 +68,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingLogicalDrivePath_Success Assert.IsNotNull(storagePartitionInfo); - Console.WriteLine("#{0:000}\tInput Logical Drive: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storagePartitionInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storagePartitionInfo.ToString()); UnitTestConstants.Dump(storagePartitionInfo); diff --git a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs index f20ae16bf..771219da1 100644 --- a/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs +++ b/AlphaFS.UnitTest/AlphaFS FileSystemEntryInfo Class/AlphaFS_Directory.GetFileSystemEntryInfo_LogicalDrives.cs @@ -45,7 +45,7 @@ private void AlphaFS_Directory_GetFileSystemEntryInfo_LogicalDrives() foreach (var driveInfo in drives) { - Console.WriteLine("Input Logical Drive: [{0}]", driveInfo.Name); + Console.WriteLine("Input Logical Drive Path: [{0}]", driveInfo.Name); try { diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 4dcecfdfc..0e69d8aaf 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -145,8 +145,10 @@ - + + + diff --git a/AlphaFS.sln b/AlphaFS.sln index d475c8ee2..1623affa5 100644 --- a/AlphaFS.sln +++ b/AlphaFS.sln @@ -11,7 +11,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution AlphaFS.vsmdi = AlphaFS.vsmdi BuildRelease.proj = BuildRelease.proj CHANGELOG.md = CHANGELOG.md - AlphaFS\Device\Filesystem\Device.Filesystem.cs = AlphaFS\Device\Filesystem\Device.Filesystem.cs LICENSE.md = LICENSE.md README.md = README.md EndProjectSection diff --git a/AlphaFS/Device/Device.Local.cs b/AlphaFS/Device/Device.Local.cs index 0f7a84500..06e2c9186 100644 --- a/AlphaFS/Device/Device.Local.cs +++ b/AlphaFS/Device/Device.Local.cs @@ -19,10 +19,13 @@ * THE SOFTWARE. */ +using System.IO; + namespace Alphaleonis.Win32.Device { /// [AlphaFS] Provides static methods to retrieve device resource information from the local host. public static partial class Local { + internal static DriveType[] ValidDriveTypes = {DriveType.CDRom, DriveType.Fixed, DriveType.Removable}; } } diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index e6dfa433b..4f144c3df 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; @@ -34,7 +35,7 @@ namespace Alphaleonis.Win32.Device public static partial class Local { /// [AlphaFS] Enumerates the physical disks on the Computer, populated with volume- and logical drive information. - /// Returns an collection that represents the physical disks on the Computer. + /// Returns an collection that represents the physical disks on the Computer. [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() { @@ -42,22 +43,40 @@ public static IEnumerable EnumeratePhysicalDisks() } - - - /// [AlphaFS] Enumerates the physical disks on the Computer, populated with volume- and logical drive information. - /// Returns an collection that represents the physical disks on the Computer. + /// [AlphaFS] Enumerates the physical disks of type on the Computer, populated with volume- and logical drive information. + /// Returns an collection that represents the physical disks on the Computer. + /// >One or more of the values. + [SecurityCritical] + public static IEnumerable EnumeratePhysicalDisks(DriveType[] driveTypes) + { + if (null == driveTypes) + throw new ArgumentNullException("driveTypes"); + + return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess, driveTypes); + } + + + /// [AlphaFS] Enumerates the physical disks of type on the Computer, populated with volume- and logical drive information. + /// Returns an collection that represents the physical disks on the Computer. + /// true indicates the current process is in an elevated state, allowing to retrieve more data. + /// >One or more of the values. [SecurityCritical] - internal static IEnumerable EnumeratePhysicalDisksCore(bool isElevated) + internal static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, DriveType[] driveTypes = null) { - var physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDiskInfoCore(isElevated, null, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + if (null == driveTypes) + driveTypes = new[] {DriveType.CDRom, DriveType.Fixed, DriveType.Removable}; - var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDiskInfoCore(false, volumeGuid, null, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + var physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDiskInfoCore(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + + //var pVolumeGuids = EnumerateDevicesCore(null, DeviceGuid.Volume, false).Select(deviceInfo => GetPhysicalDiskInfoCore(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDiskInfoCore(false, volumeGuid, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false) - .Select(driveName => new DriveInfo(driveName)).Where(driveInfo => driveInfo.DriveType == DriveType.CDRom || driveInfo.DriveType == DriveType.Fixed || driveInfo.DriveType == DriveType.Removable) - - .Select(driveInfo => GetPhysicalDiskInfoCore(false, driveInfo.Name, null, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + .Select(driveName => new DriveInfo(driveName)).Where(driveInfo => {return driveTypes.Any(drive => driveInfo.DriveType == drive);}) + + .Select(driveInfo => GetPhysicalDiskInfoCore(false, driveInfo.Name, null)).Where(physicalDisk => null != physicalDisk).ToArray(); foreach (var pDisk in physicalDisks) @@ -65,27 +84,43 @@ internal static IEnumerable EnumeratePhysicalDisksCore(bool is yield return PopulatePhysicalDisk(pDisk, pVolumeGuids, pLogicalDrives); - // Windows Disk Management shows CD-ROM so mimic that behaviour. + //// Windows Disk Management shows CD-ROM so mimic that behaviour. - var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => GetPhysicalDiskInfoCore(isElevated, null, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + //var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => GetPhysicalDiskInfoCore(isElevated, null, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); - foreach (var pCdRom in cdRoms) + //foreach (var pCdRom in cdRoms) - yield return PopulatePhysicalCDRom(pCdRom, pVolumeGuids, pLogicalDrives); + // yield return PopulatePhysicalCDRom(pCdRom, pVolumeGuids, pLogicalDrives); } + - - private static void PopulateLogicalDriveDetails(PhysicalDiskInfo pDiskInfo, string drivePath) + private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, PhysicalDiskInfo[] pVolumes, PhysicalDiskInfo[] pLogicalDrives) { - // Add device logical drive. + var pDiskInfo = new PhysicalDiskInfo(pDisk); - if (null == pDiskInfo.LogicalDrives) - pDiskInfo.LogicalDrives = new Collection(); - pDiskInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(drivePath)); - } + foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber)) + { + var volumeDriveNumber = pVolume.StorageDeviceInfo.DeviceNumber; + + var volumePartitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; + + + PopulateVolumeDetails(pDiskInfo, volumePartitionNumber, pVolume.DevicePath); + // Get logical drive from volume matching DeviceNumber and PartitionNumber. + + foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == volumeDriveNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == volumePartitionNumber)) + + PopulateLogicalDriveDetails(pDiskInfo, pLogicalDrive.DevicePath); + } + + + return pDiskInfo; + } + + private static void PopulateVolumeDetails(PhysicalDiskInfo pDiskInfo, int partitionNumber, string volumeGuid) { //// Add device volume labels. @@ -104,7 +139,7 @@ private static void PopulateVolumeDetails(PhysicalDiskInfo pDiskInfo, int partit pDiskInfo.PartitionIndexes.Add(partitionNumber); - // Add device volume s. + // Add device volume GUIDs. if (null == pDiskInfo.VolumeGuids) pDiskInfo.VolumeGuids = new Collection(); @@ -113,65 +148,41 @@ private static void PopulateVolumeDetails(PhysicalDiskInfo pDiskInfo, int partit } - private static PhysicalDiskInfo PopulatePhysicalCDRom(PhysicalDiskInfo pCdRom, PhysicalDiskInfo[] pVolumes, PhysicalDiskInfo[] pLogicalDrives) + private static void PopulateLogicalDriveDetails(PhysicalDiskInfo pDiskInfo, string drivePath) { - var pDiskInfo = new PhysicalDiskInfo(pCdRom) - { - StorageDeviceInfo = pCdRom.StorageDeviceInfo, - StoragePartitionInfo = pCdRom.StoragePartitionInfo - }; - - - // Get volume from CDRom matching DeviceNumber. - - var pVolume = pVolumes.SingleOrDefault(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber && pVol.StorageDeviceInfo.PartitionNumber == pDiskInfo.StorageDeviceInfo.PartitionNumber); - - if (null != pVolume) - { - PopulateVolumeDetails(pDiskInfo, pVolume.StorageDeviceInfo.PartitionNumber, pVolume.DevicePath); - - - // Get logical drive from CDRom matching DeviceNumber and PartitionNumber. - - var pLogicalDrive = pLogicalDrives.SingleOrDefault(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pVolume.StorageDeviceInfo.PartitionNumber); - - if (null != pLogicalDrive) - PopulateLogicalDriveDetails(pDiskInfo, pLogicalDrive.DevicePath); - } + // Add device logical drive. + if (null == pDiskInfo.LogicalDrives) + pDiskInfo.LogicalDrives = new Collection(); - return pDiskInfo; + pDiskInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(drivePath)); } - private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, PhysicalDiskInfo[] pVolumes, PhysicalDiskInfo[] pLogicalDrives) - { - var pDiskInfo = new PhysicalDiskInfo(pDisk) - { - StorageDeviceInfo = pDisk.StorageDeviceInfo, - StoragePartitionInfo = pDisk.StoragePartitionInfo - }; - + //private static PhysicalDiskInfo PopulatePhysicalCDRom(PhysicalDiskInfo pCdRom, PhysicalDiskInfo[] pVolumes, PhysicalDiskInfo[] pLogicalDrives) + //{ + // var pDiskInfo = new PhysicalDiskInfo(pCdRom); - foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber)) - { - var volumeDriveNumber = pVolume.StorageDeviceInfo.DeviceNumber; - var volumePartitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; + // // Get volume from CDRom matching DeviceNumber. + // var pVolume = pVolumes.SingleOrDefault(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber && pVol.StorageDeviceInfo.PartitionNumber == pDiskInfo.StorageDeviceInfo.PartitionNumber); - PopulateVolumeDetails(pDiskInfo, volumePartitionNumber, pVolume.DevicePath); + // if (null != pVolume) + // { + // PopulateVolumeDetails(pDiskInfo, pVolume.StorageDeviceInfo.PartitionNumber, pVolume.DevicePath); - // Get logical drive from volume matching DeviceNumber and PartitionNumber. + // // Get logical drive from CDRom matching DeviceNumber and PartitionNumber. - foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == volumeDriveNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == volumePartitionNumber)) + // var pLogicalDrive = pLogicalDrives.SingleOrDefault(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pVolume.StorageDeviceInfo.PartitionNumber); - PopulateLogicalDriveDetails(pDiskInfo, pLogicalDrive.DevicePath); - } + // if (null != pLogicalDrive) + // PopulateLogicalDriveDetails(pDiskInfo, pLogicalDrive.DevicePath); + // } - return pDiskInfo; - } + // return pDiskInfo; + //} } } diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index 04076e143..e40da336f 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -36,7 +36,7 @@ public static partial class Local /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks, associated volumes and logical drives. - /// Instead, use method and property and/or . + /// Instead, use method and property and/or . /// /// /// @@ -64,6 +64,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) if (null == storageDeviceInfo) return null; + if (isDrive) // Use logical drive path. @@ -84,7 +85,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) if (null != pDiskInfo) { - // Use the storageDeviceInfo created earlier using validatedDevicePath. + // Use the storageDeviceInfo instance created earlier because it is based on the input path. pDiskInfo.StorageDeviceInfo = storageDeviceInfo; @@ -92,6 +93,10 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) // Accessing the device by its path: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} // does not relate to any drive or volume, so the default PartitionNumber of 0 is misleading. pDiskInfo.StorageDeviceInfo.PartitionNumber = -1; + + + if (null == pDiskInfo.StoragePartitionInfo) + pDiskInfo.StoragePartitionInfo = GetStoragePartitionInfo(validatedDevicePath); } @@ -104,7 +109,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks, associated volumes and logical drives. - /// Instead, use method and property and/or . + /// Instead, use method and property and/or . /// /// /// @@ -112,17 +117,16 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) /// /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// - /// A instance. /// A instance. /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) + internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string devicePath, DeviceInfo deviceInfo) { var isDeviceInfo = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); @@ -130,8 +134,7 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string devicePath = deviceInfo.DevicePath; - if (null == storageDeviceInfo) - storageDeviceInfo = GetStorageDeviceInfoCore(false, devicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, devicePath); if (null == storageDeviceInfo) return null; @@ -164,6 +167,7 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string } + // Use the storageDeviceInfo instance created earlier because it is based on the input path. pDiskInfo.StorageDeviceInfo = storageDeviceInfo; diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index bd55c143e..48f29fa6e 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -117,19 +117,12 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis PartitionCount = MbrPartitionInfo.Count; break; - - - default: - Console.WriteLine(PartitionStyle.ToString()); - break; } - IsOnDynamicDisk = null != GptPartitionInfo && GptPartitionInfo.Any(partition => - - partition.PartitionType == PartitionType.LdmData || partition.PartitionType == PartitionType.LdmMetadata) || + OnDynamicDisk = null != GptPartitionInfo && GptPartitionInfo.Any(partition => partition.PartitionType == PartitionType.LdmData || partition.PartitionType == PartitionType.LdmMetadata) || - null != MbrPartitionInfo && MbrPartitionInfo.Any(partition => partition.DiskPartitionType == DiskPartitionType.Ldm); + null != MbrPartitionInfo && MbrPartitionInfo.Any(partition => partition.DiskPartitionType == DiskPartitionType.Ldm); } #endregion // Constructors @@ -211,7 +204,7 @@ public string GptUsableLengthUnitSize /// true if the partition is on a dynamic disk. - public bool IsOnDynamicDisk { get; private set; } + public bool OnDynamicDisk { get; private set; } /// Contains partition information specific to master boot record (MBR) disks. @@ -238,7 +231,7 @@ public string GptUsableLengthUnitSize /// The total size of the storage partition. public long TotalSize { get; private set; } - + #if DEBUG /// diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index 8d4b944a4..48a42ba56 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -77,31 +77,31 @@ private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle saf using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) { - if (null == safeBuffer) - { - // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + //if (null == safeBuffer) + //{ + // // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle, pathToDevice); + // var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle, pathToDevice); - if (volDiskExtents.HasValue) - { - // Use the first disk extent. + // if (volDiskExtents.HasValue) + // { + // // Use the first disk extent. - pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); + // pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - safeHandleRetry = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); + // safeHandleRetry = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); - isRetry = Utils.IsValidHandle(safeHandleRetry, false); - } + // isRetry = Utils.IsValidHandle(safeHandleRetry, false); + // } - if (isRetry) - goto StartGetData; + // if (isRetry) + // goto StartGetData; - return null; - } + // return null; + //} if (isRetry && !safeHandleRetry.IsClosed) diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index 7b4775bf0..da8cb4d0a 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -90,24 +90,24 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri { var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); - if (null == safeBuffer) - { - // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + //if (null == safeBuffer) + //{ + // // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - var volDiskExtents = GetVolumeDiskExtents(safeHandle, pathToDevice); + // var volDiskExtents = GetVolumeDiskExtents(safeHandle, pathToDevice); - if (volDiskExtents.HasValue) - { - // Use the first disk extent. + // if (volDiskExtents.HasValue) + // { + // // Use the first disk extent. - pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); + // pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - goto StartGetData; - } - } + // goto StartGetData; + // } + //} - else + //else using (safeBuffer) storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure()); } @@ -147,31 +147,31 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) { - if (null == safeBuffer) - { - // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. + //if (null == safeBuffer) + //{ + // // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle, pathToDevice); + // var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle, pathToDevice); - if (volDiskExtents.HasValue) - { - // Use the first disk extent. + // if (volDiskExtents.HasValue) + // { + // // Use the first disk extent. - pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); + // pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - safeHandleRetry = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); + // safeHandleRetry = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); - isRetry = Utils.IsValidHandle(safeHandleRetry, false); - } + // isRetry = Utils.IsValidHandle(safeHandleRetry, false); + // } - if (isRetry) - goto StartGetData; + // if (isRetry) + // goto StartGetData; - return null; - } + // return null; + //} var deviceDescriptor = safeBuffer.PtrToStructure(); @@ -221,6 +221,7 @@ private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeH if (isRetry && !safeHandleRetry.IsClosed) safeHandleRetry.Close(); + return newStorageDeviceInfo; } } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 4f14fd710..fa4bd25ea 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -87,7 +87,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle // Use the first disk extent. var diskNumber = volDiskExtents.Value.Extents[0].DiskNumber; - return new StoragePartitionInfo((int)diskNumber, disk, layout, partitions); + return new StoragePartitionInfo((int) diskNumber, disk, layout, partitions); } } diff --git a/AlphaFS/Filesystem/File Class/File.Create.cs b/AlphaFS/Filesystem/File Class/File.Create.cs index df1bc4c56..c12c7847e 100644 --- a/AlphaFS/Filesystem/File Class/File.Create.cs +++ b/AlphaFS/Filesystem/File Class/File.Create.cs @@ -254,7 +254,7 @@ public static FileStream CreateTransacted(KernelTransaction transaction, string /// The option controls how you would like to share created file with other requesters. /// Indicates the format of the parameter. /// The number of bytes buffered for reads and writes to the file. - /// Returns a that provides read/write access to the file specified in path. + /// Returns a that provides read/write access to the file specified in path. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive")] [SecurityCritical] diff --git a/AlphaFS/Filesystem/File Class/File.GetAccessControl.cs b/AlphaFS/Filesystem/File Class/File.GetAccessControl.cs index 84f8b1838..ae8b2e912 100644 --- a/AlphaFS/Filesystem/File Class/File.GetAccessControl.cs +++ b/AlphaFS/Filesystem/File Class/File.GetAccessControl.cs @@ -32,7 +32,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class File { /// Gets a object that encapsulates the access control list (ACL) entries for a specified file. - /// Returns a object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -44,7 +44,7 @@ public static FileSecurity GetAccessControl(string path) } /// Gets a object that encapsulates the access control list (ACL) entries for a specified file. - /// Returns a object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -58,7 +58,7 @@ public static FileSecurity GetAccessControl(string path, AccessControlSections i /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for a specified file. - /// Returns a object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -86,7 +86,7 @@ public static FileSecurity GetAccessControl(string path, AccessControlSections i /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for a specified file handle. - /// Returns a object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// @@ -98,7 +98,7 @@ public static FileSecurity GetAccessControl(SafeFileHandle handle) } /// [AlphaFS] Gets a object that encapsulates the access control list (ACL) entries for a specified file handle. - /// Returns a object that encapsulates the access control rules for the file described by the parameter. + /// Returns a object that encapsulates the access control rules for the file described by the parameter. /// /// /// diff --git a/AlphaFS/Filesystem/File Class/File.GetCompressedSize.cs b/AlphaFS/Filesystem/File Class/File.GetCompressedSize.cs index 534a029a2..f208c1f97 100644 --- a/AlphaFS/Filesystem/File Class/File.GetCompressedSize.cs +++ b/AlphaFS/Filesystem/File Class/File.GetCompressedSize.cs @@ -102,7 +102,7 @@ public static long GetCompressedSizeTransacted(KernelTransaction transaction, st /// The transaction. /// The name of the file. /// Indicates the format of the path parameter(s). - /// The actual number of bytes of disk storage used to store the specified file. + /// The actual number of bytes of disk storage used to store the specified file. [SecurityCritical] internal static long GetCompressedSizeCore(KernelTransaction transaction, string path, PathFormat pathFormat) { diff --git a/AlphaFS/Filesystem/File Class/File.GetEncryptionStatus.cs b/AlphaFS/Filesystem/File Class/File.GetEncryptionStatus.cs index 29d9ddfda..9489127bb 100644 --- a/AlphaFS/Filesystem/File Class/File.GetEncryptionStatus.cs +++ b/AlphaFS/Filesystem/File Class/File.GetEncryptionStatus.cs @@ -30,7 +30,7 @@ public static partial class File /// [AlphaFS] Retrieves the encryption status of the specified file. /// The name of the file. /// Indicates the format of the path parameter(s). - /// The of the specified . + /// The of the specified . [SecurityCritical] public static FileEncryptionStatus GetEncryptionStatus(string path, PathFormat pathFormat) { @@ -40,7 +40,7 @@ public static FileEncryptionStatus GetEncryptionStatus(string path, PathFormat p /// [AlphaFS] Retrieves the encryption status of the specified file. /// The name of the file. - /// The of the specified . + /// The of the specified . [SecurityCritical] public static FileEncryptionStatus GetEncryptionStatus(string path) { diff --git a/AlphaFS/Filesystem/File Class/File.Open.cs b/AlphaFS/Filesystem/File Class/File.Open.cs index 01d0a30fb..d96f615b8 100644 --- a/AlphaFS/Filesystem/File Class/File.Open.cs +++ b/AlphaFS/Filesystem/File Class/File.Open.cs @@ -212,7 +212,7 @@ public static FileStream Open(string path, FileMode mode, FileAccess access, Fil /// /// A on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. - /// + /// [SecurityCritical] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes) { diff --git a/AlphaFS/Filesystem/File Class/File.OpenBackupRead.cs b/AlphaFS/Filesystem/File Class/File.OpenBackupRead.cs index 683bf2f82..fbf212831 100644 --- a/AlphaFS/Filesystem/File Class/File.OpenBackupRead.cs +++ b/AlphaFS/Filesystem/File Class/File.OpenBackupRead.cs @@ -39,7 +39,7 @@ public static FileStream OpenBackupRead(string path, PathFormat pathFormat) /// [AlphaFS] Opens the specified file for reading purposes bypassing security attributes. This method is simpler to use then BackupFileStream to read only file's data stream. /// The file path to open. - /// Returns a on the specified path, having the read-only mode and sharing options. + /// Returns a on the specified path, having the read-only mode and sharing options. [SecurityCritical] public static FileStream OpenBackupRead(string path) { diff --git a/AlphaFS/Filesystem/Shell32Info.cs b/AlphaFS/Filesystem/Shell32Info.cs index 1423941de..be72f1c6d 100644 --- a/AlphaFS/Filesystem/Shell32Info.cs +++ b/AlphaFS/Filesystem/Shell32Info.cs @@ -155,7 +155,7 @@ public void Refresh() /// Returns the path as a string. - /// The path. + /// The path. public override string ToString() { return FullPath; diff --git a/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs b/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs index ccd895574..df8ee73fc 100644 --- a/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs +++ b/AlphaFS/Filesystem/Structures, Enumerations/FileIdInfo.cs @@ -71,7 +71,7 @@ private static void ArrayToLong(byte[] fileId, int startIndex, int count, out lo /// 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. /// An object to compare with this instance. - /// 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 in the sort order. Zero This instance occurs in the same position in the sort order as . Greater than zero This instance follows in the sort order. + /// 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 in the sort order. Zero This instance occurs in the same position in the sort order as . Greater than zero This instance follows in the sort order. public int CompareTo(object obj) { if (null == obj) @@ -86,7 +86,7 @@ public int CompareTo(object obj) /// Compares the current object with another object of the same type. /// An object to compare with this object. - /// 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 parameter.Zero This object is equal to . Greater than zero This object is greater than . + /// 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 parameter.Zero This object is equal to . Greater than zero This object is greater than . public int CompareTo(FileIdInfo other) { return _volumeSerialNumber != other._volumeSerialNumber diff --git a/AlphaFS/OperatingSystem/IsAtLeast.cs b/AlphaFS/OperatingSystem/IsAtLeast.cs index 14f0ac382..e991a4c2b 100644 --- a/AlphaFS/OperatingSystem/IsAtLeast.cs +++ b/AlphaFS/OperatingSystem/IsAtLeast.cs @@ -25,7 +25,7 @@ namespace Alphaleonis.Win32 public static partial class OperatingSystem { /// [AlphaFS] Determines whether the operating system is of the specified version or later. - /// true if the operating system is of the specified or later; otherwise, false. + /// true if the operating system is of the specified or later; otherwise, false. /// The lowest version for which to return true. public static bool IsAtLeast(EnumOsName version) { @@ -34,7 +34,7 @@ public static bool IsAtLeast(EnumOsName version) /// [AlphaFS] Determines whether the operating system is of the specified version or later, allowing specification of a minimum service pack that must be installed on the lowest version. - /// true if the operating system matches the specified with the specified service pack, or if the operating system is of a later version; otherwise, false. + /// true if the operating system matches the specified with the specified service pack, or if the operating system is of a later version; otherwise, false. /// The minimum required version. /// The major version of the service pack that must be installed on the minimum required version to return true. This can be 0 to indicate that no service pack is required. public static bool IsAtLeast(EnumOsName version, int servicePackVersion) diff --git a/CHANGELOG.md b/CHANGELOG.md index eee2a864e..471d4897e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ Version 2.3 (2018-XX-XX) Version 2.2.3 (2018-XX-XX) +------------- ### Bugs Fixed From 34b5a3de87ff5acf59bb8c84b647218785695c39 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 10 Jun 2018 03:12:50 +0200 Subject: [PATCH 096/133] Code improvement. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 24 +++ ...tPhysicalDiskInfo_UsingLogicalDrivePath.cs | 11 ++ ...DiskInfo_UsingVolumePathFromSystemDrive.cs | 8 +- ...pterInfo_UsingVolumePathFromSystemDrive.cs | 4 +- ...viceInfo_UsingDevicePathFromSystemDrive.cs | 64 +++++++ ...StorageDeviceInfo_UsingLogicalDrivePath.cs | 9 + ...viceInfo_UsingVolumePathFromSystemDrive.cs | 65 +++++++ ...ngDevicePathFromSystemDrive_ReturnsNull.cs | 51 ++++++ ...ragePartitionInfo_UsingLogicalDrivePath.cs | 2 + ...tionInfo_UsingVolumePathFromSystemDrive.cs | 65 +++++++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 4 + AlphaFS/Device/Device.Local.cs | 3 - AlphaFS/Device/DriveInfo/DriveInfo.cs | 2 +- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 36 ++-- .../Storage/Device.StorageAdapterInfo.cs | 9 +- .../Storage/Device.StorageDeviceInfo.cs | 19 +- .../Storage/Device.StorageGptPartitionInfo.cs | 22 ++- .../Storage/Device.StorageMbrPartitionInfo.cs | 25 ++- .../Storage/Device.StoragePartitionInfo.cs | 163 ++++++++++-------- .../Storage/Local.GetStorageDeviceInfo.cs | 12 +- AlphaFS/Filesystem/DiskSpaceInfo.cs | 2 +- 21 files changed, 473 insertions(+), 127 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index cab66b780..7569e26ec 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -35,10 +35,13 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); + var gotDisk = false; var pDriveCount = 0; + var pDrives = Alphaleonis.Win32.Device.Local.EnumeratePhysicalDisks().OrderBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber).ThenBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.PartitionNumber).ToArray(); + foreach (var pDisk in pDrives) { Console.WriteLine("#{0:000}\tPhysical Disk: [{1}]\t\t{2}\t\t{3}", ++pDriveCount, pDisk.StorageDeviceInfo.DeviceNumber, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); @@ -51,7 +54,28 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Local_Success() UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + + // Show all partition information. + + if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) + { + gotDisk = true; + + foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, true); + } + + if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) + { + gotDisk = true; + + foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, true); + } + Console.WriteLine(); + + //Assert.IsTrue(gotDisk); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs index 6c8380cc5..990ade173 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs @@ -35,6 +35,7 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePath_Success() { UnitTestConstants.PrintUnitTestHeader(false); + var gotDisk = false; var driveCount = 0; foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) @@ -85,7 +86,11 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePath_Success() // For CDRom, the PartitionNumber is always -1. if (pDisk.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) + { Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.CDRom, pDisk.StorageDeviceInfo.DeviceType); + } + else Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); @@ -97,17 +102,23 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePath_Success() if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) { + gotDisk = true; + foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) UnitTestConstants.Dump(partition, true); } if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) { + gotDisk = true; + foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) UnitTestConstants.Dump(partition, true); } Console.WriteLine(); + + Assert.IsTrue(gotDisk); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs index 67925160a..b8639bdd8 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs @@ -35,7 +35,7 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Su { UnitTestConstants.PrintUnitTestHeader(false); - + var gotDisk = false; var volumeCount = 0; var sourceDrive = UnitTestConstants.SysDrive; @@ -75,17 +75,23 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Su if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) { + gotDisk = true; + foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) UnitTestConstants.Dump(partition, true); } if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) { + gotDisk = true; + foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) UnitTestConstants.Dump(partition, true); } Console.WriteLine(); + + Assert.IsTrue(gotDisk); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs index 64bcb233c..33fd487fb 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs @@ -58,8 +58,8 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingVolumePathFromSystemDrive_ Assert.IsNotNull(pDisk); Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - - Assert.AreEqual(storageAdapterInfo, pDisk.StorageAdapterInfo); + + Assert.AreEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs new file mode 100644 index 000000000..49c4e0b9f --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs @@ -0,0 +1,64 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_GetStorageDeviceInfo_UsingDevicePathFromSystemDrive_Success() + { + UnitTestAssert.IsElevatedProcess(); + UnitTestConstants.PrintUnitTestHeader(false); + + + var deviceCount = 0; + + var sourceDrive = UnitTestConstants.SysDrive; + var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; + + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); + + + Console.WriteLine("#{0:000}\tInput Device Path: [{1}]\t\t{2}", ++deviceCount, devicePath, pDisk.StorageDeviceInfo.ToString()); + + + var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(devicePath); + + + UnitTestConstants.Dump(storageDeviceInfo); + + Assert.IsNotNull(storageDeviceInfo); + + Assert.IsNotNull(pDisk); + + Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + + Assert.AreEqual(storageDeviceInfo, pDisk.StorageDeviceInfo); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs index 69df2f322..6e249e8c6 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs @@ -73,8 +73,17 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingLogicalDrivePath_Success() } + // For CDRom, the PartitionNumber is always - 1. + if (driveInfo.DriveType == System.IO.DriveType.CDRom) + { + Assert.AreEqual(-1, storageDeviceInfo.PartitionNumber); + Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.CDRom, storageDeviceInfo.DeviceType); + } + + else + Assert.AreNotEqual(-1, storageDeviceInfo.PartitionNumber); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs new file mode 100644 index 000000000..2324bc3f3 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs @@ -0,0 +1,65 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_GetStorageDeviceInfo_UsingVolumePathFromSystemDrive_Success() + { + UnitTestAssert.IsElevatedProcess(); + UnitTestConstants.PrintUnitTestHeader(false); + + + var volumeCount = 0; + + var sourceDrive = UnitTestConstants.SysDrive; + + var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); + + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); + + + Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]\t\t{2}", ++volumeCount, sourceVolume, pDisk.StorageDeviceInfo.ToString()); + + + var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(sourceVolume); + + + UnitTestConstants.Dump(storageDeviceInfo); + + Assert.IsNotNull(storageDeviceInfo); + + Assert.IsNotNull(pDisk); + + Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + + Assert.AreEqual(pDisk.StorageDeviceInfo, storageDeviceInfo); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs new file mode 100644 index 000000000..a5e50db20 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs @@ -0,0 +1,51 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull() + { + UnitTestAssert.IsElevatedProcess(); + UnitTestConstants.PrintUnitTestHeader(false); + + var deviceCount = 0; + + var sourceDrive = UnitTestConstants.SysDrive; + + var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; + + Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); + + var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(devicePath); + + Assert.IsNull(storagePartitionInfo); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs index eb8a8734e..5f6e4aa03 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs @@ -73,6 +73,8 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingLogicalDrivePath_Success UnitTestConstants.Dump(storagePartitionInfo); + // Show all partition information. + if (null != storagePartitionInfo.GptPartitionInfo) { gotDisk = true; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs new file mode 100644 index 000000000..3c5074319 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs @@ -0,0 +1,65 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Device_GetStoragePartitionInfo_UsingVolumePathFromSystemDrive_Success() + { + UnitTestAssert.IsElevatedProcess(); + UnitTestConstants.PrintUnitTestHeader(false); + + + var volumeCount = 0; + + var sourceDrive = UnitTestConstants.SysDrive; + + var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); + + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); + + + Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]\t\t{2}", ++volumeCount, sourceVolume, pDisk.StoragePartitionInfo.ToString()); + + + var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(sourceVolume); + + + UnitTestConstants.Dump(storagePartitionInfo); + + Assert.IsNotNull(storagePartitionInfo); + + Assert.IsNotNull(pDisk); + + Assert.AreEqual(pDisk.StorageDeviceInfo.DeviceNumber, storagePartitionInfo.DeviceNumber); + + Assert.AreEqual(pDisk.StoragePartitionInfo, storagePartitionInfo); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 0e69d8aaf..7c5093fd3 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -147,6 +147,10 @@ + + + + diff --git a/AlphaFS/Device/Device.Local.cs b/AlphaFS/Device/Device.Local.cs index 06e2c9186..0f7a84500 100644 --- a/AlphaFS/Device/Device.Local.cs +++ b/AlphaFS/Device/Device.Local.cs @@ -19,13 +19,10 @@ * THE SOFTWARE. */ -using System.IO; - namespace Alphaleonis.Win32.Device { /// [AlphaFS] Provides static methods to retrieve device resource information from the local host. public static partial class Local { - internal static DriveType[] ValidDriveTypes = {DriveType.CDRom, DriveType.Fixed, DriveType.Removable}; } } diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.cs index 40937f71c..96706ca9b 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.cs @@ -148,7 +148,7 @@ public bool IsReady /// Gets the name of the drive. /// The name of the drive. - /// This property is the name assigned to the drive, such as: C:\ or "D:\". + /// This property is the name assigned to the drive, such as: C:\ or D:\ public string Name { get { return _name; } diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index e40da336f..a8867df4f 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -86,12 +86,14 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) if (null != pDiskInfo) { // Use the storageDeviceInfo instance created earlier because it is based on the input path. + pDiskInfo.StorageDeviceInfo = storageDeviceInfo; - - if (isDeviceInfo) - // Accessing the device by its path: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - // does not relate to any drive or volume, so the default PartitionNumber of 0 is misleading. + + // Accessing the device by its path: \\?\scsi#disk&ven_sandisk&prod... + // does not relate to any drive or volume, so the default PartitionNumber of 0 is misleading. + + if (isDeviceInfo && pDiskInfo.StorageDeviceInfo.PartitionNumber == 0) pDiskInfo.StorageDeviceInfo.PartitionNumber = -1; @@ -148,7 +150,15 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string Name = isDeviceInfo ? deviceInfo.FriendlyName : null, - PhysicalDeviceObjectName = isDeviceInfo ? deviceInfo.PhysicalDeviceObjectName : null + PhysicalDeviceObjectName = isDeviceInfo ? deviceInfo.PhysicalDeviceObjectName : null, + + + StorageAdapterInfo = isDeviceInfo ? new StorageAdapterInfo {BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription} : null, + + + // Use the storageDeviceInfo instance created earlier because it is based on the input path. + + StorageDeviceInfo = storageDeviceInfo }; @@ -160,26 +170,14 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string { pDiskInfo.StorageAdapterInfo = GetStorageAdapterInfoNative(safeHandle, devicePath); - storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, devicePath, storageDeviceInfo); + // Use the storageDeviceInfo instance created earlier because it is based on the input path. + //pDiskInfo.StorageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, devicePath, pDiskInfo.StorageDeviceInfo); pDiskInfo.StoragePartitionInfo = GetStoragePartitionInfoNative(safeHandle, devicePath); } } - // Use the storageDeviceInfo instance created earlier because it is based on the input path. - pDiskInfo.StorageDeviceInfo = storageDeviceInfo; - - - if (isDeviceInfo) - { - if (null == pDiskInfo.StorageAdapterInfo) - pDiskInfo.StorageAdapterInfo = new StorageAdapterInfo(); - - pDiskInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; - } - - return pDiskInfo; } } diff --git a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs index 42a6e4360..1149c54af 100644 --- a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs @@ -131,10 +131,11 @@ public override bool Equals(object obj) other.AcceleratedTransfer == AcceleratedTransfer && other.AdapterScansDown == AdapterScansDown && other.AdapterUsesPio == AdapterUsesPio && - other.CommandQueueing == CommandQueueing && - other.MaximumTransferBytes == MaximumTransferBytes && + other.BusReportedDeviceDescription == BusReportedDeviceDescription && + other.BusType == BusType && other.BusVersion == BusVersion && - other.BusType == BusType; + other.CommandQueueing == CommandQueueing && + other.MaximumTransferBytes == MaximumTransferBytes; } @@ -144,7 +145,7 @@ public override int GetHashCode() { unchecked { - return MaximumTransferBytes + AcceleratedTransfer.GetHashCode() + (null != BusVersion ? BusVersion.GetHashCode() : 0) + BusType.GetHashCode(); + return MaximumTransferBytes.GetHashCode() + AcceleratedTransfer.GetHashCode() + AcceleratedTransfer.GetHashCode() + CommandQueueing.GetHashCode() + BusType.GetHashCode(); } } diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 6607fd402..ad12aba5b 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -31,6 +31,12 @@ namespace Alphaleonis.Win32.Device [SecurityCritical] public sealed class StorageDeviceInfo { + #region Private Fields + + + #endregion // Private Fields + + #region Constructors /// [AlphaFS] Initializes an empty StorageDeviceInfo instance. @@ -136,11 +142,16 @@ public override bool Equals(object obj) var other = obj as StorageDeviceInfo; return null != other && + other.BusType == BusType && other.DeviceNumber == DeviceNumber && - other.PartitionNumber == PartitionNumber && other.DeviceType == DeviceType && - other.BusType == BusType && - other.SerialNumber == SerialNumber; + other.PartitionNumber == PartitionNumber && + other.ProductId == ProductId && + other.ProductRevision == ProductRevision && + other.RemovableMedia == RemovableMedia && + other.SerialNumber == SerialNumber && + other.TotalSize == TotalSize && + other.VendorId == VendorId; } @@ -150,7 +161,7 @@ public override int GetHashCode() { unchecked { - return DeviceNumber + PartitionNumber + (null != SerialNumber ? SerialNumber.GetHashCode() : 0) + BusType.GetHashCode() + DeviceType.GetHashCode(); + return RemovableMedia.GetHashCode() + TotalSize.GetHashCode() + DeviceNumber.GetHashCode() + PartitionNumber.GetHashCode(); } } diff --git a/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs b/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs index 998a0e12d..39a13620a 100644 --- a/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs @@ -33,6 +33,7 @@ public sealed class StorageGptPartitionInfo { #region Private Fields + private readonly int _partitionNumber; private ulong _partitionLength; private ulong _startingOffset; @@ -44,7 +45,7 @@ public sealed class StorageGptPartitionInfo /// [AlphaFS] Initializes an empty StorageGptPartitionInfo instance. public StorageGptPartitionInfo() { - PartitionNumber = -1; + _partitionNumber = -1; } @@ -54,11 +55,11 @@ internal StorageGptPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partitio _startingOffset = partition.StartingOffset; - PartitionNumber = (int) partition.PartitionNumber; + _partitionNumber = (int) partition.PartitionNumber; + RewritePartition = partition.RewritePartition; - var gptPartition = partition.Gpt; Description = gptPartition.Name.Trim(); @@ -148,7 +149,10 @@ public string PartitionLengthUnitSize /// The storage partition number, starting at 1. - public int PartitionNumber { get; private set; } + public int PartitionNumber + { + get { return _partitionNumber; } + } /// The the partition type. Each partition type that the EFI specification supports is identified by its own GUID, which is published by the developer of the partition. @@ -204,9 +208,13 @@ public override bool Equals(object obj) return null != other && other.Attributes == Attributes && - other.PartitionId == PartitionId && other.Description == Description && - other.PartitionType == PartitionType; + other.PartitionId == PartitionId && + other.PartitionLength == PartitionLength && + other.PartitionNumber == PartitionNumber && + other.PartitionType == PartitionType && + other.RewritePartition == RewritePartition && + other.StartingOffset == StartingOffset; } @@ -216,7 +224,7 @@ public override int GetHashCode() { unchecked { - return Attributes.GetHashCode() + PartitionId.GetHashCode() + Description.GetHashCode() + PartitionType.GetHashCode(); + return PartitionLength.GetHashCode() + StartingOffset.GetHashCode() + PartitionNumber.GetHashCode(); } } diff --git a/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs b/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs index 6aef85312..50fe82ff9 100644 --- a/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs @@ -33,6 +33,7 @@ public sealed class StorageMbrPartitionInfo { #region Private Fields + private readonly int _partitionNumber; private ulong _partitionLength; private ulong _startingOffset; @@ -44,24 +45,24 @@ public sealed class StorageMbrPartitionInfo /// [AlphaFS] Initializes an empty StorageMbrPartitionInfo instance. public StorageMbrPartitionInfo() { - HiddenSectors = -1; + _partitionNumber = -1; - PartitionNumber = -1; + HiddenSectors = -1; } internal StorageMbrPartitionInfo(NativeMethods.PARTITION_INFORMATION_EX partition) : this() { + _partitionNumber = (int) partition.PartitionNumber; + _partitionLength = partition.PartitionLength; _startingOffset = partition.StartingOffset; - PartitionNumber = (int) partition.PartitionNumber; - + RewritePartition = partition.RewritePartition; - var mbrPartition = partition.Mbr; BootIndicator = mbrPartition.BootIndicator; @@ -121,7 +122,10 @@ public string PartitionLengthUnitSize /// The storage partition number, starting at 1. - public int PartitionNumber { get; private set; } + public int PartitionNumber + { + get { return _partitionNumber; } + } /// true if the partition is of a recognized type. @@ -177,9 +181,14 @@ public override bool Equals(object obj) return null != other && other.BootIndicator == BootIndicator && + other.DiskPartitionType == DiskPartitionType && other.HiddenSectors == HiddenSectors && + other.PartitionLength == PartitionLength && + other.PartitionNumber == PartitionNumber && other.RecognizedPartition == RecognizedPartition && - other.DiskPartitionType == DiskPartitionType; + other.RewritePartition == RewritePartition && + other.StartingOffset == StartingOffset; + } @@ -189,7 +198,7 @@ public override int GetHashCode() { unchecked { - return BootIndicator.GetHashCode() + HiddenSectors.GetHashCode() + RecognizedPartition.GetHashCode() + DiskPartitionType.GetHashCode(); + return PartitionLength.GetHashCode() + StartingOffset.GetHashCode() + PartitionNumber.GetHashCode(); } } diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index 48f29fa6e..2d7a79714 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -59,62 +59,72 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis { DeviceNumber = diskNumber; - MbrSignature = disk.PartitionInformation.MbrSignature; - - GptDiskId = disk.PartitionInformation.DiskId; - MediaType = (StorageMediaType) disk.Geometry.MediaType; - PartitionStyle = (PartitionStyle) disk.PartitionInformation.PartitionStyle; + PartitionCount = (int)drive.PartitionCount; - TotalSize = disk.DiskSize; + MbrSignature = disk.PartitionInformation.MbrSignature; - PartitionCount = (int) drive.PartitionCount; + GptDiskId = disk.PartitionInformation.DiskId; + + PartitionStyle = (PartitionStyle) disk.PartitionInformation.PartitionStyle; + TotalSize = disk.DiskSize; + switch (PartitionStyle) { case PartitionStyle.Gpt: + GptMaxPartitionCount = (int) drive.Gpt.MaxPartitionCount; _gptStartingUsableOffset = drive.Gpt.StartingUsableOffset; + _gptUsableLength = drive.Gpt.UsableLength; - - GptPartitionInfo = new Collection(); - var partitionTypes = Utils.EnumToArray(); - - for (var i = 0; i <= PartitionCount - 1; i++) - GptPartitionInfo.Add(new StorageGptPartitionInfo(partitions[i], partitionTypes)); - + if (PartitionCount > 0) + { + if (null == GptPartitionInfo) + GptPartitionInfo = new Collection(); + + + var partitionTypes = Utils.EnumToArray(); + + for (var i = 0; i <= PartitionCount - 1; i++) + GptPartitionInfo.Add(new StorageGptPartitionInfo(partitions[i], partitionTypes)); + } + break; case PartitionStyle.Mbr: - if (null == MbrPartitionInfo) - MbrPartitionInfo = new Collection(); + if (PartitionCount > 0) + { + if (null == MbrPartitionInfo) + MbrPartitionInfo = new Collection(); - for (var i = 0; i <= PartitionCount - 1; i++) - { - var partition = partitions[i]; + for (var i = 0; i <= PartitionCount - 1; i++) + { + var partition = partitions[i]; - // MSDN: PartitionCount: On hard disks with the MBR layout, this value will always be a multiple of 4. - // Any partitions that are actually unused will have a partition type of PARTITION_ENTRY_UNUSED (0). + // MSDN: PartitionCount: On hard disks with the MBR layout, this value will always be a multiple of 4. + // Any partitions that are actually unused will have a partition type of PARTITION_ENTRY_UNUSED (0). - if (partition.Mbr.PartitionType == (NativeMethods.DiskPartitionType)DiskPartitionType.UnusedEntry) - continue; + if (partition.Mbr.PartitionType == (NativeMethods.DiskPartitionType) DiskPartitionType.UnusedEntry) + continue; - MbrPartitionInfo.Add(new StorageMbrPartitionInfo(partition)); - } + MbrPartitionInfo.Add(new StorageMbrPartitionInfo(partition)); + } - // Update to reflect the real number of used partition entries. - PartitionCount = MbrPartitionInfo.Count; + // Update to reflect the real number of used partition entries. + PartitionCount = MbrPartitionInfo.Count; + } break; } @@ -224,7 +234,6 @@ public string GptUsableLengthUnitSize /// The number of partitions on the drive. public int PartitionCount { get; private set; } - /// The format of the partition. For a list of values, see . public PartitionStyle PartitionStyle { get; private set; } @@ -254,53 +263,57 @@ public override string ToString() } - ///// Determines whether the specified Object is equal to the current Object. - ///// Another object to compare to. - ///// true if the specified Object is equal to the current Object; otherwise, false. - //public override bool Equals(object obj) - //{ - // if (null == obj || GetType() != obj.GetType()) - // return false; - - // var other = obj as StoragePartitionInfo; - - // return null != other && - // other.DeviceNumber == DeviceNumber && - // other.PartitionNumber == PartitionNumber && - // other.PartitionStyle == PartitionStyle && - // other.TotalSize == TotalSize; - //} - - - ///// Serves as a hash function for a particular type. - ///// Returns a hash code for the current Object. - //public override int GetHashCode() - //{ - // unchecked - // { - // return PartitionCount + PartitionStyle.GetHashCode() + TotalSize.GetHashCode(); - // } - //} - - - ///// Implements the operator == - ///// A. - ///// B. - ///// The result of the operator. - //public static bool operator ==(StoragePartitionInfo left, StoragePartitionInfo right) - //{ - // return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); - //} - - - ///// Implements the operator != - ///// A. - ///// B. - ///// The result of the operator. - //public static bool operator !=(StoragePartitionInfo left, StoragePartitionInfo right) - //{ - // return !(left == right); - //} + /// Determines whether the specified Object is equal to the current Object. + /// Another object to compare to. + /// true if the specified Object is equal to the current Object; otherwise, false. + public override bool Equals(object obj) + { + if (null == obj || GetType() != obj.GetType()) + return false; + + var other = obj as StoragePartitionInfo; + + return null != other && + other.DeviceNumber == DeviceNumber && + other.GptDiskId == GptDiskId && + other.GptStartingUsableOffset == GptStartingUsableOffset && + other.GptUsableLength == GptUsableLength && + other.MediaType == MediaType && + other.PartitionCount == PartitionCount && + other.PartitionStyle == PartitionStyle && + other.TotalSize == TotalSize; + } + + + /// Serves as a hash function for a particular type. + /// Returns a hash code for the current Object. + public override int GetHashCode() + { + unchecked + { + return GptUsableLength.GetHashCode() + GptStartingUsableOffset.GetHashCode() + DeviceNumber.GetHashCode() + PartitionCount.GetHashCode(); + } + } + + + /// Implements the operator == + /// A. + /// B. + /// The result of the operator. + public static bool operator ==(StoragePartitionInfo left, StoragePartitionInfo right) + { + return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); + } + + + /// Implements the operator != + /// A. + /// B. + /// The result of the operator. + public static bool operator !=(StoragePartitionInfo left, StoragePartitionInfo right) + { + return !(left == right); + } #endregion // Methods } diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index da8cb4d0a..e997c1acc 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -111,13 +111,21 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri using (safeBuffer) storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure()); } - + if (null != storageDeviceInfo && isElevated) { using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read)) - + { storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, pathToDevice, storageDeviceInfo); + } + + + // Accessing the device by its path: \\?\scsi#disk&ven_sandisk&prod... + // does not relate to any drive or volume, so the default PartitionNumber of 0 is misleading. + + if (null != storageDeviceInfo && storageDeviceInfo.PartitionNumber == 0) + storageDeviceInfo.PartitionNumber = -1; } diff --git a/AlphaFS/Filesystem/DiskSpaceInfo.cs b/AlphaFS/Filesystem/DiskSpaceInfo.cs index 656bd4991..a80fbb672 100644 --- a/AlphaFS/Filesystem/DiskSpaceInfo.cs +++ b/AlphaFS/Filesystem/DiskSpaceInfo.cs @@ -126,7 +126,7 @@ public long ClusterSize /// Gets the name of a drive. - /// This property is the name assigned to the drive, such as: C:\ or "D:\". + /// This property is the name assigned to the drive, such as: C:\ or D:\ public string DriveName { get; private set; } From 67420d9559b6ce41070e67f6c817f58f86668f4b Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 10 Jun 2018 11:32:51 +0200 Subject: [PATCH 097/133] Code improvement. --- ...pterInfo_UsingDevicePathFromSystemDrive.cs | 4 +-- ...torageAdapterInfo_UsingLogicalDrivePath.cs | 1 - ...pterInfo_UsingVolumePathFromSystemDrive.cs | 5 ++-- ...viceInfo_UsingDevicePathFromSystemDrive.cs | 2 -- ...viceInfo_UsingVolumePathFromSystemDrive.cs | 2 -- ...ngDevicePathFromSystemDrive_ReturnsNull.cs | 1 - ...tionInfo_UsingVolumePathFromSystemDrive.cs | 2 -- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 2 +- .../Storage/Device.StoragePartitionInfo.cs | 8 ++---- .../Storage/Local.GetStorageAdapterInfo.cs | 27 ++++++++++++++++--- .../Storage/Local.GetStorageDeviceInfo.cs | 21 +++++++-------- .../Storage/Local.GetStoragePartitionInfo.cs | 23 +++++++++++++++- 12 files changed, 62 insertions(+), 36 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs index e5639f654..d70327889 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs @@ -32,10 +32,8 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] public void AlphaFS_Device_GetStorageAdapterInfo_UsingDevicePathFromSystemDrive_Success() { - UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); - - + var deviceCount = 0; var sourceDrive = UnitTestConstants.SysDrive; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs index 2bcd824ef..e51f43a39 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs @@ -32,7 +32,6 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] public void AlphaFS_Device_GetStorageAdapterInfo_UsingLogicalDrivePath_Success() { - UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); var gotDisk = false; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs index 33fd487fb..8786a95d0 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs @@ -32,10 +32,9 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] public void AlphaFS_Device_GetStorageAdapterInfo_UsingVolumePathFromSystemDrive_Success() { - UnitTestAssert.IsElevatedProcess(); + //UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); - - + var volumeCount = 0; var sourceDrive = UnitTestConstants.SysDrive; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs index 49c4e0b9f..dae60d495 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs @@ -32,10 +32,8 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] public void AlphaFS_Device_GetStorageDeviceInfo_UsingDevicePathFromSystemDrive_Success() { - UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); - var deviceCount = 0; var sourceDrive = UnitTestConstants.SysDrive; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs index 2324bc3f3..9af972c88 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs @@ -32,10 +32,8 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] public void AlphaFS_Device_GetStorageDeviceInfo_UsingVolumePathFromSystemDrive_Success() { - UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); - var volumeCount = 0; var sourceDrive = UnitTestConstants.SysDrive; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs index a5e50db20..3ba8b6e6d 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs @@ -32,7 +32,6 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] public void AlphaFS_Device_GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull() { - UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); var deviceCount = 0; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs index 3c5074319..3c8153281 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs @@ -32,10 +32,8 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] public void AlphaFS_Device_GetStoragePartitionInfo_UsingVolumePathFromSystemDrive_Success() { - UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); - var volumeCount = 0; var sourceDrive = UnitTestConstants.SysDrive; diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index a8867df4f..f56f258ed 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -98,7 +98,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) if (null == pDiskInfo.StoragePartitionInfo) - pDiskInfo.StoragePartitionInfo = GetStoragePartitionInfo(validatedDevicePath); + pDiskInfo.StoragePartitionInfo = GetStoragePartitionInfo(isElevated, validatedDevicePath); } diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index 2d7a79714..0475f7832 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -86,9 +86,7 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis if (PartitionCount > 0) { - if (null == GptPartitionInfo) - GptPartitionInfo = new Collection(); - + GptPartitionInfo = new Collection(); var partitionTypes = Utils.EnumToArray(); @@ -103,9 +101,7 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis if (PartitionCount > 0) { - if (null == MbrPartitionInfo) - MbrPartitionInfo = new Collection(); - + MbrPartitionInfo = new Collection(); for (var i = 0; i <= PartitionCount - 1; i++) { diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index 48a42ba56..8a5ddb600 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -21,9 +21,9 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Globalization; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; +using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device @@ -45,14 +45,35 @@ public static partial class Local /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) + { + return GetStorageAdapterInfo(ProcessContext.IsElevatedProcess, devicePath); + } + + + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume or . + /// Calling this method requires an elevated state. + /// + /// Returns a instance that represent the storage device on the Computer that is related to . + /// + /// + /// + /// + /// true indicates the current process is in an elevated state, allowing to retrieve more data. + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + public static StorageAdapterInfo GetStorageAdapterInfo(bool isElevated, string devicePath) { var pathToDevice = FileSystemHelper.GetDevicePath(devicePath); if (Utils.IsNullOrWhiteSpace(pathToDevice)) return null; + - - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, isElevated ? FileSystemRights.Read : Filesystem.NativeMethods.FILE_ANY_ACCESS)) return GetStorageAdapterInfoNative(safeHandle, devicePath); } diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index e997c1acc..ac7be1b59 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -34,7 +34,7 @@ public static partial class Local /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume or . /// Returns a instance that represent the storage device on the Computer that is related to . /// - /// When this method is called from a non-elevated state, only the properties and are useful. + /// When this method is called from a non-elevated state, only the properties , and are useful. /// The remaining properties are meaningless and can only be obtained by calling the method from an elevated state. /// /// @@ -57,7 +57,7 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) /// Returns a instance that represent the storage device on the Computer that is related to . /// - /// When this method is called from a non-elevated state, only the properties and are useful. + /// When this method is called from a non-elevated state, only the properties , and are useful. /// The remaining properties are meaningless and can only be obtained by calling the method from an elevated state. /// /// @@ -86,7 +86,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri // Get storage device info. - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, Filesystem.NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, isElevated ? FileSystemRights.Read : Filesystem.NativeMethods.FILE_ANY_ACCESS)) { var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); @@ -116,17 +116,16 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri if (null != storageDeviceInfo && isElevated) { using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read)) - { + storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, pathToDevice, storageDeviceInfo); - } + } - - // Accessing the device by its path: \\?\scsi#disk&ven_sandisk&prod... - // does not relate to any drive or volume, so the default PartitionNumber of 0 is misleading. - if (null != storageDeviceInfo && storageDeviceInfo.PartitionNumber == 0) - storageDeviceInfo.PartitionNumber = -1; - } + // Accessing the device by its path: \\?\scsi#disk&ven_sandisk&prod... + // does not relate to any drive or volume, so the default PartitionNumber of 0 is misleading. + + if (null != storageDeviceInfo && storageDeviceInfo.PartitionNumber == 0) + storageDeviceInfo.PartitionNumber = -1; return storageDeviceInfo; diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index fa4bd25ea..228958686 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -21,7 +21,9 @@ using System; using System.Runtime.InteropServices; +using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; +using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device @@ -41,6 +43,25 @@ public static partial class Local /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) + { + return GetStoragePartitionInfo(ProcessContext.IsElevatedProcess, devicePath); + } + + + /// [AlphaFS] Retrieves information about the partitions on a disk and the features of each partition. + /// Returns a instance that represent the partition info on the Computer that is related to . + /// + /// + /// + /// + /// true indicates the current process is in an elevated state, allowing to retrieve more data. + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, string devicePath) { var pathToDevice = FileSystemHelper.GetDevicePath(devicePath); @@ -48,7 +69,7 @@ public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) return null; - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, Filesystem.NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, isElevated ? FileSystemRights.Read : Filesystem.NativeMethods.FILE_ANY_ACCESS)) return GetStoragePartitionInfoNative(safeHandle, devicePath); } From 4796976eaa4c4d09139a2d3dfd234c0259880f9d Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 10 Jun 2018 22:59:55 +0200 Subject: [PATCH 098/133] Code improvement. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 22 --- ...pterInfo_UsingDevicePathFromSystemDrive.cs | 15 +- ...pterInfo_UsingVolumePathFromSystemDrive.cs | 2 +- ...viceInfo_UsingDevicePathFromSystemDrive.cs | 2 +- AlphaFS/AlphaFS.csproj | 7 +- AlphaFS/Device/Device.DeviceInfo.cs | 2 +- ...=> FileSystemHelper.GetLocalDevicePath.cs} | 31 +-- ...ileSystemHelper.GetValidatedDevicePath.cs} | 15 +- .../FilesystemHelper.OpenPhysicalDrive.cs | 2 +- .../Device/Native Methods/NativeMethods.cs | 29 +++ AlphaFS/Device/Native Other/IoControlCode.cs | 4 +- .../PhysicalDisk/Device.PhysicalDiskInfo.cs | 8 +- .../Local.EnumeratePhysicalDisks.cs | 11 +- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 75 +++++--- .../Storage/Device.StorageAdapterInfo.cs | 17 +- .../Storage/Device.StorageDeviceInfo.cs | 27 ++- .../Storage/Device.StoragePartitionInfo.cs | 11 +- .../Storage/Local.GetStorageAdapterInfo.cs | 73 ++------ .../Storage/Local.GetStorageDeviceInfo.cs | 177 +++++------------- .../Storage/Local.GetStoragePartitionInfo.cs | 25 ++- .../Storage/Local.GetVolumeDiskExtents.cs | 2 + .../Native Methods/NativeMethods.Constants.cs | 4 - .../Path Class/Path.IsLogicalDrive.cs | 8 +- 23 files changed, 260 insertions(+), 309 deletions(-) rename AlphaFS/Device/FileSystemHelper/{FilesystemHelper.GetDevicePath.cs => FileSystemHelper.GetLocalDevicePath.cs} (64%) rename AlphaFS/Device/FileSystemHelper/{FilesystemHelper.ValidateDevicePath.cs => FileSystemHelper.GetValidatedDevicePath.cs} (75%) create mode 100644 AlphaFS/Device/Native Methods/NativeMethods.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index 7569e26ec..12b1ada39 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -35,8 +35,6 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); - var gotDisk = false; - var pDriveCount = 0; var pDrives = Alphaleonis.Win32.Device.Local.EnumeratePhysicalDisks().OrderBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber).ThenBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.PartitionNumber).ToArray(); @@ -55,27 +53,7 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Local_Success() UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); - // Show all partition information. - - if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) - { - gotDisk = true; - - foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) - UnitTestConstants.Dump(partition, true); - } - - if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) - { - gotDisk = true; - - foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) - UnitTestConstants.Dump(partition, true); - } - Console.WriteLine(); - - //Assert.IsTrue(gotDisk); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs index d70327889..b0a83e908 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs @@ -56,7 +56,20 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingDevicePathFromSystemDrive_ Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(storageAdapterInfo, pDisk.StorageAdapterInfo); + + if (Alphaleonis.Win32.Security.ProcessContext.IsElevatedProcess) + { + Assert.AreEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); + + Assert.AreNotEqual(Alphaleonis.Win32.Device.StorageBusType.Unknown, storageAdapterInfo.BusType); + } + + else + { + Assert.AreNotEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); + + Assert.AreEqual(pDisk.StorageAdapterInfo.BusType, storageAdapterInfo.BusType); + } } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs index 8786a95d0..36de56cee 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs @@ -57,7 +57,7 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingVolumePathFromSystemDrive_ Assert.IsNotNull(pDisk); Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - + Assert.AreEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs index dae60d495..72b16399b 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs @@ -56,7 +56,7 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingDevicePathFromSystemDrive_S Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(storageDeviceInfo, pDisk.StorageDeviceInfo); + Assert.AreEqual(pDisk.StorageDeviceInfo, storageDeviceInfo); } } } diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index c69d19033..4c078e8ff 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -197,6 +197,7 @@ True + @@ -205,8 +206,8 @@ - - + + @@ -740,7 +741,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.DeviceInfo.cs b/AlphaFS/Device/Device.DeviceInfo.cs index c7df55b40..a0df154a2 100644 --- a/AlphaFS/Device/Device.DeviceInfo.cs +++ b/AlphaFS/Device/Device.DeviceInfo.cs @@ -81,7 +81,7 @@ public DeviceInfo(string host) public string DeviceDescription { get; internal set; } - /// The device interface path string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// The device interface path string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} public string DevicePath { get; internal set; } diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs b/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetLocalDevicePath.cs similarity index 64% rename from AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs rename to AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetLocalDevicePath.cs index bc5978833..40ef50a32 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetDevicePath.cs +++ b/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetLocalDevicePath.cs @@ -27,53 +27,56 @@ namespace Alphaleonis.Win32.Device { internal static partial class FileSystemHelper { - /// Determines and retrieves the such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// Determines and retrieves the such as: \\.\C: or \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// Returns the path string such as: \\.\C: or \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// - /// Returns the path string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - internal static string GetDevicePath(string devicePath) + internal static string GetLocalDevicePath(string devicePath) { string unusedLogicalDrive; - return GetDevicePath(devicePath, out unusedLogicalDrive); + return GetLocalDevicePath(devicePath, out unusedLogicalDrive); } - /// Determines and retrieves the such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// Returns the path string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// Determines and retrieves the such as: \\.\C: or \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// Returns the path string such as: \\.\C: or \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// /// If is a logical drive, it is returned in - internal static string GetDevicePath(string devicePath, out string logicalDrive) + internal static string GetLocalDevicePath(string devicePath, out string logicalDrive) { bool isDrive; bool isVolume; bool isDeviceInfo; - devicePath = ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + var validatedDevicePath = GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + + if (!validatedDevicePath.StartsWith(Path.LogicalDrivePrefix, StringComparison.OrdinalIgnoreCase)) + + validatedDevicePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", isDrive ? Path.LogicalDrivePrefix : string.Empty, Path.RemoveTrailingDirectorySeparator(validatedDevicePath)); - devicePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", isDrive ? Path.LogicalDrivePrefix : string.Empty, Path.RemoveTrailingDirectorySeparator(devicePath)); if (isDrive) { - logicalDrive = Path.GetRegularPathCore(devicePath, GetFullPathOptions.RemoveTrailingDirectorySeparator, false); + logicalDrive = Path.GetRegularPathCore(validatedDevicePath, GetFullPathOptions.RemoveTrailingDirectorySeparator, false); - logicalDrive = devicePath.Substring(Path.LogicalDrivePrefix.Length); + logicalDrive = validatedDevicePath.Substring(Path.LogicalDrivePrefix.Length); } else logicalDrive = null; - return devicePath; + return validatedDevicePath; } } } diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.ValidateDevicePath.cs b/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs similarity index 75% rename from AlphaFS/Device/FileSystemHelper/FilesystemHelper.ValidateDevicePath.cs rename to AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs index aea027637..64dcb96ab 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.ValidateDevicePath.cs +++ b/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs @@ -26,13 +26,16 @@ namespace Alphaleonis.Win32.Device { internal static partial class FileSystemHelper { - /// Determines the type of device path. + /// Determines and retrieves the type of device path. /// The final device path with a . - internal static string ValidateDevicePath(string devicePath, out bool isDrive, out bool isVolume, out bool isDeviceInfo) + internal static string GetValidatedDevicePath(string devicePath, out bool isDrive, out bool isVolume, out bool isDevice) { - if (Utils.IsNullOrWhiteSpace(devicePath)) + if (null == devicePath) throw new ArgumentNullException("devicePath"); + if (devicePath.Trim().Length == 0) + throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "devicePath"); + // Resolve single drive letter or get root directory information. @@ -43,13 +46,13 @@ internal static string ValidateDevicePath(string devicePath, out bool isDrive, o isVolume = hasPath && devicePath.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase); - isDeviceInfo = hasPath && !isVolume && devicePath.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal); + isDevice = hasPath && !isVolume && devicePath.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal); - isDrive = hasPath && !isDeviceInfo && !isVolume && Path.IsLogicalDriveCore(devicePath, false, PathFormat.LongFullPath); + isDrive = hasPath && !isDevice && !isVolume && Path.IsLogicalDriveCore(devicePath, false, PathFormat.LongFullPath); - if (!hasPath || !isVolume && !isDeviceInfo && !isDrive) + if (!hasPath || !isVolume && !isDevice && !isDrive) throw new ArgumentException(Resources.Argument_must_be_DriveLetter_or_VolumeGuid_or_DevicePath, "devicePath"); diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs index ec2b5c533..6ff790ae2 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs @@ -41,7 +41,7 @@ internal static partial class FileSystemHelper /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// /// If no elevated access is needed to access the physical disk or volume/logical drive, specify 0 for this parameter. [SecurityCritical] diff --git a/AlphaFS/Device/Native Methods/NativeMethods.cs b/AlphaFS/Device/Native Methods/NativeMethods.cs new file mode 100644 index 000000000..35ad29fd9 --- /dev/null +++ b/AlphaFS/Device/Native Methods/NativeMethods.cs @@ -0,0 +1,29 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Device +{ + internal static partial class NativeMethods + { + /// FILE_ANY_ACCESS = 0 + internal const int FILE_ANY_ACCESS = 0; + } +} diff --git a/AlphaFS/Device/Native Other/IoControlCode.cs b/AlphaFS/Device/Native Other/IoControlCode.cs index fa945e474..5baa7ad65 100644 --- a/AlphaFS/Device/Native Other/IoControlCode.cs +++ b/AlphaFS/Device/Native Other/IoControlCode.cs @@ -123,7 +123,9 @@ internal enum IoControlCode : uint //IOCTL_STORAGE_RESET_DEVICE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0401 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), - /// Returns a STORAGE_DEVICE_NUMBER structure that contains the FILE_DEVICE_XXX type, device number, and, for a partitionable device, the partition number assigned to a device by the driver when the device is started. This request is usually issued by a fault-tolerant disk driver. + /// Returns a STORAGE_DEVICE_NUMBER structure that contains the FILE_DEVICE_XXX type, device number, and, for a partitionable device, + /// the partition number assigned to a device by the driver when the device is started. This request is usually issued by a fault-tolerant disk driver. + /// IOCTL_STORAGE_GET_DEVICE_NUMBER = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0420 << 2) | IoMethod.Buffered | (0 << 14), diff --git a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs index 9a5b6a3e2..7fcf7c01f 100644 --- a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs @@ -60,7 +60,7 @@ internal PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) /// Returns a string that represents the path to the device. /// A drive path such as: C:, D:\, /// a volume path such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// or a string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string. + /// or a string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string. /// public string DevicePath { get; internal set; } @@ -114,7 +114,7 @@ internal PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// public bool ContainsVolume(string devicePath) { @@ -122,11 +122,13 @@ public bool ContainsVolume(string devicePath) bool isVolume; bool isDeviceInfo; - devicePath = FileSystemHelper.ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + devicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); if (isDrive && null != LogicalDrives) { + devicePath = devicePath.Replace(Path.LogicalDrivePrefix, string.Empty); + devicePath = Path.RemoveTrailingDirectorySeparator(devicePath, false); return LogicalDrives.Any(driveName => driveName.Equals(devicePath, StringComparison.OrdinalIgnoreCase)); diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 4f144c3df..6b9fd45d6 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -67,16 +67,15 @@ internal static IEnumerable EnumeratePhysicalDisksCore(bool is driveTypes = new[] {DriveType.CDRom, DriveType.Fixed, DriveType.Removable}; - var physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => GetPhysicalDiskInfoCore(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + var physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => CreatePhysicalDiskInfo(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); - //var pVolumeGuids = EnumerateDevicesCore(null, DeviceGuid.Volume, false).Select(deviceInfo => GetPhysicalDiskInfoCore(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); - var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => GetPhysicalDiskInfoCore(false, volumeGuid, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => CreatePhysicalDiskInfo(false, volumeGuid, null)).Where(physicalDisk => null != physicalDisk).ToArray(); var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false) - .Select(driveName => new DriveInfo(driveName)).Where(driveInfo => {return driveTypes.Any(drive => driveInfo.DriveType == drive);}) + .Select(driveName => new DriveInfo(driveName)).Where(driveInfo => {return driveTypes.Any(driveType => driveInfo.DriveType == driveType);}) - .Select(driveInfo => GetPhysicalDiskInfoCore(false, driveInfo.Name, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + .Select(driveInfo => CreatePhysicalDiskInfo(false, driveInfo.Name, null)).Where(physicalDisk => null != physicalDisk).ToArray(); foreach (var pDisk in physicalDisks) @@ -86,7 +85,7 @@ internal static IEnumerable EnumeratePhysicalDisksCore(bool is //// Windows Disk Management shows CD-ROM so mimic that behaviour. - //var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => GetPhysicalDiskInfoCore(isElevated, null, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + //var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => CreatePhysicalDiskInfo(isElevated, null, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); //foreach (var pCdRom in cdRoms) diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index f56f258ed..9fa28fc52 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -31,7 +31,7 @@ namespace Alphaleonis.Win32.Device { public static partial class Local { - /// [AlphaFS] Retrieves the physical disk on the Computer that is related to the logical drive name, volume or . + /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . /// Returns a instance that represents the physical disk on the Computer or null on error/no data available. /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. @@ -45,33 +45,54 @@ public static partial class Local /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// [SecurityCritical] public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) + { + return GetPhysicalDiskInfo(ProcessContext.IsElevatedProcess, devicePath); + } + + + /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . + /// Returns a instance that represents the physical disk on the Computer or null on error/no data available. + /// + /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. + /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks, associated volumes and logical drives. + /// Instead, use method and property and/or . + /// + /// + /// + /// + /// true indicates the current process is in an elevated state, allowing to retrieve more data. + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + [SecurityCritical] + public static PhysicalDiskInfo GetPhysicalDiskInfo(bool isElevated, string devicePath) { bool isDrive; bool isVolume; - bool isDeviceInfo; - - var isElevated = ProcessContext.IsElevatedProcess; + bool isDevice; - var validatedDevicePath = FileSystemHelper.ValidateDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); - - - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, validatedDevicePath); + var validatedDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + + if (isDrive) + validatedDevicePath = FileSystemHelper.GetLocalDevicePath(validatedDevicePath); + + + var storageDeviceInfo = GetStorageDeviceInfo(isElevated, validatedDevicePath); if (null == storageDeviceInfo) return null; - - - if (isDrive) - // Use logical drive path. - FileSystemHelper.GetDevicePath(validatedDevicePath, out validatedDevicePath); + // Get the PhysicalDiskInfo instance. - var pDiskInfo = isDeviceInfo + var pDiskInfo = isDevice ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => pDisk.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber && pDisk.StorageDeviceInfo.PartitionNumber == storageDeviceInfo.PartitionNumber) @@ -93,7 +114,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) // Accessing the device by its path: \\?\scsi#disk&ven_sandisk&prod... // does not relate to any drive or volume, so the default PartitionNumber of 0 is misleading. - if (isDeviceInfo && pDiskInfo.StorageDeviceInfo.PartitionNumber == 0) + if (isDevice && pDiskInfo.StorageDeviceInfo.PartitionNumber == 0) pDiskInfo.StorageDeviceInfo.PartitionNumber = -1; @@ -106,7 +127,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) } - /// [AlphaFS] Retrieves the physical disk on the Computer that is related to the logical drive name, volume or . + /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . /// A instance that represents the physical disk on the Computer or null on error/no data available. /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. @@ -122,21 +143,21 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// /// A instance. /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string devicePath, DeviceInfo deviceInfo) + internal static PhysicalDiskInfo CreatePhysicalDiskInfo(bool isElevated, string devicePath, DeviceInfo deviceInfo) { - var isDeviceInfo = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); + var isDevice = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); - if (isDeviceInfo) + if (isDevice) devicePath = deviceInfo.DevicePath; - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, devicePath); + var storageDeviceInfo = GetStorageDeviceInfo(isElevated, devicePath); if (null == storageDeviceInfo) return null; @@ -146,14 +167,14 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string { DevicePath = devicePath, - DeviceDescription = isDeviceInfo ? deviceInfo.DeviceDescription : null, + DeviceDescription = isDevice ? deviceInfo.DeviceDescription : null, - Name = isDeviceInfo ? deviceInfo.FriendlyName : null, + Name = isDevice ? deviceInfo.FriendlyName : null, - PhysicalDeviceObjectName = isDeviceInfo ? deviceInfo.PhysicalDeviceObjectName : null, + PhysicalDeviceObjectName = isDevice ? deviceInfo.PhysicalDeviceObjectName : null, - StorageAdapterInfo = isDeviceInfo ? new StorageAdapterInfo {BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription} : null, + StorageAdapterInfo = isDevice ? new StorageAdapterInfo {BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription} : null, // Use the storageDeviceInfo instance created earlier because it is based on the input path. @@ -171,7 +192,7 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, string pDiskInfo.StorageAdapterInfo = GetStorageAdapterInfoNative(safeHandle, devicePath); // Use the storageDeviceInfo instance created earlier because it is based on the input path. - //pDiskInfo.StorageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, devicePath, pDiskInfo.StorageDeviceInfo); + //pDiskInfo.StorageDeviceInfo = SetStorageDeviceInfoData(safeHandle, devicePath, pDiskInfo.StorageDeviceInfo); pDiskInfo.StoragePartitionInfo = GetStoragePartitionInfoNative(safeHandle, devicePath); } diff --git a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs index 1149c54af..3ad92aa78 100644 --- a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs @@ -63,47 +63,46 @@ internal StorageAdapterInfo(NativeMethods.STORAGE_ADAPTER_DESCRIPTOR adapter) : #region Properties /// When true, the storage adapter supports synchronous transfers as a way of speeding up I/O. - public bool AcceleratedTransfer { get; internal set; } + public bool AcceleratedTransfer { get; private set; } /// When true, the storage adapter scans down for BIOS devices, that is, the storage adapter begins scanning with the highest device number rather than the lowest. - public bool AdapterScansDown { get; internal set; } + public bool AdapterScansDown { get; private set; } /// When true, the storage adapter uses programmed I/O (PIO). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pio")] - public bool AdapterUsesPio { get; internal set; } + public bool AdapterUsesPio { get; private set; } /// The bus type of the storage adapter. - public StorageBusType BusType { get; internal set; } + public StorageBusType BusType { get; private set; } /// Represents a description of a device instance as identified by the bus. public string BusReportedDeviceDescription { get; internal set; } /// The version number, if any, of the storage adapter. - public Version BusVersion { get; internal set; } + public Version BusVersion { get; private set; } /// When true, the storage adapter supports SCSI tagged queuing and/or per-logical-unit internal queues, or the non-SCSI equivalent. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Queueing")] - public bool CommandQueueing { get; internal set; } + public bool CommandQueueing { get; private set; } /// Specifies the maximum number of bytes the storage adapter can transfer in a single operation. - public int MaximumTransferBytes { get; internal set; } + public int MaximumTransferBytes { get; private set; } #if DEBUG - /// + /// Specifies the maximum number of bytes the storage adapter can transfer in a single operation, formatted as a unit size. public string MaximumTransferBytesUnitSize { get { return Utils.UnitSizeToText(MaximumTransferBytes); } } #endif - #endregion // Properties diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index ad12aba5b..1c6ccac98 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -68,7 +68,10 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public StorageBusType BusType { get; internal set; } - /// Indicates if the physical disk supports multiple outstanding commands (SCSI tagged queuing or equivalent). When false the physical disk does not support SCSI-tagged queuing or the equivalent. + /// + /// Indicates if the physical disk supports multiple outstanding commands (SCSI tagged queuing or equivalent). + /// When false the physical disk does not support SCSI-tagged queuing or the equivalent. + /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Queueing")] public bool CommandQueueing { get; internal set; } @@ -77,13 +80,14 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public StorageDeviceType DeviceType { get; internal set; } - /// The device number of the storage device, starting at 0. + /// The device number of the storage device, starting at 0. public int DeviceNumber { get; internal set; } /// - /// The partition number of the storage device, starting at 1. If the device cannot be partitioned, like a CDROM, -1 is returned. - /// -1 is also returned if the device is accessed by its path: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} instead of a logical drive- or volume path. + /// The partition number of the storage device, starting at 1. If the device cannot be partitioned, like a CDROM, -1 is returned. + /// -1 is also returned if the device is accessed by its path: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// instead of a logical drive- or volume path. /// public int PartitionNumber { get; internal set; } @@ -96,24 +100,27 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public string ProductRevision { get; internal set; } - /// Indicates if the physical disk is removable. When true the physical disk's media (if any) is removable. If the device has no media, this member should be ignored. When false the physical disk's media is not removable. + /// + /// Indicates if the physical disk is removable. When true the physical disk's media (if any) is removable. + /// If the device has no media, this member should be ignored. When false the physical disk's media is not removable. + /// public bool RemovableMedia { get; internal set; } - /// The serial number of the physical disk. If the physical disk has no serial number or the session is not elevated -1 is returned. + /// The serial number of the physical disk. If the physical disk has no serial number null is returned. public string SerialNumber { get; internal set; } - /// The total size of the physical disk. + /// The total size of the physical disk. If the session is not elevated 0 is returned. public long TotalSize { get; internal set; } -#if DEBUG - /// + + /// The total size of the physical disk, formatted as a unit size. If the session is not elevated 0 is returned. public string TotalSizeUnitSize { get { return Utils.UnitSizeToText(TotalSize); } } -#endif + /// The Vendor ID of the physical disk. public string VendorId { get; internal set; } diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index 0475f7832..222904115 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -177,7 +177,7 @@ internal set } - /// The size of the usable blocks on the disk, in bytes. + /// The size of the usable blocks on the disk in bytes. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] public long GptUsableLength { @@ -200,7 +200,7 @@ internal set #if DEBUG - /// + /// The size of the usable blocks on the disk in bytes, formatted as a unit size. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpt")] public string GptUsableLengthUnitSize { @@ -236,15 +236,14 @@ public string GptUsableLengthUnitSize /// The total size of the storage partition. public long TotalSize { get; private set; } - -#if DEBUG - /// + + + /// The total size of the storage partition, formatted as a unit size. public string TotalSizeUnitSize { get { return Utils.UnitSizeToText(TotalSize); } } -#endif #endregion // Properties diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index 8a5ddb600..a4b02709d 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -21,6 +21,7 @@ using System; using System.Diagnostics.CodeAnalysis; +using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; @@ -30,10 +31,8 @@ namespace Alphaleonis.Win32.Device { public static partial class Local { - /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume or . - /// Calling this method requires an elevated state. - /// - /// Returns a instance that represent the storage device on the Computer that is related to . + /// [AlphaFS] Retrieves the storage adapter of the device that is related to the logical drive name, volume or . + /// Returns a instance that represent the adapter information of the storage device that is related to . /// /// /// @@ -42,18 +41,17 @@ public static partial class Local /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// + [SecurityCritical] public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) { return GetStorageAdapterInfo(ProcessContext.IsElevatedProcess, devicePath); } - /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume or . - /// Calling this method requires an elevated state. - /// - /// Returns a instance that represent the storage device on the Computer that is related to . + /// [AlphaFS] Retrieves the storage adapter of the device that is related to the logical drive name, volume or . + /// Returns a instance that represent the storage device that is related to . /// /// /// @@ -63,23 +61,29 @@ public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// + [SecurityCritical] public static StorageAdapterInfo GetStorageAdapterInfo(bool isElevated, string devicePath) { - var pathToDevice = FileSystemHelper.GetDevicePath(devicePath); + bool isDrive; + bool isVolume; + bool isDevice; - if (Utils.IsNullOrWhiteSpace(pathToDevice)) - return null; - + var validatedDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, isElevated ? FileSystemRights.Read : Filesystem.NativeMethods.FILE_ANY_ACCESS)) + if (isDrive) + validatedDevicePath = FileSystemHelper.GetLocalDevicePath(validatedDevicePath); + + + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(validatedDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) return GetStorageAdapterInfoNative(safeHandle, devicePath); } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] + [SecurityCritical] private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle safeHandle, string pathToDevice) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY @@ -88,46 +92,9 @@ private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle saf QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery }; - SafeFileHandle safeHandleRetry = null; - var isRetry = false; - - StartGetData: - - // Get storage adapter info. - - using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) { - //if (null == safeBuffer) - //{ - // // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - - - // var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle, pathToDevice); - - // if (volDiskExtents.HasValue) - // { - // // Use the first disk extent. - - // pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - - - // safeHandleRetry = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); - - // isRetry = Utils.IsValidHandle(safeHandleRetry, false); - // } - - - // if (isRetry) - // goto StartGetData; - - // return null; - //} - - - if (isRetry && !safeHandleRetry.IsClosed) - safeHandleRetry.Close(); - return new StorageAdapterInfo(safeBuffer.PtrToStructure()); } } diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index ac7be1b59..b13885df1 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -21,7 +21,7 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Globalization; +using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; @@ -31,12 +31,9 @@ namespace Alphaleonis.Win32.Device { public static partial class Local { - /// [AlphaFS] Retrieves the type, device- and partition number for the storage device on the Computer that is related to the logical drive name, volume or . - /// Returns a instance that represent the storage device on the Computer that is related to . - /// - /// When this method is called from a non-elevated state, only the properties , and are useful. - /// The remaining properties are meaningless and can only be obtained by calling the method from an elevated state. - /// + /// [AlphaFS] Retrieves the type, device- and partition number for the storage device that is related to the logical drive name, volume or . + /// Returns a instance that represent the storage device that is related to . + /// When this method is called from a non-elevated state, the property always returns 0. /// /// /// @@ -45,86 +42,59 @@ public static partial class Local /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// + [SecurityCritical] public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { - return GetStorageDeviceInfoCore(ProcessContext.IsElevatedProcess, devicePath); + return GetStorageDeviceInfo(ProcessContext.IsElevatedProcess, devicePath); } - - - /// Returns a instance that represent the storage device on the Computer that is related to . - /// - /// When this method is called from a non-elevated state, only the properties , and are useful. - /// The remaining properties are meaningless and can only be obtained by calling the method from an elevated state. - /// + /// Returns a instance that represent the storage device that is related to . + /// When this method is called from a non-elevated state, the property always returns 0. /// /// /// /// /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// - internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, string devicePath) + [SecurityCritical] + public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string devicePath) { - var pathToDevice = FileSystemHelper.GetDevicePath(devicePath); + bool isDrive; + bool isVolume; + bool isDevice; - if (Utils.IsNullOrWhiteSpace(pathToDevice)) - return null; + var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + if (isDrive) + localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - StorageDeviceInfo storageDeviceInfo = null; + StorageDeviceInfo storageDeviceInfo; - StartGetData: - - // Get storage device info. - - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, isElevated ? FileSystemRights.Read : Filesystem.NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) { - var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath); - - //if (null == safeBuffer) - //{ - // // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - - - // var volDiskExtents = GetVolumeDiskExtents(safeHandle, pathToDevice); + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath)) - // if (volDiskExtents.HasValue) - // { - // // Use the first disk extent. + storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure()); - // pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - - // goto StartGetData; - // } - //} - //else - using (safeBuffer) - storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure()); - } - - - if (null != storageDeviceInfo && isElevated) - { - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read)) - - storageDeviceInfo = GetStorageDeviceInfoNative(safeHandle, pathToDevice, storageDeviceInfo); + SetStorageDeviceInfoData(isElevated, safeHandle, localDevicePath, storageDeviceInfo); } // Accessing the device by its path: \\?\scsi#disk&ven_sandisk&prod... // does not relate to any drive or volume, so the default PartitionNumber of 0 is misleading. - if (null != storageDeviceInfo && storageDeviceInfo.PartitionNumber == 0) + if (isDevice && storageDeviceInfo.PartitionNumber == 0) + storageDeviceInfo.PartitionNumber = -1; @@ -132,104 +102,55 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri } - /// Sets the physical disk properties such as FriendlyName, device size and serial number. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - private static StorageDeviceInfo GetStorageDeviceInfoNative(SafeFileHandle safeHandle, string pathToDevice, StorageDeviceInfo storageDeviceInfo) + [SecurityCritical] + private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle safeHandle, string localDevicePath, StorageDeviceInfo storageDeviceInfo) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageDeviceProperty, QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery }; + - SafeFileHandle safeHandleRetry = null; - var isRetry = false; - - - StartGetData: - - StorageDeviceInfo newStorageDeviceInfo; - - // Get storage device info. - - using (var safeBuffer = InvokeDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) { - //if (null == safeBuffer) - //{ - // // Assumption through observation: devicePath is a logical drive that points to a Dynamic disk. - - - // var volDiskExtents = GetVolumeDiskExtents(isRetry ? safeHandleRetry : safeHandle, pathToDevice); - - // if (volDiskExtents.HasValue) - // { - // // Use the first disk extent. - - // pathToDevice = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Path.PhysicalDrivePrefix, volDiskExtents.Value.Extents[0].DiskNumber.ToString(CultureInfo.InvariantCulture)); - - - // safeHandleRetry = FileSystemHelper.OpenPhysicalDisk(pathToDevice, FileSystemRights.Read); - - // isRetry = Utils.IsValidHandle(safeHandleRetry, false); - // } - - - // if (isRetry) - // goto StartGetData; - - // return null; - //} - - var deviceDescriptor = safeBuffer.PtrToStructure(); - newStorageDeviceInfo = new StorageDeviceInfo - { - DeviceType = storageDeviceInfo.DeviceType, - - DeviceNumber = storageDeviceInfo.DeviceNumber, + storageDeviceInfo.BusType = (StorageBusType) deviceDescriptor.BusType; - PartitionNumber = storageDeviceInfo.PartitionNumber, + storageDeviceInfo.CommandQueueing = deviceDescriptor.CommandQueueing; + storageDeviceInfo.ProductId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductIdOffset).Trim(); - BusType = (StorageBusType) deviceDescriptor.BusType, + storageDeviceInfo.ProductRevision = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductRevisionOffset).Trim(); - CommandQueueing = deviceDescriptor.CommandQueueing, - - ProductId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductIdOffset).Trim(), + storageDeviceInfo.RemovableMedia = deviceDescriptor.RemovableMedia; - ProductRevision = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductRevisionOffset).Trim(), + storageDeviceInfo.SerialNumber = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(); - RemovableMedia = deviceDescriptor.RemovableMedia, + storageDeviceInfo.VendorId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.VendorIdOffset).Trim(); - SerialNumber = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(), - VendorId = safeBuffer.PtrToStringAnsi((int)deviceDescriptor.VendorIdOffset).Trim() - }; + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.ProductRevision) || storageDeviceInfo.ProductRevision.Length == 1) + storageDeviceInfo.ProductRevision = null; - - if (Utils.IsNullOrWhiteSpace(newStorageDeviceInfo.ProductRevision) || newStorageDeviceInfo.ProductRevision.Length == 1) - newStorageDeviceInfo.ProductRevision = null; - - if (Utils.IsNullOrWhiteSpace(newStorageDeviceInfo.SerialNumber) || newStorageDeviceInfo.SerialNumber.Length == 1) - newStorageDeviceInfo.SerialNumber = null; + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.SerialNumber) || storageDeviceInfo.SerialNumber.Length == 1) + storageDeviceInfo.SerialNumber = null; - if (Utils.IsNullOrWhiteSpace(newStorageDeviceInfo.VendorId) || newStorageDeviceInfo.VendorId.Length == 1) - newStorageDeviceInfo.VendorId = null; + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.VendorId) || storageDeviceInfo.VendorId.Length == 1) + storageDeviceInfo.VendorId = null; } - using (var safeBuffer = GetDeviceIoData(isRetry ? safeHandleRetry : safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, pathToDevice)) - - newStorageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; - + // Get disk total size. - if (isRetry && !safeHandleRetry.IsClosed) - safeHandleRetry.Close(); + if (isElevated) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, localDevicePath)) - return newStorageDeviceInfo; + storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; } } } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 228958686..dbbf00ed0 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -21,6 +21,7 @@ using System; using System.Runtime.InteropServices; +using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; @@ -31,7 +32,7 @@ namespace Alphaleonis.Win32.Device public static partial class Local { /// [AlphaFS] Retrieves information about the partitions on a disk and the features of each partition. - /// Returns a instance that represent the partition info on the Computer that is related to . + /// Returns a instance that represent the partition info that is related to . /// /// /// @@ -40,8 +41,9 @@ public static partial class Local /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// + [SecurityCritical] public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) { return GetStoragePartitionInfo(ProcessContext.IsElevatedProcess, devicePath); @@ -49,7 +51,7 @@ public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) /// [AlphaFS] Retrieves information about the partitions on a disk and the features of each partition. - /// Returns a instance that represent the partition info on the Computer that is related to . + /// Returns a instance that represent the partition info that is related to . /// /// /// @@ -59,22 +61,28 @@ public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\pcistor#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// + [SecurityCritical] public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, string devicePath) { - var pathToDevice = FileSystemHelper.GetDevicePath(devicePath); + bool isDrive; + bool isVolume; + bool isDevice; - if (Utils.IsNullOrWhiteSpace(pathToDevice)) - return null; + var validatedDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + + if (isDrive) + validatedDevicePath = FileSystemHelper.GetLocalDevicePath(validatedDevicePath); - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(pathToDevice, isElevated ? FileSystemRights.Read : Filesystem.NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(validatedDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) return GetStoragePartitionInfoNative(safeHandle, devicePath); } + [SecurityCritical] private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandle, string pathForException) { var volDiskExtents = GetVolumeDiskExtents(safeHandle, pathForException); @@ -116,6 +124,7 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle } + [SecurityCritical] /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeHandle, string pathForException) { diff --git a/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs b/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs index 9d86da057..9ba3e5644 100644 --- a/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs @@ -21,6 +21,7 @@ using System; using System.Runtime.InteropServices; +using System.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device @@ -28,6 +29,7 @@ namespace Alphaleonis.Win32.Device public static partial class Local { /// Retrieves the physical location and disk number of a specified volume on one or more disks. + [SecurityCritical] private static NativeMethods.VOLUME_DISK_EXTENTS? GetVolumeDiskExtents(SafeFileHandle safeHandle, string pathForException) { var structSize = Marshal.SizeOf(typeof(NativeMethods.DISK_EXTENT_SINGLE)); diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs index 3083eaffa..16cf400f2 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.Constants.cs @@ -69,9 +69,5 @@ internal static partial class NativeMethods /// Invalid FileAttributes = -1 internal const FileAttributes InvalidFileAttributes = (FileAttributes) (-1); - - - /// FILE_ANY_ACCESS = 0 - internal const int FILE_ANY_ACCESS = 0; } } diff --git a/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs b/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs index 488c5d9c9..9d60f32f3 100644 --- a/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs +++ b/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs @@ -25,8 +25,8 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Path { - /// [AlphaFS] Checks if is in a logical drive format, such as "C:", "D:". - /// true when is in a logical drive format, such as "C:", "D:". + /// [AlphaFS] Checks if is in a logical drive format, such as C:, D: + /// true when is in a logical drive format, such as C:, D: /// /// /// The absolute path to check. @@ -36,8 +36,8 @@ public static bool IsLogicalDrive(string path) } - /// [AlphaFS] Checks if is in a logical drive format, such as "C:", "D:". - /// true when is in a logical drive format, such as "C:", "D:". + /// [AlphaFS] Checks if is in a logical drive format, such as C:, D: + /// true when is in a logical drive format, such as C:, D: /// /// /// The absolute path to check. From a46184dcacf2e48948f29aabf11bef0a9921dca0 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 11 Jun 2018 12:20:54 +0200 Subject: [PATCH 099/133] Code improvement. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 11 ++++ ...DiskInfo_UsingDevicePathFromSystemDrive.cs | 3 - ...pterInfo_UsingDevicePathFromSystemDrive.cs | 2 - ...viceInfo_UsingDevicePathFromSystemDrive.cs | 2 - .../AlphaFS_Volume.GetXxx.cs | 24 +++++-- .../Local.EnumeratePhysicalDisks.cs | 16 ++--- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 62 +++++-------------- .../Storage/Local.GetStorageAdapterInfo.cs | 16 ++--- .../Storage/Local.GetStorageDeviceInfo.cs | 16 ++--- .../Storage/Local.GetStoragePartitionInfo.cs | 51 +++++++-------- .../Filesystem/Path Class/Path.Constants.cs | 2 - 11 files changed, 88 insertions(+), 117 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index 12b1ada39..558ec2a86 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -53,6 +53,17 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Local_Success() UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + // Show all partition information. + + if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) + foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, true); + + if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) + foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, true); + + Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs index b19fb49d3..490756d35 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs @@ -35,7 +35,6 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive_Su { UnitTestConstants.PrintUnitTestHeader(false); - var deviceCount = 0; var sourceDrive = UnitTestConstants.SysDrive; @@ -67,8 +66,6 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive_Su Assert.IsNotNull(pDisk.VolumeGuids); - Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(pDisk.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceDrive)); Assert.AreEqual(pDisk.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceVolume)); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs index b0a83e908..9fcc80b5f 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs @@ -54,8 +54,6 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingDevicePathFromSystemDrive_ Assert.IsNotNull(pDisk); - Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - if (Alphaleonis.Win32.Security.ProcessContext.IsElevatedProcess) { diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs index 72b16399b..d52a233dc 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs @@ -54,8 +54,6 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingDevicePathFromSystemDrive_S Assert.IsNotNull(pDisk); - Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(pDisk.StorageDeviceInfo, storageDeviceInfo); } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs index c3cce6a3a..8374a3132 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs @@ -44,17 +44,23 @@ public void AlphaFS_Volume_GetXxx_Local_Success() foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { + var isCDRom = driveInfo.DriveType == System.IO.DriveType.CDRom; + var isNetwork = driveInfo.DriveType == System.IO.DriveType.Network; + var isNoRootDirectory = driveInfo.DriveType == System.IO.DriveType.NoRootDirectory; + + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\n", ++logicalDriveCount, driveInfo.Name); - if (driveInfo.DriveType == System.IO.DriveType.CDRom) + + if (isCDRom) { - Console.WriteLine(); + Console.WriteLine("\t\tSkipped CDRom drive\n"); continue; } - + // GetVolumeDeviceName: "C:\" --> "\Device\HarddiskVolume4" var deviceNameFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumeDeviceName(driveInfo.Name); @@ -65,11 +71,17 @@ public void AlphaFS_Volume_GetXxx_Local_Success() Assert.IsNotNull(deviceNameFromLogicalDrive); - // Skip mapped drives and network drives. + if (isNetwork) + { + Assert.IsTrue(deviceNameFromLogicalDrive.StartsWith(Alphaleonis.Win32.Filesystem.Path.DosDeviceLanmanPrefix + @";" + driveInfo.Name[0] + ":", StringComparison.OrdinalIgnoreCase)); + } + + + - if (driveInfo.DriveType != System.IO.DriveType.NoRootDirectory && driveInfo.DriveType != System.IO.DriveType.Network) + if (!isNoRootDirectory && !isNetwork) { - Assert.IsTrue(deviceNameFromLogicalDrive.StartsWith(deviceNamePrefix)); + Assert.IsTrue(deviceNameFromLogicalDrive.StartsWith(deviceNamePrefix, StringComparison.OrdinalIgnoreCase)); // GetVolumeGuid: "C:\" --> "\\?\Volume{db5044f9-bd1f-4243-ab97-4b985eb29e80}\" diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 6b9fd45d6..4fd388ab9 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -67,15 +67,15 @@ internal static IEnumerable EnumeratePhysicalDisksCore(bool is driveTypes = new[] {DriveType.CDRom, DriveType.Fixed, DriveType.Removable}; - var physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => CreatePhysicalDiskInfo(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + var physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => NewPhysicalDiskInfo(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); - var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => CreatePhysicalDiskInfo(false, volumeGuid, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => NewPhysicalDiskInfo(isElevated, volumeGuid, null)).Where(physicalDisk => null != physicalDisk).ToArray(); var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false) .Select(driveName => new DriveInfo(driveName)).Where(driveInfo => {return driveTypes.Any(driveType => driveInfo.DriveType == driveType);}) - .Select(driveInfo => CreatePhysicalDiskInfo(false, driveInfo.Name, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + .Select(driveInfo => NewPhysicalDiskInfo(isElevated, driveInfo.Name, null)).Where(physicalDisk => null != physicalDisk).ToArray(); foreach (var pDisk in physicalDisks) @@ -85,7 +85,7 @@ internal static IEnumerable EnumeratePhysicalDisksCore(bool is //// Windows Disk Management shows CD-ROM so mimic that behaviour. - //var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => CreatePhysicalDiskInfo(isElevated, null, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + //var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => NewPhysicalDiskInfo(isElevated, null, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); //foreach (var pCdRom in cdRoms) @@ -100,17 +100,17 @@ private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, Phy foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber)) { - var volumeDriveNumber = pVolume.StorageDeviceInfo.DeviceNumber; + var driveNumber = pVolume.StorageDeviceInfo.DeviceNumber; - var volumePartitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; + var partitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; - PopulateVolumeDetails(pDiskInfo, volumePartitionNumber, pVolume.DevicePath); + PopulateVolumeDetails(pDiskInfo, partitionNumber, pVolume.DevicePath); // Get logical drive from volume matching DeviceNumber and PartitionNumber. - foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == volumeDriveNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == volumePartitionNumber)) + foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == driveNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == partitionNumber)) PopulateLogicalDriveDetails(pDiskInfo, pLogicalDrive.DevicePath); } diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index 9fa28fc52..1faea91b9 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -84,40 +84,28 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(bool isElevated, string devic validatedDevicePath = FileSystemHelper.GetLocalDevicePath(validatedDevicePath); - var storageDeviceInfo = GetStorageDeviceInfo(isElevated, validatedDevicePath); + // We need the StorageDeviceInfo to locate our input path. - if (null == storageDeviceInfo) - return null; - + var storageDeviceInfo = GetStorageDeviceInfo(isElevated, validatedDevicePath); // Get the PhysicalDiskInfo instance. - var pDiskInfo = isDevice + var pDiskInfo = null == storageDeviceInfo ? null : isDevice ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => pDisk.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber && pDisk.StorageDeviceInfo.PartitionNumber == storageDeviceInfo.PartitionNumber) : isVolume - ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => null != pDisk.VolumeGuids && pDisk.ContainsVolume(validatedDevicePath)) + ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => pDisk.ContainsVolume(validatedDevicePath)) : isDrive - ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => null != pDisk.LogicalDrives && pDisk.ContainsVolume(validatedDevicePath)) + ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => pDisk.ContainsVolume(validatedDevicePath)) : null; if (null != pDiskInfo) { - // Use the storageDeviceInfo instance created earlier because it is based on the input path. - pDiskInfo.StorageDeviceInfo = storageDeviceInfo; - - // Accessing the device by its path: \\?\scsi#disk&ven_sandisk&prod... - // does not relate to any drive or volume, so the default PartitionNumber of 0 is misleading. - - if (isDevice && pDiskInfo.StorageDeviceInfo.PartitionNumber == 0) - pDiskInfo.StorageDeviceInfo.PartitionNumber = -1; - - if (null == pDiskInfo.StoragePartitionInfo) pDiskInfo.StoragePartitionInfo = GetStoragePartitionInfo(isElevated, validatedDevicePath); } @@ -149,22 +137,26 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(bool isElevated, string devic /// Use either or , not both. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDiskInfo CreatePhysicalDiskInfo(bool isElevated, string devicePath, DeviceInfo deviceInfo) + private static PhysicalDiskInfo NewPhysicalDiskInfo(bool isElevated, string devicePath, DeviceInfo deviceInfo) { + if (devicePath == null && deviceInfo == null) + return null; + var isDevice = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); if (isDevice) devicePath = deviceInfo.DevicePath; + + var pDiskInfo = new PhysicalDiskInfo + { + StorageAdapterInfo = GetStorageAdapterInfo(isElevated, devicePath), - var storageDeviceInfo = GetStorageDeviceInfo(isElevated, devicePath); + StorageDeviceInfo = GetStorageDeviceInfo(isElevated, devicePath), - if (null == storageDeviceInfo) - return null; + StoragePartitionInfo = GetStoragePartitionInfo(isElevated, devicePath), - var pDiskInfo = new PhysicalDiskInfo - { DevicePath = devicePath, DeviceDescription = isDevice ? deviceInfo.DeviceDescription : null, @@ -172,31 +164,11 @@ internal static PhysicalDiskInfo CreatePhysicalDiskInfo(bool isElevated, string Name = isDevice ? deviceInfo.FriendlyName : null, PhysicalDeviceObjectName = isDevice ? deviceInfo.PhysicalDeviceObjectName : null, - - - StorageAdapterInfo = isDevice ? new StorageAdapterInfo {BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription} : null, - - - // Use the storageDeviceInfo instance created earlier because it is based on the input path. - - StorageDeviceInfo = storageDeviceInfo }; - // When elevated, get populated StorageAdapterInfo and StorageDeviceInfo instances. - - if (isElevated) - { - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(devicePath, FileSystemRights.Read)) - { - pDiskInfo.StorageAdapterInfo = GetStorageAdapterInfoNative(safeHandle, devicePath); - - // Use the storageDeviceInfo instance created earlier because it is based on the input path. - //pDiskInfo.StorageDeviceInfo = SetStorageDeviceInfoData(safeHandle, devicePath, pDiskInfo.StorageDeviceInfo); - - pDiskInfo.StoragePartitionInfo = GetStoragePartitionInfoNative(safeHandle, devicePath); - } - } + if (isDevice) + pDiskInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; return pDiskInfo; diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index a4b02709d..072008e3e 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -76,26 +76,18 @@ public static StorageAdapterInfo GetStorageAdapterInfo(bool isElevated, string d validatedDevicePath = FileSystemHelper.GetLocalDevicePath(validatedDevicePath); - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(validatedDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - - return GetStorageAdapterInfoNative(safeHandle, devicePath); - } - - - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - [SecurityCritical] - private static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle safeHandle, string pathToDevice) - { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery }; + + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(validatedDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathToDevice, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, validatedDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) { - return new StorageAdapterInfo(safeBuffer.PtrToStructure()); + return null == safeBuffer ? null : new StorageAdapterInfo(safeBuffer.PtrToStructure()); } } } diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index b13885df1..7c24f0a39 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -83,21 +83,13 @@ public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string dev { using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath)) - storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure()); + storageDeviceInfo = null != safeBuffer ? new StorageDeviceInfo(safeBuffer.PtrToStructure()) : null; - SetStorageDeviceInfoData(isElevated, safeHandle, localDevicePath, storageDeviceInfo); + if (null != storageDeviceInfo) + SetStorageDeviceInfoData(isElevated, safeHandle, localDevicePath, storageDeviceInfo); } - - - // Accessing the device by its path: \\?\scsi#disk&ven_sandisk&prod... - // does not relate to any drive or volume, so the default PartitionNumber of 0 is misleading. - - if (isDevice && storageDeviceInfo.PartitionNumber == 0) - - storageDeviceInfo.PartitionNumber = -1; - - + return storageDeviceInfo; } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index dbbf00ed0..bb94def36 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -70,15 +70,15 @@ public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, stri bool isVolume; bool isDevice; - var validatedDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); if (isDrive) - validatedDevicePath = FileSystemHelper.GetLocalDevicePath(validatedDevicePath); + localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(validatedDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - return GetStoragePartitionInfoNative(safeHandle, devicePath); + return GetStoragePartitionInfoNative(safeHandle, localDevicePath); } @@ -89,43 +89,44 @@ private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle if (null == volDiskExtents || volDiskExtents.Value.NumberOfDiskExtents == 0) return null; - + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, pathForException, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) - { - var layout = safeBuffer.PtrToStructure(); - - // Sanity check. - if (layout.PartitionCount <= 256) + if (null != safeBuffer) { - var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 + var layout = safeBuffer.PtrToStructure(); + + // Sanity check. + if (layout.PartitionCount <= 256) + { + var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 + + var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 - var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 + var partitions = new NativeMethods.PARTITION_INFORMATION_EX[layout.PartitionCount]; - var partitions = new NativeMethods.PARTITION_INFORMATION_EX[layout.PartitionCount]; - - for (var i = 0; i <= layout.PartitionCount - 1; i++) + for (var i = 0; i <= layout.PartitionCount - 1; i++) - partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); + partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); - var disk = GetDiskGeometryExNative(safeHandle, pathForException); + var disk = GetDiskGeometryExNative(safeHandle, pathForException); - // Use the first disk extent. - var diskNumber = volDiskExtents.Value.Extents[0].DiskNumber; + // Use the first disk extent. + var diskNumber = volDiskExtents.Value.Extents[0].DiskNumber; - return new StoragePartitionInfo((int) diskNumber, disk, layout, partitions); + return new StoragePartitionInfo((int) diskNumber, disk, layout, partitions); + } } - } return null; } - [SecurityCritical] /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). + [SecurityCritical] private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeHandle, string pathForException) { var bufferSize = 128; @@ -133,7 +134,7 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHa while (true) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) { - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); @@ -151,9 +152,9 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHa }; - var offset = (uint) sizeOf + sizeof(long); // 32 + var offset = (uint)sizeOf + sizeof(long); // 32 - diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure((int) offset); + diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure((int)offset); //// Intermittently throws: System.AccessViolationException: Attempted to read or write protected memory. diff --git a/AlphaFS/Filesystem/Path Class/Path.Constants.cs b/AlphaFS/Filesystem/Path Class/Path.Constants.cs index 9f79fb86e..60101c744 100644 --- a/AlphaFS/Filesystem/Path Class/Path.Constants.cs +++ b/AlphaFS/Filesystem/Path Class/Path.Constants.cs @@ -128,12 +128,10 @@ public static partial class Path /// [AlphaFS] DosDeviceLanmanPrefix = "\Device\LanmanRedirector\" Provides a MS-Dos Lanman Redirector Path UNC prefix to a network share. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lanman")] - [Obsolete("Unused")] public static readonly string DosDeviceLanmanPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", DevicePrefix, "LanmanRedirector", DirectorySeparatorChar); /// [AlphaFS] DosDeviceMupPrefix = "\Device\Mup\" Provides a MS-Dos Mup Redirector Path UNC prefix to a network share. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mup")] - [Obsolete("Unused")] public static readonly string DosDeviceMupPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", DevicePrefix, "Mup", DirectorySeparatorChar); From baa4d8274f9814d60f425028f89a2b58dd64435f Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 11 Jun 2018 23:33:34 +0200 Subject: [PATCH 100/133] Code improvement. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 7 + ...InitializeInstanceUsingLogicalDrivePath.cs | 136 +++++++++++++++ ...tializeInstanceUsingPhysicalDriveNumber.cs | 57 +++++++ .../AlphaFS_Volume.GetDriveFormat.cs | 6 +- ...haFS_Volume.GetDriveNameForNtDeviceName.cs | 6 +- .../AlphaFS_Volume.GetDriveType.cs | 6 +- ...phaFS_Volume.GetUniqueVolumeNameForPath.cs | 6 +- ...ume.GetVolumeInfo_UsingLogicalDrivePath.cs | 6 +- ...me.GetVolumeLabel_UsingLogicalDrivePath.cs | 6 +- .../AlphaFS_Volume.GetXxx.cs | 40 +++-- .../AlphaFS_Device.EnumerateDevices.cs | 2 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 2 + .../AlphaFS_File.GetChangeTime.cs | 2 +- AlphaFS/AlphaFS.csproj | 2 + ...FileSystemHelper.GetValidatedDevicePath.cs | 12 +- AlphaFS/Device/Local.EnumerateDevices.cs | 4 +- .../NativeMethods.VolumeManagement.cs | 2 +- .../PhysicalDisk/Device.PhysicalDiskInfo.cs | 161 +++++++----------- .../Device.PhysicalDiskInfo_Methods.cs | 63 +++++++ .../Device.PhysicalDiskInfo_Properties.cs | 74 ++++++++ .../Local.EnumeratePhysicalDisks.cs | 50 +----- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 115 +++++-------- .../Device/Storage/Local.GetDeviceIoData.cs | 2 +- .../Storage/Local.GetStorageDeviceInfo.cs | 29 +++- .../Storage/Local.GetStoragePartitionInfo.cs | 31 +++- AlphaFS/Device/Test.cs | 2 +- AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs | 2 +- .../Device/Volume/Volume.GetVolumePathName.cs | 2 +- AlphaFS/Filesystem/File Class/File.Copy.cs | 2 +- .../File Class/File.CreateSymbolicLink.cs | 2 +- .../Filesystem/File Class/File.WriteText.cs | 32 ++-- AlphaFS/Filesystem/FindFileSystemEntryInfo.cs | 4 +- .../Link Stream/BackupFileStream.cs | 2 +- .../Path.GetFinalPathNameByHandle.cs | 2 +- AlphaFS/Filesystem/Path Class/Path.Helpers.cs | 10 +- .../Path Class/Path.IsLogicalDrive.cs | 2 +- AlphaFS/Filesystem/Shell32.cs | 6 +- AlphaFS/NativeError.cs | 2 +- AlphaFS/Security/InternalPrivilegeEnabler.cs | 2 +- AlphaFS/Utils.cs | 34 +++- AlphaFS/Win32Errors.cs | 2 +- CHANGELOG.md | 14 +- 42 files changed, 639 insertions(+), 310 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs create mode 100644 AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Methods.cs create mode 100644 AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Properties.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index 558ec2a86..5376c6398 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -37,9 +37,16 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Local_Success() var pDriveCount = 0; + var physicalDrives = Alphaleonis.Win32.Filesystem.Volume.QueryAllDosDevices().Where(device => device.StartsWith("PhysicalDrive", StringComparison.OrdinalIgnoreCase)).ToArray(); + var pDrives = Alphaleonis.Win32.Device.Local.EnumeratePhysicalDisks().OrderBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber).ThenBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.PartitionNumber).ToArray(); + Console.WriteLine("Found: [{0}] physical drives.\n", physicalDrives.Length); + + Assert.AreEqual(physicalDrives.Length, pDrives.Length); + + foreach (var pDisk in pDrives) { Console.WriteLine("#{0:000}\tPhysical Disk: [{1}]\t\t{2}\t\t{3}", ++pDriveCount, pDisk.StorageDeviceInfo.DeviceNumber, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs new file mode 100644 index 000000000..68475175d --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs @@ -0,0 +1,136 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_PhysicalDiskInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Local_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + //var gotDisk = false; + var driveCount = 0; + + foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) + { + // System.UnauthorizedAccessException: (5) Access is denied. + if (driveInfo.DriveType == System.IO.DriveType.Network) + { + Console.WriteLine("#{0:000}\tSkipped Network drive: [{1}]\n", ++driveCount, driveInfo.Name); + continue; + } + + + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); + + + //var pDisk = new Alphaleonis.Win32.Device.PhysicalDiskInfo(driveInfo.Name); + + //UnitTestConstants.Dump(pDisk); + + + //// Works with System.IO.DriveType.CDRom. + + + + //if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) + //{ + // Console.WriteLine("#{0:000}\tSkipped NoRootDirectory drive: [{1}]\n", ++driveCount, driveInfo.Name); + // continue; + //} + + + //var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(driveInfo.Name); + + + //Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, pDisk.StorageAdapterInfo.ToString()); + + //UnitTestConstants.Dump(pDisk); + + //UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); + + //UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + + //UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + + + //Assert.IsNotNull(pDisk); + + //Assert.IsNotNull(pDisk.LogicalDrives); + + //Assert.IsNotNull(pDisk.VolumeGuids); + + + //if (pDisk.StorageDeviceInfo.PartitionNumber == -1) + // Assert.IsNull(pDisk.StoragePartitionInfo); + //else + // Assert.IsNotNull(pDisk.StoragePartitionInfo); + + + //// For CDRom, the PartitionNumber is always -1. + + //if (pDisk.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) + //{ + // Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + // Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.CDRom, pDisk.StorageDeviceInfo.DeviceType); + //} + + //else + // Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + + + //Assert.AreEqual(pDisk.LogicalDrives.Contains(driveInfo.Name.TrimEnd('\\'), StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(driveInfo.Name)); + + + //// Show all partition information. + + //if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) + //{ + // gotDisk = true; + + // foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) + // UnitTestConstants.Dump(partition, true); + //} + + //if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) + //{ + // gotDisk = true; + + // foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) + // UnitTestConstants.Dump(partition, true); + //} + + Console.WriteLine(); + + //Assert.IsTrue(gotDisk); + } + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs new file mode 100644 index 000000000..92047f3b2 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs @@ -0,0 +1,57 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_PhysicalDiskInfoTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingPhysicalDriveNumber_Local_Success() + { + UnitTestConstants.PrintUnitTestHeader(false); + + var driveCount = 0; + + var physicalDisks = Alphaleonis.Win32.Filesystem.Volume.QueryAllDosDevices().Where(device => device.StartsWith("PhysicalDrive", StringComparison.OrdinalIgnoreCase)).ToArray(); + + Console.WriteLine("Found: [{0}] physical drives.\n", physicalDisks.Length); + + + for (var physicalDiskNumber = 0; physicalDiskNumber < physicalDisks.Length; physicalDiskNumber++) + { + Console.WriteLine("#{0:000}\tInput Physical Disk Number: [{1}]", ++driveCount, physicalDiskNumber); + + var pDisk = new Alphaleonis.Win32.Device.PhysicalDiskInfo(physicalDiskNumber); + + UnitTestConstants.Dump(pDisk); + + Console.WriteLine(); + } + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs index 2f2414316..4ea93774b 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveFormat.cs @@ -42,13 +42,13 @@ private void AlphaFS_Volume_GetDriveFormat(bool isNetwork) UnitTestConstants.PrintUnitTestHeader(isNetwork); - var logicalDriveCount = 0; + var driveCount = 0; foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { var driveName = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(driveInfo.Name) : driveInfo.Name; - Console.Write("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveName); + Console.Write("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveName); var driveFormat = Alphaleonis.Win32.Filesystem.Volume.GetDriveFormat(driveName); @@ -64,7 +64,7 @@ private void AlphaFS_Volume_GetDriveFormat(bool isNetwork) } - Assert.IsTrue(logicalDriveCount > 0, "No logical drives enumerated, but it is expected."); + Assert.IsTrue(driveCount > 0, "No logical drives enumerated, but it is expected."); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs index 18105a0bf..819516bb9 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs @@ -35,7 +35,7 @@ public void AlphaFS_Volume_GetDriveNameForNtDeviceName_And_GetVolumeGuidForNtDev UnitTestConstants.PrintUnitTestHeader(false); - var logicalDriveCount = 0; + var driveCount = 0; foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { @@ -52,7 +52,7 @@ public void AlphaFS_Volume_GetDriveNameForNtDeviceName_And_GetVolumeGuidForNtDev var deviceGuid = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(driveName); - Console.WriteLine("#{0:000}\tInput Path: [{1}]", ++logicalDriveCount, dosDeviceName); + Console.WriteLine("#{0:000}\tInput Path: [{1}]", ++driveCount, dosDeviceName); @@ -74,7 +74,7 @@ public void AlphaFS_Volume_GetDriveNameForNtDeviceName_And_GetVolumeGuidForNtDev } - if (logicalDriveCount == 0) + if (driveCount == 0) UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveType.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveType.cs index c30e4475e..773f9918e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveType.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveType.cs @@ -42,13 +42,13 @@ private void AlphaFS_Volume_GetDriveType(bool isNetwork) UnitTestConstants.PrintUnitTestHeader(isNetwork); - var logicalDriveCount = 0; + var driveCount = 0; foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { var driveName = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(driveInfo.Name) : driveInfo.Name; - Console.Write("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveName); + Console.Write("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveName); if (driveInfo.DriveType == System.IO.DriveType.CDRom) { @@ -73,7 +73,7 @@ private void AlphaFS_Volume_GetDriveType(bool isNetwork) } - Assert.IsTrue(logicalDriveCount > 0, "No logical drives enumerated, but it is expected."); + Assert.IsTrue(driveCount > 0, "No logical drives enumerated, but it is expected."); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs index 93eb96d7c..ce16aa589 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs @@ -36,7 +36,7 @@ public void AlphaFS_Volume_GetUniqueVolumeNameForPath_Local_Success() UnitTestConstants.PrintUnitTestHeader(false); - var logicalDriveCount = 0; + var driveCount = 0; foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { @@ -50,7 +50,7 @@ public void AlphaFS_Volume_GetUniqueVolumeNameForPath_Local_Success() var deviceGuid = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(driveName); - Console.WriteLine("#{0:000}\tInput Path: [{1}]", ++logicalDriveCount, driveName); + Console.WriteLine("#{0:000}\tInput Path: [{1}]", ++driveCount, driveName); var volumeNameResult = Alphaleonis.Win32.Filesystem.Volume.GetUniqueVolumeNameForPath(driveName); @@ -90,7 +90,7 @@ public void AlphaFS_Volume_GetUniqueVolumeNameForPath_Local_Success() } - if (logicalDriveCount == 0) + if (driveCount == 0) UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs index 03e719600..540f62c29 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeInfo_UsingLogicalDrivePath.cs @@ -42,13 +42,13 @@ private void AlphaFS_Volume_GetVolumeInfo_UsingLogicalDrivePath(bool isNetwork) UnitTestConstants.PrintUnitTestHeader(isNetwork); - var logicalDriveCount = 0; + var driveCount = 0; foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { var driveName = isNetwork ? Alphaleonis.Win32.Filesystem.Path.LocalToUnc(driveInfo.Name) : driveInfo.Name; - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveName); + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveName); //// Skip mapped drives and CDRom drives. @@ -119,7 +119,7 @@ private void AlphaFS_Volume_GetVolumeInfo_UsingLogicalDrivePath(bool isNetwork) } - Assert.IsTrue(logicalDriveCount > 0, "No logical drives enumerated, but it is expected."); + Assert.IsTrue(driveCount > 0, "No logical drives enumerated, but it is expected."); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeLabel_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeLabel_UsingLogicalDrivePath.cs index 9d8fdc518..7eb5b4a16 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeLabel_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetVolumeLabel_UsingLogicalDrivePath.cs @@ -35,7 +35,7 @@ public void AlphaFS_Volume_GetVolumeLabel_UsingLogicalDrivePath_Local_Success() UnitTestConstants.PrintUnitTestHeader(false); - var logicalDriveCount = 0; + var driveCount = 0; foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { @@ -43,7 +43,7 @@ public void AlphaFS_Volume_GetVolumeLabel_UsingLogicalDrivePath_Local_Success() continue; - Console.Write("#{0:000}\tInput Logical Drive Path: [{1}]", ++logicalDriveCount, driveInfo.Name); + Console.Write("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); var volumeLabel = Alphaleonis.Win32.Filesystem.Volume.GetVolumeLabel(driveInfo.Name); @@ -55,7 +55,7 @@ public void AlphaFS_Volume_GetVolumeLabel_UsingLogicalDrivePath_Local_Success() } - Assert.IsTrue(logicalDriveCount > 0, "No logical drives enumerated, but it is expected."); + Assert.IsTrue(driveCount > 0, "No logical drives enumerated, but it is expected."); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs index 8374a3132..8f2b91f25 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs @@ -39,7 +39,7 @@ public void AlphaFS_Volume_GetXxx_Local_Success() var volumePrefix = Alphaleonis.Win32.Filesystem.Path.VolumePrefix + "{"; - var logicalDriveCount = 0; + var driveCount = 0; foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) @@ -49,15 +49,8 @@ public void AlphaFS_Volume_GetXxx_Local_Success() var isNoRootDirectory = driveInfo.DriveType == System.IO.DriveType.NoRootDirectory; - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\n", ++logicalDriveCount, driveInfo.Name); - - - if (isCDRom) - { - Console.WriteLine("\t\tSkipped CDRom drive\n"); - continue; - } - + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\n", ++driveCount, driveInfo.Name); + @@ -81,7 +74,14 @@ public void AlphaFS_Volume_GetXxx_Local_Success() if (!isNoRootDirectory && !isNetwork) { - Assert.IsTrue(deviceNameFromLogicalDrive.StartsWith(deviceNamePrefix, StringComparison.OrdinalIgnoreCase)); + + if (isCDRom) + Assert.IsTrue(deviceNameFromLogicalDrive.StartsWith(Alphaleonis.Win32.Filesystem.Path.DevicePrefix, StringComparison.OrdinalIgnoreCase)); + + else + Assert.IsTrue(deviceNameFromLogicalDrive.StartsWith(deviceNamePrefix, StringComparison.OrdinalIgnoreCase)); + + // GetVolumeGuid: "C:\" --> "\\?\Volume{db5044f9-bd1f-4243-ab97-4b985eb29e80}\" @@ -109,18 +109,24 @@ public void AlphaFS_Volume_GetXxx_Local_Success() } - // GetVolumePathName: "C:\" or "C:\Windows" --> "C:\" + if (isCDRom) + Console.WriteLine("\tSkipped Logical Drive.\n"); - var volumePathNameFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumePathName(driveInfo.Name); + else + { + // GetVolumePathName: "C:\" or "C:\Windows" --> "C:\" + + var volumePathNameFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumePathName(driveInfo.Name); - Console.WriteLine("\tGetVolumePathName\t\t\t: [{0}]\n", volumePathNameFromLogicalDrive); + Console.WriteLine("\tGetVolumePathName\t\t\t: [{0}]\n", volumePathNameFromLogicalDrive); - Assert.IsNotNull(volumePathNameFromLogicalDrive); + Assert.IsNotNull(volumePathNameFromLogicalDrive); - Assert.AreEqual(driveInfo.Name, volumePathNameFromLogicalDrive); + Assert.AreEqual(driveInfo.Name, volumePathNameFromLogicalDrive); + } } - if (logicalDriveCount == 0) + if (driveCount == 0) UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs index 86694210c..f199dbc89 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs @@ -67,7 +67,7 @@ private static IEnumerable EnumMemberToList() { var enumType = typeof(T); - // Can't use generic type constraints on value types, so have to do check like this. + // Cannot 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"); diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 7c5093fd3..a07bc3fc1 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -156,7 +156,9 @@ + + diff --git a/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs b/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs index 600898697..5b2fe4b1a 100644 --- a/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs +++ b/AlphaFS.UnitTest/File Class/File_Timestamps/AlphaFS_File.GetChangeTime.cs @@ -57,7 +57,7 @@ private void AlphaFS_File_GetChangeTime(bool isNetwork) 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. + // We cannot 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(); diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 4c078e8ff..05a7fb9df 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -198,6 +198,8 @@ + + diff --git a/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs b/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs index 64dcb96ab..f8894a180 100644 --- a/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs +++ b/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs @@ -37,10 +37,20 @@ internal static string GetValidatedDevicePath(string devicePath, out bool isDriv throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "devicePath"); + if (devicePath.StartsWith(Path.PhysicalDrivePrefix, StringComparison.OrdinalIgnoreCase)) + { + isDrive = false; + isVolume = false; + isDevice = false; + + return devicePath; + } + + // Resolve single drive letter or get root directory information. devicePath = devicePath.Length == 1 ? devicePath + Path.VolumeSeparatorChar : Path.GetPathRoot(devicePath, false); - + var hasPath = !Utils.IsNullOrWhiteSpace(devicePath); diff --git a/AlphaFS/Device/Local.EnumerateDevices.cs b/AlphaFS/Device/Local.EnumerateDevices.cs index b425f30ba..6971c73be 100644 --- a/AlphaFS/Device/Local.EnumerateDevices.cs +++ b/AlphaFS/Device/Local.EnumerateDevices.cs @@ -69,7 +69,7 @@ public static IEnumerable EnumerateDevices(string hostName, DeviceGu /// One of the devices. /// true to retrieve all device properties. [SecurityCritical] - internal static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid deviceGuid, bool getAllProperties) + private static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid deviceGuid, bool getAllProperties) { if (Utils.IsNullOrWhiteSpace(hostName)) hostName = Environment.MachineName; @@ -192,7 +192,7 @@ private static string GetDeviceBusReportedDeviceDescription(SafeHandle safeHandl return null; - var bufferSize = Filesystem.NativeMethods.DefaultFileBufferSize / 32; // 128 + const int bufferSize = Filesystem.NativeMethods.DefaultFileBufferSize / 32; // 128 var descriptionBuffer = new byte[bufferSize]; ulong propertyType = 0; diff --git a/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs b/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs index 257823df0..0bb3e2c94 100644 --- a/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs @@ -219,7 +219,7 @@ internal static partial class NativeMethods /// /// Use GetVolumeNameForVolumeMountPoint to obtain a volume path for use with functions such as SetVolumeMountPoint and FindFirstVolumeMountPoint that require a volume path as an input parameter. /// SMB does not support volume management functions. - /// Mount points aren't supported by ReFS volumes. + /// Mount points are not supported by ReFS volumes. /// Minimum supported client: Windows XP [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] diff --git a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs index 7fcf7c01f..31ab51ecc 100644 --- a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs @@ -20,17 +20,17 @@ */ using System; -using System.Collections.Generic; -using System.Linq; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Security; using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Device { - /// [AlphaFS] Provides access to information of a physical disk. + /// [AlphaFS] Provides access to information of a physical disk on the Computer. [Serializable] [SecurityCritical] - public sealed class PhysicalDiskInfo + public sealed partial class PhysicalDiskInfo { #region Constructors @@ -40,103 +40,86 @@ public PhysicalDiskInfo() } - /// [AlphaFS] Initializes a PhysicalDiskInfo instance. - /// An initialized instance. - internal PhysicalDiskInfo(PhysicalDiskInfo physicalDiskInfo) + /// [AlphaFS] Initializes a PhysicalDiskInfo instance from a physical disk number such as: 0, 1, ... + /// A number that indicates a physical disk on the Computer. + public PhysicalDiskInfo(int deviceNumber) { - CopyTo(physicalDiskInfo, this); + if (deviceNumber < 0) + throw new ArgumentOutOfRangeException("deviceNumber"); + + Utils.CopyTo(Local.GetPhysicalDiskInfoCore(Security.ProcessContext.IsElevatedProcess, deviceNumber, null), this); } #endregion // Constructors - #region Properties - - /// The device description. - public string DeviceDescription { get; internal set; } - - - /// The path to the device. - /// Returns a string that represents the path to the device. - /// A drive path such as: C:, D:\, - /// a volume path such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// or a string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string. - /// - public string DevicePath { get; internal set; } - - - /// An of logical drives that are located on the physical disk. - public ICollection LogicalDrives { get; internal set; } - - - /// The "FriendlyName" of the physical disk. - public string Name { get; internal set; } - - - /// An of partition index numbers that are located on the physical disk. - public ICollection PartitionIndexes { get; internal set; } - - - /// Encapsulates the physical device location (PDO) information provided by a device's firmware to Windows. - public string PhysicalDeviceObjectName { get; internal set; } + /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . + /// A instance that represents the physical disk on the Computer or null on error/no data available. + /// + /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. + /// Do not call this method for every logical drive/volume on the Computer as each call queries all physical disks, associated volumes and logical drives. + /// Instead, use method and property or . + /// + /// + /// + /// + /// + /// true indicates the current process is in an elevated state, allowing to retrieve more data. + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + /// A instance. + /// Use either or , not both. + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] + [SecurityCritical] + internal static PhysicalDiskInfo InitializePhysicalDiskInfo(bool isElevated, string devicePath, DeviceInfo deviceInfo) + { + if (null == devicePath && null == deviceInfo) + return null; + var isDevice = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); - /// The storage device adapter information. Retrieving this information requires an elevated state. - public StorageAdapterInfo StorageAdapterInfo { get; internal set; } + if (isDevice) + devicePath = deviceInfo.DevicePath; - /// The storage device information. - public StorageDeviceInfo StorageDeviceInfo { get; internal set; } - - /// The storage device partitiion information. - public StoragePartitionInfo StoragePartitionInfo { get; internal set; } + var storageDeviceInfo = Local.GetStorageDeviceInfoCore(isElevated, devicePath); + if (null == storageDeviceInfo) + return null; - /// An of volume strings of volumes that are located on the physical disk. - public ICollection VolumeGuids { get; internal set; } + var pDiskInfo = new PhysicalDiskInfo + { + DevicePath = devicePath, - ///// An of volume label strings of volumes that are located on the physical disk. - //public ICollection VolumeLabels { get; internal set; } + DeviceDescription = isDevice ? deviceInfo.DeviceDescription : null, - #endregion // Properties + Name = isDevice ? deviceInfo.FriendlyName : null, + PhysicalDeviceObjectName = isDevice ? deviceInfo.PhysicalDeviceObjectName : null, - #region Methods - /// Checks if the volume or logical drive is located on the physical disk. - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// - /// true if the volume or logical drive is located on the physical disk; otherwise, false. - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// - public bool ContainsVolume(string devicePath) - { - bool isDrive; - bool isVolume; - bool isDeviceInfo; + StorageAdapterInfo = Local.GetStorageAdapterInfo(isElevated, devicePath), - devicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + StorageDeviceInfo = storageDeviceInfo, + StoragePartitionInfo = Local.GetStoragePartitionInfo(isElevated, devicePath) + }; - if (isDrive && null != LogicalDrives) - { - devicePath = devicePath.Replace(Path.LogicalDrivePrefix, string.Empty); - devicePath = Path.RemoveTrailingDirectorySeparator(devicePath, false); + if (isDevice) + pDiskInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; - return LogicalDrives.Any(driveName => driveName.Equals(devicePath, StringComparison.OrdinalIgnoreCase)); - } - - return isVolume && null != VolumeGuids && VolumeGuids.Any(guid => guid.Equals(devicePath, StringComparison.OrdinalIgnoreCase)); + return pDiskInfo; } + + /// Returns the "FriendlyName" of the physical disk. @@ -158,11 +141,8 @@ public override bool Equals(object obj) var other = obj as PhysicalDiskInfo; return null != other && null != other.DevicePath && null != other.StorageDeviceInfo && - other.DevicePath.Equals(DevicePath, StringComparison.OrdinalIgnoreCase) && - other.StorageDeviceInfo.Equals(StorageDeviceInfo) && - other.StorageDeviceInfo.DeviceNumber.Equals(StorageDeviceInfo.DeviceNumber) && other.StorageDeviceInfo.PartitionNumber.Equals(StorageDeviceInfo.PartitionNumber); } @@ -193,30 +173,5 @@ public override int GetHashCode() { return !(left == right); } - - - private static void CopyTo(T source, T destination) - { - // Properties listed here should not be overwritten by the physical disk template. - - //var excludedProps = new[] {"PartitionNumber"}; - - - //var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite && !excludedProps.Any(prop => prop.Equals(x.Name))).ToArray(); - - var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite).ToArray(); - - var dstProps = srcProps.ToArray(); - - - foreach (var srcProp in srcProps) - { - var dstProp = dstProps.First(x => x.Name.Equals(srcProp.Name)); - - dstProp.SetValue(destination, srcProp.GetValue(source, null), null); - } - } - - #endregion // Methods } } diff --git a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Methods.cs b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Methods.cs new file mode 100644 index 000000000..223a12d11 --- /dev/null +++ b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Methods.cs @@ -0,0 +1,63 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 Alphaleonis.Win32.Filesystem; + +namespace Alphaleonis.Win32.Device +{ + public sealed partial class PhysicalDiskInfo + { + /// Checks if the logical drive/volume is located on the physical disk. + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// + /// true if the logical drive/volume is located on the physical disk; otherwise, false. + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + public bool ContainsVolume(string devicePath) + { + bool isDrive; + bool isVolume; + bool isDeviceInfo; + + devicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDeviceInfo); + + + if (isDrive && null != LogicalDrives) + { + devicePath = devicePath.Replace(Path.LogicalDrivePrefix, string.Empty); + + devicePath = Path.RemoveTrailingDirectorySeparator(devicePath, false); + + return LogicalDrives.Any(driveName => driveName.Equals(devicePath, StringComparison.OrdinalIgnoreCase)); + } + + + return isVolume && null != VolumeGuids && VolumeGuids.Any(guid => guid.Equals(devicePath, StringComparison.OrdinalIgnoreCase)); + } + } +} diff --git a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Properties.cs b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Properties.cs new file mode 100644 index 000000000..b2739b139 --- /dev/null +++ b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Properties.cs @@ -0,0 +1,74 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 Alphaleonis.Win32.Filesystem; + +namespace Alphaleonis.Win32.Device +{ + public sealed partial class PhysicalDiskInfo + { + /// The device description. + public string DeviceDescription { get; internal set; } + + + /// The path to the device. + /// Returns a string that represents the path to the device. + /// A drive path such as: C:, D:\, + /// a volume path such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// or a string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string. + /// + public string DevicePath { get; internal set; } + + + /// An of logical drives that are located on the physical disk. + public ICollection LogicalDrives { get; internal set; } + + + /// The "FriendlyName" of the physical disk. + public string Name { get; internal set; } + + + /// An of partition index numbers that are located on the physical disk. + public ICollection PartitionIndexes { get; internal set; } + + + /// Encapsulates the physical device location (PDO) information provided by a device's firmware to Windows. + public string PhysicalDeviceObjectName { get; internal set; } + + + /// The storage device adapter information. Retrieving this information requires an elevated state. + public StorageAdapterInfo StorageAdapterInfo { get; internal set; } + + + /// The storage device information. + public StorageDeviceInfo StorageDeviceInfo { get; internal set; } + + + /// The storage device partitiion information. + public StoragePartitionInfo StoragePartitionInfo { get; internal set; } + + + /// An of volume strings of volumes that are located on the physical disk. + public ICollection VolumeGuids { get; internal set; } + } +} diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 4fd388ab9..d5342fc26 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -22,6 +22,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.IO; using System.Linq; using System.Security; @@ -39,7 +40,7 @@ public static partial class Local [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() { - return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess); + return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess, null); } @@ -61,41 +62,33 @@ public static IEnumerable EnumeratePhysicalDisks(DriveType[] d /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// >One or more of the values. [SecurityCritical] - internal static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, DriveType[] driveTypes = null) + private static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, DriveType[] driveTypes) { if (null == driveTypes) driveTypes = new[] {DriveType.CDRom, DriveType.Fixed, DriveType.Removable}; - var physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => NewPhysicalDiskInfo(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + var physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); - var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => NewPhysicalDiskInfo(isElevated, volumeGuid, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + + var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, volumeGuid, null)).Where(physicalDisk => null != physicalDisk).ToArray(); var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false) .Select(driveName => new DriveInfo(driveName)).Where(driveInfo => {return driveTypes.Any(driveType => driveInfo.DriveType == driveType);}) - .Select(driveInfo => NewPhysicalDiskInfo(isElevated, driveInfo.Name, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + .Select(driveInfo => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, driveInfo.Name, null)).Where(physicalDisk => null != physicalDisk).ToArray(); foreach (var pDisk in physicalDisks) yield return PopulatePhysicalDisk(pDisk, pVolumeGuids, pLogicalDrives); - - - //// Windows Disk Management shows CD-ROM so mimic that behaviour. - - //var cdRoms = EnumerateDevicesCore(null, DeviceGuid.CDRom, false).Select(deviceInfo => NewPhysicalDiskInfo(isElevated, null, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); - - //foreach (var pCdRom in cdRoms) - - // yield return PopulatePhysicalCDRom(pCdRom, pVolumeGuids, pLogicalDrives); } private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, PhysicalDiskInfo[] pVolumes, PhysicalDiskInfo[] pLogicalDrives) { - var pDiskInfo = new PhysicalDiskInfo(pDisk); + var pDiskInfo = Utils.CopyFrom(pDisk); foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber)) @@ -156,32 +149,5 @@ private static void PopulateLogicalDriveDetails(PhysicalDiskInfo pDiskInfo, stri pDiskInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(drivePath)); } - - - //private static PhysicalDiskInfo PopulatePhysicalCDRom(PhysicalDiskInfo pCdRom, PhysicalDiskInfo[] pVolumes, PhysicalDiskInfo[] pLogicalDrives) - //{ - // var pDiskInfo = new PhysicalDiskInfo(pCdRom); - - - // // Get volume from CDRom matching DeviceNumber. - - // var pVolume = pVolumes.SingleOrDefault(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber && pVol.StorageDeviceInfo.PartitionNumber == pDiskInfo.StorageDeviceInfo.PartitionNumber); - - // if (null != pVolume) - // { - // PopulateVolumeDetails(pDiskInfo, pVolume.StorageDeviceInfo.PartitionNumber, pVolume.DevicePath); - - - // // Get logical drive from CDRom matching DeviceNumber and PartitionNumber. - - // var pLogicalDrive = pLogicalDrives.SingleOrDefault(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == pVolume.StorageDeviceInfo.DeviceNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == pVolume.StorageDeviceInfo.PartitionNumber); - - // if (null != pLogicalDrive) - // PopulateLogicalDriveDetails(pDiskInfo, pLogicalDrive.DevicePath); - // } - - - // return pDiskInfo; - //} } } diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index 1faea91b9..a27897f60 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -20,10 +20,9 @@ */ using System; -using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Linq; using System.Security; -using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; @@ -35,8 +34,8 @@ public static partial class Local /// Returns a instance that represents the physical disk on the Computer or null on error/no data available. /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks, associated volumes and logical drives. - /// Instead, use method and property and/or . + /// Do not call this method for every logical drive/volume on the Computer as each call queries all physical disks, associated volumes and logical drives. + /// Instead, use method and property or . /// /// /// @@ -50,7 +49,7 @@ public static partial class Local [SecurityCritical] public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) { - return GetPhysicalDiskInfo(ProcessContext.IsElevatedProcess, devicePath); + return GetPhysicalDiskInfoCore(ProcessContext.IsElevatedProcess, -1, devicePath); } @@ -58,8 +57,8 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) /// Returns a instance that represents the physical disk on the Computer or null on error/no data available. /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks, associated volumes and logical drives. - /// Instead, use method and property and/or . + /// Do not call this method for every logical drive/volume on the Computer as each call queries all physical disks, associated volumes and logical drives. + /// Instead, use method and property or . /// /// /// @@ -74,101 +73,75 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) [SecurityCritical] public static PhysicalDiskInfo GetPhysicalDiskInfo(bool isElevated, string devicePath) { - bool isDrive; - bool isVolume; - bool isDevice; - - var validatedDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); - - if (isDrive) - validatedDevicePath = FileSystemHelper.GetLocalDevicePath(validatedDevicePath); - - - // We need the StorageDeviceInfo to locate our input path. - - var storageDeviceInfo = GetStorageDeviceInfo(isElevated, validatedDevicePath); - - // Get the PhysicalDiskInfo instance. - - var pDiskInfo = null == storageDeviceInfo ? null : isDevice - - ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => pDisk.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber && pDisk.StorageDeviceInfo.PartitionNumber == storageDeviceInfo.PartitionNumber) - - : isVolume - ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => pDisk.ContainsVolume(validatedDevicePath)) - - : isDrive - ? EnumeratePhysicalDisksCore(isElevated).SingleOrDefault(pDisk => pDisk.ContainsVolume(validatedDevicePath)) - : null; - - - if (null != pDiskInfo) - { - pDiskInfo.StorageDeviceInfo = storageDeviceInfo; - - if (null == pDiskInfo.StoragePartitionInfo) - pDiskInfo.StoragePartitionInfo = GetStoragePartitionInfo(isElevated, validatedDevicePath); - } - - - return pDiskInfo; + return GetPhysicalDiskInfoCore(isElevated, -1, devicePath); } + + /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . - /// A instance that represents the physical disk on the Computer or null on error/no data available. + /// Returns a instance that represents the physical disk on the Computer or null on error/no data available. /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every volume or logical drive on the system as each call queries all physical disks, associated volumes and logical drives. - /// Instead, use method and property and/or . + /// Do not call this method for every logical drive/volume on the Computer as each call queries all physical disks, associated volumes and logical drives. + /// Instead, use method and property or . /// /// /// /// - /// /// true indicates the current process is in an elevated state, allowing to retrieve more data. + /// Retrieve a instance by device number. /// /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// - /// A instance. - /// Use either or , not both. - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - private static PhysicalDiskInfo NewPhysicalDiskInfo(bool isElevated, string devicePath, DeviceInfo deviceInfo) + internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int deviceNumber, string devicePath) { - if (devicePath == null && deviceInfo == null) - return null; - - var isDevice = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); + var isDeviceNumber = deviceNumber > -1; + var isDrive = false; + var isVolume = false; + var isDevice = false; - if (isDevice) - devicePath = deviceInfo.DevicePath; + var validatedDevicePath = isDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + if (isDrive) + validatedDevicePath = FileSystemHelper.GetLocalDevicePath(validatedDevicePath); - var pDiskInfo = new PhysicalDiskInfo - { - StorageAdapterInfo = GetStorageAdapterInfo(isElevated, devicePath), - StorageDeviceInfo = GetStorageDeviceInfo(isElevated, devicePath), + // We need the StorageDeviceInfo to locate the device number or input path. - StoragePartitionInfo = GetStoragePartitionInfo(isElevated, devicePath), + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, validatedDevicePath); - DevicePath = devicePath, + Func matchDeviceNumber = pDisk => pDisk.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber; - DeviceDescription = isDevice ? deviceInfo.DeviceDescription : null, + var matchAll = matchDeviceNumber + (pDisk => pDisk.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber && pDisk.StorageDeviceInfo.PartitionNumber == storageDeviceInfo.PartitionNumber); + + + // Get the PhysicalDiskInfo instance. - Name = isDevice ? deviceInfo.FriendlyName : null, + var pDiskInfo = null == storageDeviceInfo ? null : isDeviceNumber || isDevice - PhysicalDeviceObjectName = isDevice ? deviceInfo.PhysicalDeviceObjectName : null, - }; + ? EnumeratePhysicalDisksCore(isElevated, null).SingleOrDefault(isDeviceNumber ? matchDeviceNumber : matchAll) + + : isVolume + ? EnumeratePhysicalDisksCore(isElevated, null).SingleOrDefault(pDisk => pDisk.ContainsVolume(validatedDevicePath)) + + : isDrive + ? EnumeratePhysicalDisksCore(isElevated, null).SingleOrDefault(pDisk => pDisk.ContainsVolume(validatedDevicePath)) + : null; - if (isDevice) - pDiskInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; + if (null != pDiskInfo) + { + pDiskInfo.StorageDeviceInfo = storageDeviceInfo; + + if (null == pDiskInfo.StoragePartitionInfo) + pDiskInfo.StoragePartitionInfo = GetStoragePartitionInfoCore(isElevated, deviceNumber, validatedDevicePath); + } return pDiskInfo; diff --git a/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs b/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs index a1fc9317f..b7c1acbe1 100644 --- a/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs +++ b/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs @@ -31,7 +31,7 @@ public static partial class Local { [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] - private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) + internal static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) { Utils.IsValidHandle(safeHandle); diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index 7c24f0a39..442f2b5d9 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -21,6 +21,7 @@ using System; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; @@ -47,7 +48,7 @@ public static partial class Local [SecurityCritical] public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { - return GetStorageDeviceInfo(ProcessContext.IsElevatedProcess, devicePath); + return GetStorageDeviceInfoCore(ProcessContext.IsElevatedProcess, devicePath); } @@ -66,6 +67,26 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) /// [SecurityCritical] public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string devicePath) + { + return GetStorageDeviceInfoCore(isElevated, devicePath); + } + + + /// Returns a instance that represent the storage device that is related to . + /// When this method is called from a non-elevated state, the property always returns 0. + /// + /// + /// + /// + /// true indicates the current process is in an elevated state, allowing to retrieve more data. + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + [SecurityCritical] + internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, string devicePath) { bool isDrive; bool isVolume; @@ -96,7 +117,7 @@ public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string dev [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] - private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle safeHandle, string localDevicePath, StorageDeviceInfo storageDeviceInfo) + private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle safeHandle, string pathForException, StorageDeviceInfo storageDeviceInfo) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { @@ -105,7 +126,7 @@ private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle saf }; - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathForException, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) { var deviceDescriptor = safeBuffer.PtrToStructure(); @@ -140,7 +161,7 @@ private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle saf if (isElevated) - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, localDevicePath)) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, pathForException)) storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index bb94def36..55416ab26 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -20,6 +20,7 @@ */ using System; +using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; @@ -46,7 +47,7 @@ public static partial class Local [SecurityCritical] public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) { - return GetStoragePartitionInfo(ProcessContext.IsElevatedProcess, devicePath); + return GetStoragePartitionInfoCore(ProcessContext.IsElevatedProcess, -1, devicePath); } @@ -66,11 +67,35 @@ public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) [SecurityCritical] public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, string devicePath) { - bool isDrive; + return GetStoragePartitionInfoCore(isElevated, -1, devicePath); + } + + + + + /// [AlphaFS] Retrieves information about the partitions on a disk and the features of each partition. + /// Returns a instance that represent the partition info that is related to . + /// + /// + /// + /// + /// true indicates the current process is in an elevated state, allowing to retrieve more data. + /// Retrieve a instance by device number. + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + [SecurityCritical] + internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, int deviceNumber, string devicePath) + { + var isDeviceNumber = deviceNumber > -1; + var isDrive = false; bool isVolume; bool isDevice; - var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + var localDevicePath = isDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); diff --git a/AlphaFS/Device/Test.cs b/AlphaFS/Device/Test.cs index e61d0df26..6ac7d049b 100644 --- a/AlphaFS/Device/Test.cs +++ b/AlphaFS/Device/Test.cs @@ -44,7 +44,7 @@ // internal static T SetFlag(this Enum flags, T value, bool state = true) // { -// if (!Enum.IsDefined(typeof(T), value)) throw new ArgumentException("Enum value and flags types don't match."); +// if (!Enum.IsDefined(typeof(T), value)) throw new ArgumentException("Enum value and flags types do not match."); // if (state) return (T) Enum.ToObject(typeof(T), Convert.ToUInt64(flags) | Convert.ToUInt64(value)); // return (T) Enum.ToObject(typeof(T), Convert.ToUInt64(flags) & ~Convert.ToUInt64(value)); // } diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs b/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs index fd2cf247c..7472eb7e4 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs @@ -32,7 +32,7 @@ public static partial class Volume /// [AlphaFS] Retrieves a volume path for the volume that is associated with the specified volume mount point (drive letter, volume path, or mounted folder). /// The unique volume name of the form: "\\?\Volume{GUID}\". /// SMB does not support volume management functions. - /// Mount points aren't supported by ReFS volumes. + /// Mount points are not supported by ReFS volumes. /// /// The path of a mounted folder (for example, "Y:\MountX\") or a drive letter (for example, "X:\"). [SuppressMessage("Microsoft.Interoperability", "CA1404:CallGetLastErrorImmediatelyAfterPInvoke", Justification = diff --git a/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs b/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs index 8824d4f08..07c9a7595 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs @@ -61,7 +61,7 @@ public static string GetVolumePathName(string path) switch ((uint) lastError) { - // Don't throw exception on these errors. + // Do not throw exception on these errors. case Win32Errors.ERROR_NO_MORE_FILES: case Win32Errors.ERROR_INVALID_PARAMETER: case Win32Errors.ERROR_INVALID_NAME: diff --git a/AlphaFS/Filesystem/File Class/File.Copy.cs b/AlphaFS/Filesystem/File Class/File.Copy.cs index a988e7dac..b27b0de6b 100644 --- a/AlphaFS/Filesystem/File Class/File.Copy.cs +++ b/AlphaFS/Filesystem/File Class/File.Copy.cs @@ -950,7 +950,7 @@ private static bool RestartCopyMoveOrThrowException(int lastError, bool isFolder // 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. + // we do not know if the problem was with the source or destination file. // Check if destination directory already exists. // Directory.Move() diff --git a/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs b/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs index f0e1404d7..aea5fe229 100644 --- a/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs +++ b/AlphaFS/Filesystem/File Class/File.CreateSymbolicLink.cs @@ -231,7 +231,7 @@ internal static void CreateSymbolicLinkCore(KernelTransaction transaction, strin } - // Don't use long path notation, as it will be empty upon creation. + // Do not use long path notation, as it will be empty upon creation. targetFileName = Path.GetRegularPathCore(targetFileName, GetFullPathOptions.None, false); diff --git a/AlphaFS/Filesystem/File Class/File.WriteText.cs b/AlphaFS/Filesystem/File Class/File.WriteText.cs index ad20411fa..bf2eaaec6 100644 --- a/AlphaFS/Filesystem/File Class/File.WriteText.cs +++ b/AlphaFS/Filesystem/File Class/File.WriteText.cs @@ -39,7 +39,7 @@ public static partial class File /// specified lines to the file, and then closes the file. /// /// - /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter + /// The method creates the file if it does not exist, but it does not create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// @@ -52,7 +52,7 @@ public static partial class File /// /// /// The operating system is older than Windows Vista. - /// The file to append the lines to. The file is created if it doesn't already exist. + /// The file to append the lines to. The file is created if it does not already exist. /// The lines to append to the file. [SecurityCritical] public static void AppendAllLines(string path, IEnumerable contents) @@ -64,7 +64,7 @@ public static void AppendAllLines(string path, IEnumerable contents) /// specified lines to the file, and then closes the file. /// /// - /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter + /// The method creates the file if it does not exist, but it does not create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// @@ -77,7 +77,7 @@ public static void AppendAllLines(string path, IEnumerable contents) /// /// /// The operating system is older than Windows Vista. - /// The file to append the lines to. The file is created if it doesn't already exist. + /// The file to append the lines to. The file is created if it does not already exist. /// The lines to append to the file. /// The character to use. [SecurityCritical] @@ -92,7 +92,7 @@ public static void AppendAllLines(string path, IEnumerable contents, Enc /// writes the specified lines to the file, and then closes the file. /// /// - /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter + /// The method creates the file if it does not exist, but it does not create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// @@ -105,7 +105,7 @@ public static void AppendAllLines(string path, IEnumerable contents, Enc /// /// /// The operating system is older than Windows Vista. - /// The file to append the lines to. The file is created if it doesn't already exist. + /// The file to append the lines to. The file is created if it does not already exist. /// The lines to append to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -119,7 +119,7 @@ public static void AppendAllLines(string path, IEnumerable contents, Pat /// the file. /// /// - /// The method creates the file if it doesn't exist, but it doesn't create new directories. + /// The method creates the file if it does not exist, but it does not create new directories. /// Therefore, the value of the path parameter must contain existing directories. /// /// @@ -133,7 +133,7 @@ public static void AppendAllLines(string path, IEnumerable contents, Pat /// /// The operating system is older than Windows Vista. /// - /// The file to append the lines to. The file is created if it doesn't already exist. + /// The file to append the lines to. The file is created if it does not already exist. /// /// The lines to append to the file. /// The character to use. @@ -152,7 +152,7 @@ public static void AppendAllLines(string path, IEnumerable contents, Enc /// writes the specified lines to the file, and then closes the file. /// /// - /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter + /// The method creates the file if it does not exist, but it does not create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// @@ -166,7 +166,7 @@ public static void AppendAllLines(string path, IEnumerable contents, Enc /// /// The operating system is older than Windows Vista. /// The transaction. - /// The file to append the lines to. The file is created if it doesn't already exist. + /// The file to append the lines to. The file is created if it does not already exist. /// The lines to append to the file. [SecurityCritical] public static void AppendAllLinesTransacted(KernelTransaction transaction, string path, IEnumerable contents) @@ -178,7 +178,7 @@ public static void AppendAllLinesTransacted(KernelTransaction transaction, strin /// writes the specified lines to the file, and then closes the file. /// /// - /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter + /// The method creates the file if it does not exist, but it does not create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// @@ -192,7 +192,7 @@ public static void AppendAllLinesTransacted(KernelTransaction transaction, strin /// /// The operating system is older than Windows Vista. /// The transaction. - /// The file to append the lines to. The file is created if it doesn't already exist. + /// The file to append the lines to. The file is created if it does not already exist. /// The lines to append to the file. /// The character to use. [SecurityCritical] @@ -207,7 +207,7 @@ public static void AppendAllLinesTransacted(KernelTransaction transaction, strin /// specified lines to the file, and then closes the file. /// /// - /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter + /// The method creates the file if it does not exist, but it does not create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// @@ -221,7 +221,7 @@ public static void AppendAllLinesTransacted(KernelTransaction transaction, strin /// /// The operating system is older than Windows Vista. /// The transaction. - /// The file to append the lines to. The file is created if it doesn't already exist. + /// The file to append the lines to. The file is created if it does not already exist. /// The lines to append to the file. /// Indicates the format of the path parameter(s). [SecurityCritical] @@ -234,7 +234,7 @@ public static void AppendAllLinesTransacted(KernelTransaction transaction, strin /// writes the specified lines to the file, and then closes the file. /// /// - /// The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter + /// The method creates the file if it does not exist, but it does not create new directories. Therefore, the value of the path parameter /// must contain existing directories. /// /// @@ -248,7 +248,7 @@ public static void AppendAllLinesTransacted(KernelTransaction transaction, strin /// /// The operating system is older than Windows Vista. /// The transaction. - /// The file to append the lines to. The file is created if it doesn't already exist. + /// The file to append the lines to. The file is created if it does not already exist. /// The lines to append to the file. /// The character to use. /// Indicates the format of the path parameter(s). diff --git a/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs b/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs index 3514cf0fb..c5669441b 100644 --- a/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs +++ b/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs @@ -317,7 +317,7 @@ private FileSystemEntryInfo NewFilesystemEntry(string pathLp, string fileName, N private T NewFileSystemEntryType(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. + // Determine yield, e.g. do not return files when only folders are requested and vice versa. if (null != FileSystemObjectType && (!(bool) FileSystemObjectType || !isFolder) && (!(bool) !FileSystemObjectType || isFolder)) return (T) (object) null; @@ -456,7 +456,7 @@ public IEnumerable Enumerate() ) { // Removes the object at the beginning of your Queue. - // The algorithmic complexity of this is O(1). It doesn't loop over elements. + // The algorithmic complexity of this is O(1). It does not loop over elements. var pathLp = dirs.Dequeue(); NativeMethods.WIN32_FIND_DATA win32FindData; diff --git a/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs b/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs index d3259f731..5ace05b25 100644 --- a/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs +++ b/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs @@ -627,7 +627,7 @@ protected override void Dispose(bool disposing) if (disposing) { // If one of the constructors previously threw an exception, - // than the object hasn't been initialized properly and call from finalize will fail. + // than the object has not been initialized properly and call from finalize will fail. if (null != SafeFileHandle && !SafeFileHandle.IsInvalid) { diff --git a/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs b/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs index 5da137b66..49a53aa45 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetFinalPathNameByHandle.cs @@ -104,7 +104,7 @@ internal static string GetFinalPathNameByHandleCore(SafeFileHandle handle, Final // 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. + // Cannot map a 0 byte file. long fileSizeHi; if (!NativeMethods.GetFileSizeEx(handle, out fileSizeHi)) if (fileSizeHi == 0) diff --git a/AlphaFS/Filesystem/Path Class/Path.Helpers.cs b/AlphaFS/Filesystem/Path Class/Path.Helpers.cs index 753e9e4e1..55e416ba3 100644 --- a/AlphaFS/Filesystem/Path Class/Path.Helpers.cs +++ b/AlphaFS/Filesystem/Path Class/Path.Helpers.cs @@ -283,7 +283,7 @@ private static string NormalizePath(string path, GetFullPathOptions options) 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", don't. + // 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. @@ -382,7 +382,7 @@ private static string NormalizePath(string path, GetFullPathOptions options) // 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 + // Do not 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. @@ -432,7 +432,7 @@ private static string NormalizePath(string path, GetFullPathOptions options) // 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. + // and do not know what order they're in. Hence the copy. if (numDots > 0 || numSpaces > 0) { var numCharsToCopy = lastSigChar >= 0 ? index - lastSigChar - 1 : index; @@ -514,8 +514,8 @@ private static string NormalizePath(string path, GetFullPathOptions options) // 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. + // But for compatibility, ensure that callers that are not doing a + // full check are not rejected here. if ((options & GetFullPathOptions.FullCheck) != 0) { var newBufferString = newBuffer.ToString(); diff --git a/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs b/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs index 9d60f32f3..8d9b05c7d 100644 --- a/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs +++ b/AlphaFS/Filesystem/Path Class/Path.IsLogicalDrive.cs @@ -61,7 +61,7 @@ internal static bool IsLogicalDriveCore(string path, bool isRegularPath, PathFor var c = regularPath.ToUpperInvariant()[0]; - // Don't use char.IsLetter() here as that can be misleading; The only valid drive letters are: A-Z. + // Do not 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'; } diff --git a/AlphaFS/Filesystem/Shell32.cs b/AlphaFS/Filesystem/Shell32.cs index 80964d2ae..19dd86a06 100644 --- a/AlphaFS/Filesystem/Shell32.cs +++ b/AlphaFS/Filesystem/Shell32.cs @@ -620,7 +620,7 @@ internal static string PathCreateFromUrl(string urlPath) var lastError = NativeMethods.PathCreateFromUrl(urlPath, buffer, ref bufferSize, 0); - // Don't throw exception, but return string.Empty; + // Do not throw exception, but return string.Empty; return lastError == Win32Errors.S_OK ? buffer.ToString() : string.Empty; } @@ -645,7 +645,7 @@ internal static string PathCreateFromUrlAlloc(string urlPath) StringBuilder buffer; var lastError = NativeMethods.PathCreateFromUrlAlloc(urlPath, out buffer, 0); - // Don't throw exception, but return string.Empty; + // Do not throw exception, but return string.Empty; return lastError == Win32Errors.S_OK ? buffer.ToString() : string.Empty; } @@ -699,7 +699,7 @@ internal static string UrlCreateFromPath(string path) var lastError = NativeMethods.UrlCreateFromPath(pathRp, buffer, ref bufferSize, 0); - // Don't throw exception, but return null; + // Do not throw exception, but return null; var url = buffer.ToString(); if (Utils.IsNullOrWhiteSpace(url)) url = string.Empty; diff --git a/AlphaFS/NativeError.cs b/AlphaFS/NativeError.cs index 592809e72..e6f04b5c6 100644 --- a/AlphaFS/NativeError.cs +++ b/AlphaFS/NativeError.cs @@ -168,7 +168,7 @@ public static void ThrowException(uint errorCode, string readPath, string writeP 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. + // We do not have a specific exception to generate for this error. throw new IOException(errorMessage, Win32Errors.GetHrFromWin32Error(errorCode)); } } diff --git a/AlphaFS/Security/InternalPrivilegeEnabler.cs b/AlphaFS/Security/InternalPrivilegeEnabler.cs index c417b725e..6f05418e2 100644 --- a/AlphaFS/Security/InternalPrivilegeEnabler.cs +++ b/AlphaFS/Security/InternalPrivilegeEnabler.cs @@ -97,7 +97,7 @@ private void AdjustPrivilege(bool enable) NativeError.ThrowException(lastError); - // If no privilege was changed, we don't want to reset it. + // If no privilege was changed, we do not want to reset it. if (mOldPrivilege.PrivilegeCount == 0) EnabledPrivilege = null; } diff --git a/AlphaFS/Utils.cs b/AlphaFS/Utils.cs index 5642633c1..fba573a81 100644 --- a/AlphaFS/Utils.cs +++ b/AlphaFS/Utils.cs @@ -36,6 +36,38 @@ namespace Alphaleonis { internal static class Utils { + internal static T CopyFrom(T source) where T : new() + { + var destination = new T(); + + CopyTo(source, destination); + + return destination; + } + + + internal static void CopyTo(T source, T destination) + { + // Properties listed here should not be overwritten by the physical disk template. + + //var excludedProps = new[] {"PartitionNumber"}; + + + //var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite && !excludedProps.Any(prop => prop.Equals(x.Name))).ToArray(); + + var srcProps = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite).ToArray(); + + var dstProps = srcProps.ToArray(); + + foreach (var srcProp in srcProps) + { + var dstProp = dstProps.First(x => x.Name.Equals(srcProp.Name)); + + dstProp.SetValue(destination, srcProp.GetValue(source, null), null); + } + } + + [SecurityCritical] internal static int GetDoubledBufferSizeOrThrowException(SafeHandle safeBuffer, int lastError, int bufferSize, string pathForException) { @@ -87,7 +119,7 @@ internal static T[] EnumToArray() { var enumType = typeof(T); - // Can't use generic type constraints on value types, so have to do check like this. + // Cannot 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"); diff --git a/AlphaFS/Win32Errors.cs b/AlphaFS/Win32Errors.cs index 129394776..98487fd7a 100644 --- a/AlphaFS/Win32Errors.cs +++ b/AlphaFS/Win32Errors.cs @@ -4116,7 +4116,7 @@ public static int GetHrFromWin32Error(uint errorCode) ///// This link is already supported by the specified server-share. //public const uint NERR_DfsDuplicateService = 2676; - ///// Can't remove the last server-share supporting this root or link. + ///// Cannot remove the last server-share supporting this root or link. //public const uint NERR_DfsCantRemoveLastServerShare = 2677; ///// The operation is not supported for an Inter-DFS link. diff --git a/CHANGELOG.md b/CHANGELOG.md index 471d4897e..288f7677a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,7 +81,7 @@ Version 2.2 (2018-03-25) - Issue #374: Initializing `DriveInfo` instance with only a letter throws `System.ArgumentException`. - Issue #375: What is the expected result of `Path.LocalToUnc()` ? (Thx damiarnold) - Issue #376: `Path.LocalToUnc(path, true)` does not return UNC path in long path form. (Thx damiarnold) -- Issue #379: `Path.LocalToUnc()` isn't handling trailing directory separators for mapped drives. (Thx damiarnold) +- Issue #379: `Path.LocalToUnc()` is not handling trailing directory separators for mapped drives. (Thx damiarnold) - Issue #381: Change property `ByHandleFileInfo.VolumeSerialNumber` from `int` to `long`. - Issue #386: `Network.Host.EnumerateDrives()` returns invalid data. - Issue #400: `Directory.CopyDeleteCore` creates destination folder when source folder does not exist. @@ -118,7 +118,7 @@ Version 2.2 (2018-03-25) - Issue #275: Improve methods `Directory/File.CopyMoveCore`: Eliminate recursion. - Issue #277: `Directory.DeleteDirectoryCore()`: Eliminate recursion. - Issue #278: `Directory.DeleteEmptySubdirectoriesCore()`: Eliminate recursion. -- Issue #303: `Path.Constants.cs`: Don't use `CurrentCulture` (Thx HugoRoss) +- Issue #303: `Path.Constants.cs`: Do not use `CurrentCulture` (Thx HugoRoss) - Issue #306: Include `ShareInfoLevel.Info502` and set as a fallback in `GetShareInfoCore()` (Thx damiarnold) - Issue #326: Add parameter `bool preserveDates` and created overloaded `Directory.Copy` methods to support this. - Issue #331: Rename method `File/Directory.TransferTimestamps` to `CopyTimestamps`. @@ -160,7 +160,7 @@ Version 2.1.3 (2017-06-05) ### Bugs Fixed - Issue #288: `Directory.Exists` on root drive problem has come back with recent updates (Thx warrenlbrown) -- Issue #289: `Alphaleonis.Win32.Network.Host.GetShareInfo` doesn't work since 2.1.0 (Thx Schoolmonkey/damiarnold) +- Issue #289: `Alphaleonis.Win32.Network.Host.GetShareInfo` does not work since 2.1.0 (Thx Schoolmonkey/damiarnold) - Issue #296: Folder rename (casing) throws IOException with HResult `ERROR_SAME_DRIVE` (Thx doormalena) - Issue #297: Incorrect domain returned from `Host.EnumerateDomainDfsRoot` when specifying domain (Thx damiarnold) - Issue #299: `FileInfo.MoveTo` and `DirectoryInfo.MoveTo` throw `ArgumentNullException` on empty destination path (Thx doormalena) @@ -196,8 +196,8 @@ Version 2.1 (2016-09-29) - Issue #112: Add `CreationTimeUtc`, `LastAccessTimeUtc` and `LastWriteTimeUtc` to "Info" classes. - Issue #119: Fix `Path.IsLocalPath()` issues. - Issue #125: AlphaFS is now CLSCompliant. -- Issue #127: Modify method `Volume.QueryDosDevice()` so that is doesn't rely on `Path.IsLocalPath()` anymore. -- Issue #130: Modify method `Path.LocalToUnc()` so that is doesn't rely on `Path.IsLocalPath()` anymore. +- Issue #127: Modify method `Volume.QueryDosDevice()` so that is does not rely on `Path.IsLocalPath()` anymore. +- Issue #130: Modify method `Path.LocalToUnc()` so that is does not rely on `Path.IsLocalPath()` anymore. - Issue #131: Modify method `Path.GetPathRoot()` to handle UNC paths in long path format. - Issue #132: Modify method `VolumeInfo()` constructor to better handle input paths. - Issue #133: Add missing unit test `Host.GetHostShareFromPath()`. @@ -246,7 +246,7 @@ Version 2.1 (2016-09-29) - Issue #176: At `DirectoryInfo.GetFileSystemInfos()`, Long path prefix of GLOBALROOT path is missing. (Thx diontools) - Issue #179: `Path.GetFileName()` with an empty string throws an exception. (Thx brutaldev) - Issue #180: Network connects methods hangs in Windows service when credentials fail. (Thx brutaldev) -- Issue #181: `File.OpenWrite()` should create file if it doesn't exist. (Thomas Levesque) +- Issue #181: `File.OpenWrite()` should create file if it does not exist. (Thomas Levesque) - Issue #183: Add `SafeFileHandle` null check for BackupFileStream.Dispose. (Thx diontools) - Issue #185: Correct pinvoke signatures of `CreateSymbolicLink()` and `CreateSymbolicLinkTransacted()` functions. - Issue #196: Replace usage of `ExtendedFileAttributes.None` with `ExtendedFileAttributes.Normal`. @@ -265,7 +265,7 @@ Version 2.1 (2016-09-29) - Issue #242: `File.Open(file, System.IO.FileMode.Append)` does not append. - Issue #244: `File.Copy(src, dst, true)` does not respect `FILE_ATTRIBUTE_READONLY`. - Issue #246: Using `Directory.EnumerateFileSystemEntries()` recursively with a relative path may fail. -- Issue #248: `Directory.Move()` throws `FileNotFoundException` instead of `DirectoryNotFoundException` when source folder doesn't exist. +- Issue #248: `Directory.Move()` throws `FileNotFoundException` instead of `DirectoryNotFoundException` when source folder does not exist. - Issue #249: Change `File.GetHashCore()` `.ToString("X2")` to `.ToString("X2", CultureInfo.InvariantCulture)`. - Issue #252: Correct `FileSystemEntryInfos.FullPath` property when input path is a dot (current directory). - Issue #253: Apply `Dispose()` to method `File.GetHashCore()`. From c74705dac199fd621f4963d2afd80da41434dd64 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 12 Jun 2018 05:06:26 +0200 Subject: [PATCH 101/133] Code improvement. --- ...pterInfo_UsingDevicePathFromSystemDrive.cs | 8 -- .../FilesystemHelper.OpenPhysicalDrive.cs | 4 +- .../PhysicalDisk/Device.PhysicalDiskInfo.cs | 2 - .../Local.EnumeratePhysicalDisks.cs | 95 +++++++++++++------ .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 81 +++++++++++----- .../Storage/Local.GetStorageAdapterInfo.cs | 8 +- .../Storage/Local.GetStoragePartitionInfo.cs | 2 +- 7 files changed, 132 insertions(+), 68 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs index 9fcc80b5f..7d332bdd6 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs @@ -56,18 +56,10 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingDevicePathFromSystemDrive_ if (Alphaleonis.Win32.Security.ProcessContext.IsElevatedProcess) - { Assert.AreEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); - Assert.AreNotEqual(Alphaleonis.Win32.Device.StorageBusType.Unknown, storageAdapterInfo.BusType); - } - else - { Assert.AreNotEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); - - Assert.AreEqual(pDisk.StorageAdapterInfo.BusType, storageAdapterInfo.BusType); - } } } } diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs index 6ff790ae2..dc400cabe 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs @@ -31,7 +31,7 @@ namespace Alphaleonis.Win32.Device { internal static partial class FileSystemHelper { - /// Opens a physical disk or volume/logical drive for read access. + /// Opens a physical disk or logical drive/volume for read access. /// Returns a instance. /// /// @@ -43,7 +43,7 @@ internal static partial class FileSystemHelper /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// - /// If no elevated access is needed to access the physical disk or volume/logical drive, specify 0 for this parameter. + /// If no elevated access is needed to access the physical disk or logical drive/volume, specify 0 for this parameter. [SecurityCritical] public static SafeFileHandle OpenPhysicalDisk(string devicePath, FileSystemRights fileSystemRights) { diff --git a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs index 31ab51ecc..73387f5fa 100644 --- a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs @@ -85,8 +85,6 @@ internal static PhysicalDiskInfo InitializePhysicalDiskInfo(bool isElevated, str if (isDevice) devicePath = deviceInfo.DevicePath; - - var storageDeviceInfo = Local.GetStorageDeviceInfoCore(isElevated, devicePath); if (null == storageDeviceInfo) diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index d5342fc26..8d9865bf2 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -40,53 +40,92 @@ public static partial class Local [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() { - return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess, null); + return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess, -1); } - + /// [AlphaFS] Enumerates the physical disks of type on the Computer, populated with volume- and logical drive information. /// Returns an collection that represents the physical disks on the Computer. - /// >One or more of the values. + /// true indicates the current process is in an elevated state, allowing to retrieve more data. + /// Retrieve a instance by device number. [SecurityCritical] - public static IEnumerable EnumeratePhysicalDisks(DriveType[] driveTypes) + private static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, int deviceNumber) { - if (null == driveTypes) - throw new ArgumentNullException("driveTypes"); - - return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess, driveTypes); - } + var isDeviceNumber = deviceNumber > -1; + var physicalDisks = new PhysicalDiskInfo[1]; + var volumeGuids = new Collection(); + var logicalDrives = new Collection(); - /// [AlphaFS] Enumerates the physical disks of type on the Computer, populated with volume- and logical drive information. - /// Returns an collection that represents the physical disks on the Computer. - /// true indicates the current process is in an elevated state, allowing to retrieve more data. - /// >One or more of the values. - [SecurityCritical] - private static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, DriveType[] driveTypes) - { - if (null == driveTypes) - driveTypes = new[] {DriveType.CDRom, DriveType.Fixed, DriveType.Removable}; + var driveTypes = new[] {DriveType.CDRom, DriveType.Fixed, DriveType.Removable}; + + + if (isDeviceNumber) + { + // Devices / Physical disk. + foreach (var deviceInfo in EnumerateDevicesCore(null, DeviceGuid.Disk, false)) + { + var storageDeviceInfo = GetStorageDeviceInfoCore(false, deviceInfo.DevicePath); + + if (null == storageDeviceInfo || storageDeviceInfo.DeviceNumber != deviceNumber) + continue; + + + physicalDisks[0] = PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, deviceInfo); - var physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + // Volumes. + foreach (var volumeGuid in Volume.EnumerateVolumes()) + { + storageDeviceInfo = GetStorageDeviceInfoCore(false, volumeGuid); + if (null == storageDeviceInfo || storageDeviceInfo.DeviceNumber != deviceNumber) + continue; - var pVolumeGuids = Volume.EnumerateVolumes().Select(volumeGuid => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, volumeGuid, null)).Where(physicalDisk => null != physicalDisk).ToArray(); - - var pLogicalDrives = DriveInfo.EnumerateLogicalDrivesCore(false, false) - - .Select(driveName => new DriveInfo(driveName)).Where(driveInfo => {return driveTypes.Any(driveType => driveInfo.DriveType == driveType);}) - - .Select(driveInfo => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, driveInfo.Name, null)).Where(physicalDisk => null != physicalDisk).ToArray(); + + volumeGuids.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, volumeGuid, null)); + } + + + // Logical drives. + foreach (var driveInfo in DriveInfo.GetDrives()) + { + if (!driveTypes.Contains(driveInfo.DriveType)) + continue; + + storageDeviceInfo = GetStorageDeviceInfoCore(false, driveInfo.Name); + + if (null == storageDeviceInfo || storageDeviceInfo.DeviceNumber != deviceNumber) + continue; + + + logicalDrives.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, driveInfo.Name, null)); + } + } + } + + else + { + physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + + foreach (var volumeGuid in Volume.EnumerateVolumes().Select(volumeGuid => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, volumeGuid, null)).Where(physicalDisk => null != physicalDisk)) + volumeGuids.Add(volumeGuid); + + foreach (var driveName in DriveInfo.EnumerateLogicalDrivesCore(false, false) + .Select(driveName => new DriveInfo(driveName)).Where(driveInfo => {return driveTypes.Any(driveType => driveInfo.DriveType == driveType);}) + .Select(driveInfo => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, driveInfo.Name, null)).Where(physicalDisk => null != physicalDisk)) + + logicalDrives.Add(driveName); + } foreach (var pDisk in physicalDisks) - yield return PopulatePhysicalDisk(pDisk, pVolumeGuids, pLogicalDrives); + yield return PopulatePhysicalDisk(pDisk, volumeGuids, logicalDrives); } - private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, PhysicalDiskInfo[] pVolumes, PhysicalDiskInfo[] pLogicalDrives) + private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, IEnumerable pVolumes, IEnumerable pLogicalDrives) { var pDiskInfo = Utils.CopyFrom(pDisk); diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index a27897f60..22239b683 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -101,50 +101,85 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(bool isElevated, string devic internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int deviceNumber, string devicePath) { var isDeviceNumber = deviceNumber > -1; + bool isDevice; var isDrive = false; var isVolume = false; - var isDevice = false; - - var validatedDevicePath = isDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + + var localDevicePath = isDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); if (isDrive) - validatedDevicePath = FileSystemHelper.GetLocalDevicePath(validatedDevicePath); + localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); + + // StorageDeviceInfo contains the device number. - // We need the StorageDeviceInfo to locate the device number or input path. + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, localDevicePath); - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, validatedDevicePath); + if (null == storageDeviceInfo) + return null; - Func matchDeviceNumber = pDisk => pDisk.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber; + if (!isDeviceNumber) + deviceNumber = storageDeviceInfo.DeviceNumber; - var matchAll = matchDeviceNumber + (pDisk => pDisk.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber && pDisk.StorageDeviceInfo.PartitionNumber == storageDeviceInfo.PartitionNumber); - - - // Get the PhysicalDiskInfo instance. - var pDiskInfo = null == storageDeviceInfo ? null : isDeviceNumber || isDevice + Func matchVolume = pDiskInfo => pDiskInfo.ContainsVolume(localDevicePath); + + Func matchDeviceNumber = pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber; + + Func matchDeviceAndPartitionNumber = pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber && pDiskInfo.StorageDeviceInfo.PartitionNumber == storageDeviceInfo.PartitionNumber; + + PhysicalDiskInfo physicalDiskInfo = null; + + + //var physicalDiskInfo = EnumeratePhysicalDisksCore(isElevated, deviceNumber) + + // .SingleOrDefault(isDrive || isVolume ? matchVolume : isDeviceNumber ? matchDeviceNumber : matchDeviceAndPartitionNumber); - ? EnumeratePhysicalDisksCore(isElevated, null).SingleOrDefault(isDeviceNumber ? matchDeviceNumber : matchAll) - : isVolume - ? EnumeratePhysicalDisksCore(isElevated, null).SingleOrDefault(pDisk => pDisk.ContainsVolume(validatedDevicePath)) + var deze = EnumeratePhysicalDisksCore(isElevated, deviceNumber); - : isDrive - ? EnumeratePhysicalDisksCore(isElevated, null).SingleOrDefault(pDisk => pDisk.ContainsVolume(validatedDevicePath)) - : null; + + foreach (var pDiskInfo in EnumeratePhysicalDisksCore(isElevated, deviceNumber)) + { + if (isDrive || isVolume) + { + if (!pDiskInfo.ContainsVolume(localDevicePath)) + continue; + + physicalDiskInfo = pDiskInfo; + break; + } + + + if (isDeviceNumber) + { + if (pDiskInfo.StorageDeviceInfo.DeviceNumber != storageDeviceInfo.DeviceNumber) + continue; + + physicalDiskInfo = pDiskInfo; + break; + } + + + if (pDiskInfo.StorageDeviceInfo.DeviceNumber != storageDeviceInfo.DeviceNumber && pDiskInfo.StorageDeviceInfo.PartitionNumber != storageDeviceInfo.PartitionNumber) + continue; + + physicalDiskInfo = pDiskInfo; + break; + } - if (null != pDiskInfo) + if (null != physicalDiskInfo) { - pDiskInfo.StorageDeviceInfo = storageDeviceInfo; + physicalDiskInfo.StorageDeviceInfo = storageDeviceInfo; - if (null == pDiskInfo.StoragePartitionInfo) - pDiskInfo.StoragePartitionInfo = GetStoragePartitionInfoCore(isElevated, deviceNumber, validatedDevicePath); + if (null == physicalDiskInfo.StoragePartitionInfo) + physicalDiskInfo.StoragePartitionInfo = GetStoragePartitionInfoCore(isElevated, -1, localDevicePath); } - return pDiskInfo; + return physicalDiskInfo; } } } diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index 072008e3e..571985c5c 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -70,10 +70,10 @@ public static StorageAdapterInfo GetStorageAdapterInfo(bool isElevated, string d bool isVolume; bool isDevice; - var validatedDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); if (isDrive) - validatedDevicePath = FileSystemHelper.GetLocalDevicePath(validatedDevicePath); + localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY @@ -83,9 +83,9 @@ public static StorageAdapterInfo GetStorageAdapterInfo(bool isElevated, string d }; - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(validatedDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, validatedDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) { return null == safeBuffer ? null : new StorageAdapterInfo(safeBuffer.PtrToStructure()); } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 55416ab26..6e1cede35 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -91,9 +91,9 @@ public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, stri internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, int deviceNumber, string devicePath) { var isDeviceNumber = deviceNumber > -1; + bool isDevice; var isDrive = false; bool isVolume; - bool isDevice; var localDevicePath = isDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); From e3330dba2f7dd5e6c232375d28dff454b5f12cc4 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 12 Jun 2018 15:52:10 +0200 Subject: [PATCH 102/133] Code improvement, moved some files. --- ...DiskInfo_UsingDevicePathFromSystemDrive.cs | 7 +- ...tPhysicalDiskInfo_UsingLogicalDrivePath.cs | 5 +- ...InitializeInstanceUsingLogicalDrivePath.cs | 1 - AlphaFS/AlphaFS.csproj | 26 +++--- .../NativeMethods.DeviceManagement.cs | 70 ++++++++-------- .../PhysicalDisk/Device.PhysicalDiskInfo.cs | 6 +- .../Local.EnumeratePhysicalDisks.cs | 84 ++++++++----------- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 22 +---- .../Storage/Local.GetStorageAdapterInfo.cs | 2 - .../Storage/Local.GetStorageDeviceInfo.cs | 11 ++- .../DetectionType.cs | 0 .../DeviceGuid.cs | 0 .../DiskPartitionType.cs | 0 .../DosDeviceAttributes.cs | 0 .../EfiPartitionAttributes.cs | 0 .../PartitionStyle.cs | 0 .../PartitionType..cs | 0 .../StorageBusType.cs | 0 .../StorageDeviceType.cs | 0 .../StorageMediaType.cs | 0 .../Filesystem/Path Class/Path.Constants.cs | 1 - .../SafeCmConnectMachineHandle.cs | 0 .../SafeSetupDiClassDevsExHandle.cs | 0 23 files changed, 101 insertions(+), 134 deletions(-) rename AlphaFS/Device/{Native Other => Structures, Enumerations}/DetectionType.cs (100%) rename AlphaFS/Device/{Native Other => Structures, Enumerations}/DeviceGuid.cs (100%) rename AlphaFS/Device/{Native Other => Structures, Enumerations}/DiskPartitionType.cs (100%) rename AlphaFS/Device/{Native Other => Structures, Enumerations}/DosDeviceAttributes.cs (100%) rename AlphaFS/Device/{Native Other => Structures, Enumerations}/EfiPartitionAttributes.cs (100%) rename AlphaFS/Device/{Native Other => Structures, Enumerations}/PartitionStyle.cs (100%) rename AlphaFS/Device/{Native Other => Structures, Enumerations}/PartitionType..cs (100%) rename AlphaFS/Device/{Native Other => Structures, Enumerations}/StorageBusType.cs (100%) rename AlphaFS/Device/{Native Other => Structures, Enumerations}/StorageDeviceType.cs (100%) rename AlphaFS/Device/{Native Other => Structures, Enumerations}/StorageMediaType.cs (100%) rename AlphaFS/{Device/Native Other => Safe Handles}/SafeCmConnectMachineHandle.cs (100%) rename AlphaFS/{Device/Native Other => Safe Handles}/SafeSetupDiClassDevsExHandle.cs (100%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs index 490756d35..753080629 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs @@ -41,11 +41,10 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive_Su var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); - - - Console.WriteLine("#{0:000}\tInput Device Path: [{1}]\t\t{2}\t\t{3}", ++deviceCount, devicePath, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); + UnitTestConstants.Dump(pDisk); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs index 990ade173..866c8a7f4 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs @@ -56,10 +56,11 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePath_Success() } - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(driveInfo.Name); + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, pDisk.StorageAdapterInfo.ToString()); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(driveInfo.Name); + UnitTestConstants.Dump(pDisk); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs index 68475175d..3a65f6c8e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs @@ -20,7 +20,6 @@ */ using System; -using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 05a7fb9df..b762f1cf2 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -524,14 +524,14 @@ - - + + - - - + + + @@ -540,14 +540,14 @@ - - + + - - - + + + @@ -557,9 +557,9 @@ - + - + @@ -743,7 +743,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs b/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs index 7ed7fb348..55ea3d09c 100644 --- a/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs @@ -244,41 +244,41 @@ internal static partial class NativeMethods - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] - [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetupDiGetDevicePropertyW"), SuppressUnmanagedCodeSecurity] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SetupDiGetDeviceProperty3(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, ref DEVPROPKEY propkey, [MarshalAs(UnmanagedType.U8)] ref ulong propertyDataType, Guid propertyBuffer, int propertyBufferSize, ref int requiredSize, uint flags); - - - /// The SetupDiGetDeviceProperty function retrieves a device instance property. - /// - /// Available in Windows Vista and later versions of Windows. - /// - /// - /// - /// SetupDiGetDeviceProperty returns TRUE if it is successful. - /// Otherwise, it returns FALSE, and the logged error can be retrieved by calling GetLastError. - /// - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] - [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetupDiGetDevicePropertyW"), SuppressUnmanagedCodeSecurity] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SetupDiGetDeviceProperty2(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, ref DEVPROPKEY propkey, [MarshalAs(UnmanagedType.U8)] ref ulong propertyDataType, SafeGlobalMemoryBufferHandle propertyBuffer, int propertyBufferSize, ref int requiredSize, [MarshalAs(UnmanagedType.U4)] uint flags); - - - /// The SetupDiGetDeviceRegistryProperty function retrieves a specified Plug and Play device property. - /// - /// Available in Microsoft Windows 2000 and later versions of Windows. - /// - /// - /// - /// SetupDiGetDeviceRegistryProperty returns TRUE if the call was successful. - /// Otherwise, it returns FALSE and the logged error can be retrieved by making a call to GetLastError. - /// SetupDiGetDeviceRegistryProperty returns the ERROR_INVALID_DATA error code if the requested property does not exist for a device or if the property data is not valid. - /// - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] - [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SetupDiGetDeviceRegistryProperty(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, SPDRP property, ref int propertyRegDataType, byte[] propertyBuffer, [MarshalAs(UnmanagedType.U4)] uint propertyBufferSize, ref int requiredSize); + //[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + //[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetupDiGetDevicePropertyW"), SuppressUnmanagedCodeSecurity] + //[return: MarshalAs(UnmanagedType.Bool)] + //internal static extern bool SetupDiGetDeviceProperty3(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, ref DEVPROPKEY propkey, [MarshalAs(UnmanagedType.U8)] ref ulong propertyDataType, Guid propertyBuffer, int propertyBufferSize, ref int requiredSize, uint flags); + + + ///// The SetupDiGetDeviceProperty function retrieves a device instance property. + ///// + ///// Available in Windows Vista and later versions of Windows. + ///// + ///// + ///// + ///// SetupDiGetDeviceProperty returns TRUE if it is successful. + ///// Otherwise, it returns FALSE, and the logged error can be retrieved by calling GetLastError. + ///// + //[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + //[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetupDiGetDevicePropertyW"), SuppressUnmanagedCodeSecurity] + //[return: MarshalAs(UnmanagedType.Bool)] + //internal static extern bool SetupDiGetDeviceProperty2(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, ref DEVPROPKEY propkey, [MarshalAs(UnmanagedType.U8)] ref ulong propertyDataType, SafeGlobalMemoryBufferHandle propertyBuffer, int propertyBufferSize, ref int requiredSize, [MarshalAs(UnmanagedType.U4)] uint flags); + + + ///// The SetupDiGetDeviceRegistryProperty function retrieves a specified Plug and Play device property. + ///// + ///// Available in Microsoft Windows 2000 and later versions of Windows. + ///// + ///// + ///// + ///// SetupDiGetDeviceRegistryProperty returns TRUE if the call was successful. + ///// Otherwise, it returns FALSE and the logged error can be retrieved by making a call to GetLastError. + ///// SetupDiGetDeviceRegistryProperty returns the ERROR_INVALID_DATA error code if the requested property does not exist for a device or if the property data is not valid. + ///// + //[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + //[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] + //[return: MarshalAs(UnmanagedType.Bool)] + //internal static extern bool SetupDiGetDeviceRegistryProperty(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, SPDRP property, ref int propertyRegDataType, byte[] propertyBuffer, [MarshalAs(UnmanagedType.U4)] uint propertyBufferSize, ref int requiredSize); /// The SetupDiGetDeviceRegistryProperty function retrieves a specified Plug and Play device property. diff --git a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs index 73387f5fa..b66af9963 100644 --- a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs @@ -21,7 +21,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Globalization; using System.Security; using Alphaleonis.Win32.Filesystem; @@ -47,7 +46,10 @@ public PhysicalDiskInfo(int deviceNumber) if (deviceNumber < 0) throw new ArgumentOutOfRangeException("deviceNumber"); - Utils.CopyTo(Local.GetPhysicalDiskInfoCore(Security.ProcessContext.IsElevatedProcess, deviceNumber, null), this); + var pDiskInfo = Local.GetPhysicalDiskInfoCore(Security.ProcessContext.IsElevatedProcess, deviceNumber, null); + + if (null != pDiskInfo) + Utils.CopyTo(pDiskInfo, this); } #endregion // Constructors diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 8d9865bf2..4462d16ad 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -19,10 +19,8 @@ * THE SOFTWARE. */ -using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Globalization; using System.IO; using System.Linq; using System.Security; @@ -35,87 +33,75 @@ namespace Alphaleonis.Win32.Device { public static partial class Local { - /// [AlphaFS] Enumerates the physical disks on the Computer, populated with volume- and logical drive information. + /// [AlphaFS] Enumerates the physical disks on the Computer, populated with volume-/logical drive information. /// Returns an collection that represents the physical disks on the Computer. [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() { - return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess, -1); + return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess); } - /// [AlphaFS] Enumerates the physical disks of type on the Computer, populated with volume- and logical drive information. + /// [AlphaFS] Enumerates the physical disks on the Computer, populated with volume-/logical drive information. /// Returns an collection that represents the physical disks on the Computer. /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// Retrieve a instance by device number. [SecurityCritical] - private static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, int deviceNumber) + private static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, int deviceNumber = -1) { var isDeviceNumber = deviceNumber > -1; - + var driveTypes = new[] {DriveType.CDRom, DriveType.Fixed, DriveType.Removable}; var physicalDisks = new PhysicalDiskInfo[1]; var volumeGuids = new Collection(); var logicalDrives = new Collection(); + + + // Devices / Physical disk. - var driveTypes = new[] {DriveType.CDRom, DriveType.Fixed, DriveType.Removable}; - - - if (isDeviceNumber) + foreach (var deviceInfo in EnumerateDevicesCore(null, DeviceGuid.Disk, false)) { - // Devices / Physical disk. - foreach (var deviceInfo in EnumerateDevicesCore(null, DeviceGuid.Disk, false)) - { - var storageDeviceInfo = GetStorageDeviceInfoCore(false, deviceInfo.DevicePath); - - if (null == storageDeviceInfo || storageDeviceInfo.DeviceNumber != deviceNumber) - continue; + var storageDeviceInfo = GetStorageDeviceInfoCore(false, deviceInfo.DevicePath); + if (null == storageDeviceInfo || isDeviceNumber && storageDeviceInfo.DeviceNumber != deviceNumber) + continue; + + physicalDisks[0] = PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, deviceInfo); - physicalDisks[0] = PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, deviceInfo); - - - // Volumes. - foreach (var volumeGuid in Volume.EnumerateVolumes()) - { - storageDeviceInfo = GetStorageDeviceInfoCore(false, volumeGuid); + // There can only be one. + break; + } - if (null == storageDeviceInfo || storageDeviceInfo.DeviceNumber != deviceNumber) - continue; + if (null == physicalDisks[0]) + yield break; - volumeGuids.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, volumeGuid, null)); - } + // Volumes. - // Logical drives. - foreach (var driveInfo in DriveInfo.GetDrives()) - { - if (!driveTypes.Contains(driveInfo.DriveType)) - continue; + foreach (var volumeGuid in Volume.EnumerateVolumes()) + { + var storageDeviceInfo = GetStorageDeviceInfoCore(false, volumeGuid); - storageDeviceInfo = GetStorageDeviceInfoCore(false, driveInfo.Name); + if (null == storageDeviceInfo || isDeviceNumber && storageDeviceInfo.DeviceNumber != deviceNumber) + continue; - if (null == storageDeviceInfo || storageDeviceInfo.DeviceNumber != deviceNumber) - continue; + volumeGuids.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, volumeGuid, null)); + } - logicalDrives.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, driveInfo.Name, null)); - } - } - } + // Logical drives. - else + foreach (var driveInfo in DriveInfo.GetDrives()) { - physicalDisks = EnumerateDevicesCore(null, DeviceGuid.Disk, false).Select(deviceInfo => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, deviceInfo)).Where(physicalDisk => null != physicalDisk).ToArray(); + if (!driveTypes.Contains(driveInfo.DriveType)) + continue; - foreach (var volumeGuid in Volume.EnumerateVolumes().Select(volumeGuid => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, volumeGuid, null)).Where(physicalDisk => null != physicalDisk)) - volumeGuids.Add(volumeGuid); + var storageDeviceInfo = GetStorageDeviceInfoCore(false, driveInfo.Name); - foreach (var driveName in DriveInfo.EnumerateLogicalDrivesCore(false, false) - .Select(driveName => new DriveInfo(driveName)).Where(driveInfo => {return driveTypes.Any(driveType => driveInfo.DriveType == driveType);}) - .Select(driveInfo => PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, driveInfo.Name, null)).Where(physicalDisk => null != physicalDisk)) + if (null == storageDeviceInfo || storageDeviceInfo.DeviceNumber != deviceNumber) + continue; - logicalDrives.Add(driveName); + logicalDrives.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, driveInfo.Name, null)); } diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index 22239b683..f0c3c368a 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -21,7 +21,6 @@ using System; using System.Globalization; -using System.Linq; using System.Security; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; @@ -110,7 +109,7 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - + // StorageDeviceInfo contains the device number. var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, localDevicePath); @@ -118,28 +117,12 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de if (null == storageDeviceInfo) return null; - if (!isDeviceNumber) deviceNumber = storageDeviceInfo.DeviceNumber; - - Func matchVolume = pDiskInfo => pDiskInfo.ContainsVolume(localDevicePath); - - Func matchDeviceNumber = pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber; - - Func matchDeviceAndPartitionNumber = pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber == storageDeviceInfo.DeviceNumber && pDiskInfo.StorageDeviceInfo.PartitionNumber == storageDeviceInfo.PartitionNumber; - PhysicalDiskInfo physicalDiskInfo = null; - //var physicalDiskInfo = EnumeratePhysicalDisksCore(isElevated, deviceNumber) - - // .SingleOrDefault(isDrive || isVolume ? matchVolume : isDeviceNumber ? matchDeviceNumber : matchDeviceAndPartitionNumber); - - - var deze = EnumeratePhysicalDisksCore(isElevated, deviceNumber); - - foreach (var pDiskInfo in EnumeratePhysicalDisksCore(isElevated, deviceNumber)) { if (isDrive || isVolume) @@ -172,7 +155,8 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de if (null != physicalDiskInfo) { - physicalDiskInfo.StorageDeviceInfo = storageDeviceInfo; + if (!isDeviceNumber) + physicalDiskInfo.StorageDeviceInfo = storageDeviceInfo; if (null == physicalDiskInfo.StoragePartitionInfo) physicalDiskInfo.StoragePartitionInfo = GetStoragePartitionInfoCore(isElevated, -1, localDevicePath); diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index 571985c5c..5e3a8fb3b 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -20,12 +20,10 @@ */ using System; -using System.Diagnostics.CodeAnalysis; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; -using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index 442f2b5d9..daacee2a5 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -21,7 +21,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Globalization; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; @@ -100,17 +99,17 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri StorageDeviceInfo storageDeviceInfo; - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - { - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath)) - storageDeviceInfo = null != safeBuffer ? new StorageDeviceInfo(safeBuffer.PtrToStructure()) : null; + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath)) + { + storageDeviceInfo = null != safeBuffer ? new StorageDeviceInfo(safeBuffer.PtrToStructure()) : null; if (null != storageDeviceInfo) SetStorageDeviceInfoData(isElevated, safeHandle, localDevicePath, storageDeviceInfo); } - + return storageDeviceInfo; } diff --git a/AlphaFS/Device/Native Other/DetectionType.cs b/AlphaFS/Device/Structures, Enumerations/DetectionType.cs similarity index 100% rename from AlphaFS/Device/Native Other/DetectionType.cs rename to AlphaFS/Device/Structures, Enumerations/DetectionType.cs diff --git a/AlphaFS/Device/Native Other/DeviceGuid.cs b/AlphaFS/Device/Structures, Enumerations/DeviceGuid.cs similarity index 100% rename from AlphaFS/Device/Native Other/DeviceGuid.cs rename to AlphaFS/Device/Structures, Enumerations/DeviceGuid.cs diff --git a/AlphaFS/Device/Native Other/DiskPartitionType.cs b/AlphaFS/Device/Structures, Enumerations/DiskPartitionType.cs similarity index 100% rename from AlphaFS/Device/Native Other/DiskPartitionType.cs rename to AlphaFS/Device/Structures, Enumerations/DiskPartitionType.cs diff --git a/AlphaFS/Device/Native Other/DosDeviceAttributes.cs b/AlphaFS/Device/Structures, Enumerations/DosDeviceAttributes.cs similarity index 100% rename from AlphaFS/Device/Native Other/DosDeviceAttributes.cs rename to AlphaFS/Device/Structures, Enumerations/DosDeviceAttributes.cs diff --git a/AlphaFS/Device/Native Other/EfiPartitionAttributes.cs b/AlphaFS/Device/Structures, Enumerations/EfiPartitionAttributes.cs similarity index 100% rename from AlphaFS/Device/Native Other/EfiPartitionAttributes.cs rename to AlphaFS/Device/Structures, Enumerations/EfiPartitionAttributes.cs diff --git a/AlphaFS/Device/Native Other/PartitionStyle.cs b/AlphaFS/Device/Structures, Enumerations/PartitionStyle.cs similarity index 100% rename from AlphaFS/Device/Native Other/PartitionStyle.cs rename to AlphaFS/Device/Structures, Enumerations/PartitionStyle.cs diff --git a/AlphaFS/Device/Native Other/PartitionType..cs b/AlphaFS/Device/Structures, Enumerations/PartitionType..cs similarity index 100% rename from AlphaFS/Device/Native Other/PartitionType..cs rename to AlphaFS/Device/Structures, Enumerations/PartitionType..cs diff --git a/AlphaFS/Device/Native Other/StorageBusType.cs b/AlphaFS/Device/Structures, Enumerations/StorageBusType.cs similarity index 100% rename from AlphaFS/Device/Native Other/StorageBusType.cs rename to AlphaFS/Device/Structures, Enumerations/StorageBusType.cs diff --git a/AlphaFS/Device/Native Other/StorageDeviceType.cs b/AlphaFS/Device/Structures, Enumerations/StorageDeviceType.cs similarity index 100% rename from AlphaFS/Device/Native Other/StorageDeviceType.cs rename to AlphaFS/Device/Structures, Enumerations/StorageDeviceType.cs diff --git a/AlphaFS/Device/Native Other/StorageMediaType.cs b/AlphaFS/Device/Structures, Enumerations/StorageMediaType.cs similarity index 100% rename from AlphaFS/Device/Native Other/StorageMediaType.cs rename to AlphaFS/Device/Structures, Enumerations/StorageMediaType.cs diff --git a/AlphaFS/Filesystem/Path Class/Path.Constants.cs b/AlphaFS/Filesystem/Path Class/Path.Constants.cs index 60101c744..a364297ee 100644 --- a/AlphaFS/Filesystem/Path Class/Path.Constants.cs +++ b/AlphaFS/Filesystem/Path Class/Path.Constants.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; diff --git a/AlphaFS/Device/Native Other/SafeCmConnectMachineHandle.cs b/AlphaFS/Safe Handles/SafeCmConnectMachineHandle.cs similarity index 100% rename from AlphaFS/Device/Native Other/SafeCmConnectMachineHandle.cs rename to AlphaFS/Safe Handles/SafeCmConnectMachineHandle.cs diff --git a/AlphaFS/Device/Native Other/SafeSetupDiClassDevsExHandle.cs b/AlphaFS/Safe Handles/SafeSetupDiClassDevsExHandle.cs similarity index 100% rename from AlphaFS/Device/Native Other/SafeSetupDiClassDevsExHandle.cs rename to AlphaFS/Safe Handles/SafeSetupDiClassDevsExHandle.cs From 59f77eba2702f79bf2e21241be1d33ccdeaa6138 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 13 Jun 2018 12:00:44 +0200 Subject: [PATCH 103/133] Code improvement. --- ...DiskInfo_UsingDevicePathFromSystemDrive.cs | 20 +++++- ...tPhysicalDiskInfo_UsingLogicalDrivePath.cs | 4 +- AlphaFS/AlphaFS.csproj | 6 +- AlphaFS/Device/DriveInfo/DriveInfo.cs | 4 +- .../NativeMethods.VolumeManagement.cs | 11 ++- .../Local.EnumeratePhysicalDisks.cs | 68 ++++++++----------- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 3 - ....cs => PhysicalDiskInfo.ContainsVolume.cs} | 4 +- ...hysicalDiskInfo.cs => PhysicalDiskInfo.cs} | 0 ...ties.cs => PhysicalDiskInfo_Properties.cs} | 0 .../Storage/Local.GetStorageDeviceInfo.cs | 4 +- .../Storage/Local.GetStoragePartitionInfo.cs | 2 +- .../Volume/Volume.EnumerateVolumePathNames.cs | 2 +- .../Volume/Volume.GetVolumeDisplayName.cs | 7 +- 14 files changed, 68 insertions(+), 67 deletions(-) rename AlphaFS/Device/PhysicalDisk/{Device.PhysicalDiskInfo_Methods.cs => PhysicalDiskInfo.ContainsVolume.cs} (95%) rename AlphaFS/Device/PhysicalDisk/{Device.PhysicalDiskInfo.cs => PhysicalDiskInfo.cs} (100%) rename AlphaFS/Device/PhysicalDisk/{Device.PhysicalDiskInfo_Properties.cs => PhysicalDiskInfo_Properties.cs} (100%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs index 753080629..29cb5261d 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs @@ -56,9 +56,6 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive_Su Console.WriteLine(); - Assert.IsNull(pDisk.StoragePartitionInfo); - - Assert.IsNotNull(pDisk); Assert.IsNotNull(pDisk.LogicalDrives); @@ -68,6 +65,23 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive_Su Assert.AreEqual(pDisk.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceDrive)); Assert.AreEqual(pDisk.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceVolume)); + + + // Show all partition information. + + if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) + { + foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, true); + } + + if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) + { + foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, true); + } + + Console.WriteLine(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs index 866c8a7f4..0e1a54535 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs @@ -78,9 +78,7 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePath_Success() Assert.IsNotNull(pDisk.VolumeGuids); - if (pDisk.StorageDeviceInfo.PartitionNumber == -1) - Assert.IsNull(pDisk.StoragePartitionInfo); - else + if (pDisk.StorageDeviceInfo.PartitionNumber > 0) Assert.IsNotNull(pDisk.StoragePartitionInfo); diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index b762f1cf2..3c096406c 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -198,8 +198,8 @@ - - + + @@ -218,7 +218,7 @@ - + diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.cs index 96706ca9b..3c9d5ddf2 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.cs @@ -270,7 +270,7 @@ public VolumeInfo VolumeInfo #region .NET - /// Retrieves the names of the logical drives on the Computer in the form "drive letter:\". + /// Retrieves the drive names of all logical drives on a Computer. /// Returns an of instances on the Computer. [SecurityCritical] public static DriveInfo[] GetDrives() @@ -290,7 +290,7 @@ public override string ToString() #endregion // .NET - /// [AlphaFS] Retrieves the names of the logical drives on the Computer in the form "drive letter:\". + /// [AlphaFS] Retrieves the drive names of all logical drives on a Computer. /// Returns an of instances on the Computer. /// Retrieve logical drives as known by the Environment. /// Retrieve only when accessible (IsReady) logical drives. diff --git a/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs b/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs index 0bb3e2c94..861c549e4 100644 --- a/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.VolumeManagement.cs @@ -251,12 +251,11 @@ internal static partial class NativeMethods /// Retrieves a list of drive letters and mounted folder paths for the specified volume. - /// Minimum supported client: Windows XP. - /// Minimum supported server: Windows Server 2003. - /// - /// 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. - /// + /// + /// Minimum supported client: Windows XP [desktop apps only]. + /// Minimum supported server: Windows Server 2003 [desktop apps only]. + /// + /// 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. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumePathNamesForVolumeNameW"), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 4462d16ad..9d6943edc 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -21,12 +21,10 @@ using System.Collections.Generic; using System.Collections.ObjectModel; -using System.IO; using System.Linq; using System.Security; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; -using DriveInfo = Alphaleonis.Win32.Filesystem.DriveInfo; using Path = Alphaleonis.Win32.Filesystem.Path; namespace Alphaleonis.Win32.Device @@ -50,13 +48,10 @@ public static IEnumerable EnumeratePhysicalDisks() private static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, int deviceNumber = -1) { var isDeviceNumber = deviceNumber > -1; - var driveTypes = new[] {DriveType.CDRom, DriveType.Fixed, DriveType.Removable}; - var physicalDisks = new PhysicalDiskInfo[1]; + var physicalDisks = new Collection(); var volumeGuids = new Collection(); var logicalDrives = new Collection(); - - - // Devices / Physical disk. + foreach (var deviceInfo in EnumerateDevicesCore(null, DeviceGuid.Disk, false)) { @@ -64,44 +59,37 @@ private static IEnumerable EnumeratePhysicalDisksCore(bool isE if (null == storageDeviceInfo || isDeviceNumber && storageDeviceInfo.DeviceNumber != deviceNumber) continue; - - physicalDisks[0] = PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, deviceInfo); + + physicalDisks.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, deviceInfo)); // There can only be one. - break; + if (isDeviceNumber) + break; } - if (null == physicalDisks[0]) + if (physicalDisks.Count == 0) yield break; - // Volumes. + // Retrieve volumes belonging to deviceNumber. - foreach (var volumeGuid in Volume.EnumerateVolumes()) + foreach (var volume in Volume.EnumerateVolumes()) { - var storageDeviceInfo = GetStorageDeviceInfoCore(false, volumeGuid); + var storageDeviceInfo = GetStorageDeviceInfoCore(false, volume); - if (null == storageDeviceInfo || isDeviceNumber && storageDeviceInfo.DeviceNumber != deviceNumber) + if (null == storageDeviceInfo || isDeviceNumber && deviceNumber != storageDeviceInfo.DeviceNumber) continue; - volumeGuids.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, volumeGuid, null)); - } - - - // Logical drives. + volumeGuids.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, volume, null)); - foreach (var driveInfo in DriveInfo.GetDrives()) - { - if (!driveTypes.Contains(driveInfo.DriveType)) - continue; - var storageDeviceInfo = GetStorageDeviceInfoCore(false, driveInfo.Name); + // Resolve logical drives. - if (null == storageDeviceInfo || storageDeviceInfo.DeviceNumber != deviceNumber) - continue; + var driveName = Volume.GetVolumeDisplayName(volume); - logicalDrives.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, driveInfo.Name, null)); + if (!Utils.IsNullOrWhiteSpace(driveName)) + logicalDrives.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, driveName, null)); } @@ -111,27 +99,31 @@ private static IEnumerable EnumeratePhysicalDisksCore(bool isE } - private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, IEnumerable pVolumes, IEnumerable pLogicalDrives) + private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, ICollection pVolumes, ICollection pLogicalDrives) { var pDiskInfo = Utils.CopyFrom(pDisk); - foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber)) - { - var driveNumber = pVolume.StorageDeviceInfo.DeviceNumber; + if (null != pVolumes && pVolumes.Count > 0) - var partitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; + foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber)) + { + var driveNumber = pVolume.StorageDeviceInfo.DeviceNumber; + var partitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; + - PopulateVolumeDetails(pDiskInfo, partitionNumber, pVolume.DevicePath); + PopulateVolumeDetails(pDiskInfo, partitionNumber, pVolume.DevicePath); - // Get logical drive from volume matching DeviceNumber and PartitionNumber. + // Get logical drive from volume matching DeviceNumber and PartitionNumber. - foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => pDriveLogical.StorageDeviceInfo.DeviceNumber == driveNumber && pDriveLogical.StorageDeviceInfo.PartitionNumber == partitionNumber)) + if (null != pLogicalDrives && pLogicalDrives.Count > 0) - PopulateLogicalDriveDetails(pDiskInfo, pLogicalDrive.DevicePath); - } + foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => driveNumber == pDriveLogical.StorageDeviceInfo.DeviceNumber && partitionNumber == pDriveLogical.StorageDeviceInfo.PartitionNumber)) + + PopulateLogicalDriveDetails(pDiskInfo, pLogicalDrive.DevicePath); + } return pDiskInfo; diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index f0c3c368a..2b4fee5bc 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -127,9 +127,6 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de { if (isDrive || isVolume) { - if (!pDiskInfo.ContainsVolume(localDevicePath)) - continue; - physicalDiskInfo = pDiskInfo; break; } diff --git a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Methods.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.ContainsVolume.cs similarity index 95% rename from AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Methods.cs rename to AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.ContainsVolume.cs index 223a12d11..58ff103ac 100644 --- a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Methods.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.ContainsVolume.cs @@ -27,11 +27,11 @@ namespace Alphaleonis.Win32.Device { public sealed partial class PhysicalDiskInfo { - /// Checks if the logical drive/volume is located on the physical disk. + /// Checks if the volume/logical drive is located on the physical disk. /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// - /// true if the logical drive/volume is located on the physical disk; otherwise, false. + /// true if the volume/logical drive is located on the physical disk; otherwise, false. /// /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ diff --git a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs similarity index 100% rename from AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo.cs rename to AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs diff --git a/AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Properties.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs similarity index 100% rename from AlphaFS/Device/PhysicalDisk/Device.PhysicalDiskInfo_Properties.cs rename to AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index daacee2a5..e6eea3c7d 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -96,9 +96,8 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - StorageDeviceInfo storageDeviceInfo; - + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) @@ -110,6 +109,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri SetStorageDeviceInfoData(isElevated, safeHandle, localDevicePath, storageDeviceInfo); } + return storageDeviceInfo; } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 6e1cede35..99817fbf5 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -88,7 +88,7 @@ public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, stri /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// [SecurityCritical] - internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, int deviceNumber, string devicePath) + private static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, int deviceNumber, string devicePath) { var isDeviceNumber = deviceNumber > -1; bool isDevice; diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs index 136f80b5e..360bce7d6 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Filesystem public static partial class Volume { /// [AlphaFS] Returns an collection of drive letters and mounted folder paths for the specified volume. - /// RReturns an collection of path names for the specified volume. + /// Returns an collection of path names for the specified volume. /// /// /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs index 777d175bf..5f5df4e5b 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs @@ -38,12 +38,13 @@ public static partial class Volume [SecurityCritical] public static string GetVolumeDisplayName(string volumeName) { - string[] smallestMountPoint = { new string(Path.WildcardStarMatchAllChar, NativeMethods.MaxPathUnicode) }; + 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; + foreach (var mountPoint in EnumerateVolumePathNames(volumeName).Where(mPoint => !Utils.IsNullOrWhiteSpace(mPoint) && mPoint.Length < smallestMountPoint[0].Length)) + + smallestMountPoint[0] = mountPoint; } catch { From 4c29d634fc2c58b63b25a1bbdb67dabd1449ac6b Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 13 Jun 2018 13:57:25 +0200 Subject: [PATCH 104/133] Code improvement, moved some files. --- ...DiskInfo_UsingDevicePathFromSystemDrive.cs | 3 + ...DiskInfo_UsingVolumePathFromSystemDrive.cs | 15 +--- ...pterInfo_UsingDevicePathFromSystemDrive.cs | 16 ++-- ...torageAdapterInfo_UsingLogicalDrivePath.cs | 17 ++-- ...pterInfo_UsingVolumePathFromSystemDrive.cs | 12 +-- ...viceInfo_UsingDevicePathFromSystemDrive.cs | 8 +- ...StorageDeviceInfo_UsingLogicalDrivePath.cs | 5 +- ...viceInfo_UsingVolumePathFromSystemDrive.cs | 7 +- ...ngDevicePathFromSystemDrive_ReturnsNull.cs | 8 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 4 +- ...ectoryName_PropertyExistsShouldbeFalse.cs} | 8 +- ...yAsFileName_PropertyExistsShouldbeFalse.cs | 8 +- AlphaFS/AlphaFS.csproj | 5 +- .../NativeMethods.DiskPartitionType.cs | 0 .../NativeMethods.EfiPartitionAttributes.cs | 0 .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 6 +- ...icalDiskInfo.InitializePhysicalDiskInfo.cs | 90 +++++++++++++++++++ .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 67 -------------- .../Storage/Device.StorageDeviceInfo.cs | 4 +- .../Storage/Local.GetStorageDeviceInfo.cs | 19 ++-- AlphaFS/Filesystem/DiskSpaceInfo.cs | 4 +- .../NativeMethods.EncryptedFileRaw.cs | 8 +- 22 files changed, 167 insertions(+), 147 deletions(-) rename AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/{DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryeName_PropertyExistsShouldbeFalse.cs => DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldbeFalse.cs} (91%) rename AlphaFS/Device/{Native Methods => Native Other}/NativeMethods.DiskPartitionType.cs (100%) rename AlphaFS/Device/{Native Methods => Native Other}/NativeMethods.EfiPartitionAttributes.cs (100%) create mode 100644 AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs index 29cb5261d..65d230319 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs @@ -38,11 +38,14 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive_Su var deviceCount = 0; var sourceDrive = UnitTestConstants.SysDrive; + var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); + var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs index b8639bdd8..2fdaf3223 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs @@ -35,20 +35,18 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Su { UnitTestConstants.PrintUnitTestHeader(false); - var gotDisk = false; var volumeCount = 0; var sourceDrive = UnitTestConstants.SysDrive; var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); + Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]", ++volumeCount, sourceVolume); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); - - - Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]\t\t{2}\t\t{3}", ++volumeCount, sourceVolume, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); + UnitTestConstants.Dump(pDisk); UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); @@ -75,23 +73,18 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Su if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) { - gotDisk = true; - foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) UnitTestConstants.Dump(partition, true); } if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) { - gotDisk = true; - foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) UnitTestConstants.Dump(partition, true); } - Console.WriteLine(); - Assert.IsTrue(gotDisk); + Console.WriteLine(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs index 7d332bdd6..454b88185 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs @@ -39,27 +39,21 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingDevicePathFromSystemDrive_ var sourceDrive = UnitTestConstants.SysDrive; var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); - - - Console.WriteLine("#{0:000}\tInput Device Path: [{1}]\t\t{2}", ++deviceCount, devicePath, pDisk.StorageAdapterInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); + var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(devicePath); - + UnitTestConstants.Dump(storageAdapterInfo); Assert.IsNotNull(storageAdapterInfo); Assert.IsNotNull(pDisk); - - if (Alphaleonis.Win32.Security.ProcessContext.IsElevatedProcess) - Assert.AreEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); - - else - Assert.AreNotEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); + Assert.AreEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs index e51f43a39..194ad978d 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs @@ -34,7 +34,7 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingLogicalDrivePath_Success() { UnitTestConstants.PrintUnitTestHeader(false); - var gotDisk = false; + var gotAdapter = false; var driveCount = 0; @@ -55,24 +55,23 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingLogicalDrivePath_Success() continue; } + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); - var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(driveInfo.Name); - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageAdapterInfo.ToString()); + var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(driveInfo.Name); + UnitTestConstants.Dump(storageAdapterInfo); - - + Assert.IsNotNull(storageAdapterInfo); - gotDisk = true; - - + gotAdapter = true; + Console.WriteLine(); } - Assert.IsTrue(gotDisk); + Assert.IsTrue(gotAdapter); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs index 36de56cee..c041426cc 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs @@ -32,7 +32,6 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] public void AlphaFS_Device_GetStorageAdapterInfo_UsingVolumePathFromSystemDrive_Success() { - //UnitTestAssert.IsElevatedProcess(); UnitTestConstants.PrintUnitTestHeader(false); var volumeCount = 0; @@ -41,23 +40,20 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingVolumePathFromSystemDrive_ var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); - - - Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]\t\t{2}", ++volumeCount, sourceVolume, pDisk.StorageAdapterInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]", ++volumeCount, sourceVolume); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); + var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(sourceVolume); - + UnitTestConstants.Dump(storageAdapterInfo); Assert.IsNotNull(storageAdapterInfo); Assert.IsNotNull(pDisk); - Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs index d52a233dc..d7cc5ef46 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs @@ -37,14 +37,14 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingDevicePathFromSystemDrive_S var deviceCount = 0; var sourceDrive = UnitTestConstants.SysDrive; - var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; - - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); + var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; - Console.WriteLine("#{0:000}\tInput Device Path: [{1}]\t\t{2}", ++deviceCount, devicePath, pDisk.StorageDeviceInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); + var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(devicePath); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs index 6e249e8c6..8f74f3778 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs @@ -55,10 +55,11 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingLogicalDrivePath_Success() continue; } + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); - var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(driveInfo.Name); - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storageDeviceInfo.ToString()); + var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(driveInfo.Name); + UnitTestConstants.Dump(storageDeviceInfo); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs index 9af972c88..5d32e5e64 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs @@ -40,12 +40,11 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingVolumePathFromSystemDrive_S var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); - - - Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]\t\t{2}", ++volumeCount, sourceVolume, pDisk.StorageDeviceInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]", ++volumeCount, sourceVolume); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); + var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(sourceVolume); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs index 3ba8b6e6d..f3568c439 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs @@ -41,10 +41,12 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingDevicePathFromSystemDriv var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); - + + var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(devicePath); - - Assert.IsNull(storagePartitionInfo); + + + UnitTestConstants.Dump(storagePartitionInfo); } } } diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index a07bc3fc1..7b9e95ac3 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -169,7 +169,7 @@ - + @@ -183,7 +183,7 @@ - + diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryeName_PropertyExistsShouldbeFalse.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldbeFalse.cs similarity index 91% rename from AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryeName_PropertyExistsShouldbeFalse.cs rename to AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldbeFalse.cs index f681e5de3..c4eb7ba15 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryeName_PropertyExistsShouldbeFalse.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldbeFalse.cs @@ -30,14 +30,14 @@ public partial class DirectoryInfoTest [TestMethod] - public void DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryeName_PropertyExistsShouldbeFalse_LocalAndNetwork_Success() + public void DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse_LocalAndNetwork_Success() { - DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryeName_PropertyExistsShouldbeFalse(false); - DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryeName_PropertyExistsShouldbeFalse(true); + DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse(false); + DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse(true); } - private void DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryeName_PropertyExistsShouldbeFalse(bool isNetwork) + private void DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse.cs b/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse.cs index e2c8c3d98..0d2eb9f71 100644 --- a/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse.cs +++ b/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse.cs @@ -30,14 +30,14 @@ public partial class FileInfoTest [TestMethod] - public void FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse_LocalAndNetwork_Success() + public void FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse_LocalAndNetwork_Success() { - FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse(false); - FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse(true); + FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse(false); + FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse(true); } - private void FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse(bool isNetwork) + private void FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 3c096406c..bc0b2bd0e 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -198,6 +198,7 @@ + @@ -334,7 +335,7 @@ - + @@ -345,7 +346,7 @@ - + diff --git a/AlphaFS/Device/Native Methods/NativeMethods.DiskPartitionType.cs b/AlphaFS/Device/Native Other/NativeMethods.DiskPartitionType.cs similarity index 100% rename from AlphaFS/Device/Native Methods/NativeMethods.DiskPartitionType.cs rename to AlphaFS/Device/Native Other/NativeMethods.DiskPartitionType.cs diff --git a/AlphaFS/Device/Native Methods/NativeMethods.EfiPartitionAttributes.cs b/AlphaFS/Device/Native Other/NativeMethods.EfiPartitionAttributes.cs similarity index 100% rename from AlphaFS/Device/Native Methods/NativeMethods.EfiPartitionAttributes.cs rename to AlphaFS/Device/Native Other/NativeMethods.EfiPartitionAttributes.cs diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index 2b4fee5bc..bcbc7dfd9 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Device public static partial class Local { /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . - /// Returns a instance that represents the physical disk on the Computer or null on error/no data available. + /// Returns a instance that represents the physical disk on the Computer or null if the device can not be retrieved. /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. /// Do not call this method for every logical drive/volume on the Computer as each call queries all physical disks, associated volumes and logical drives. @@ -53,7 +53,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . - /// Returns a instance that represents the physical disk on the Computer or null on error/no data available. + /// Returns a instance that represents the physical disk on the Computer or null if the device can not be retrieved. /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. /// Do not call this method for every logical drive/volume on the Computer as each call queries all physical disks, associated volumes and logical drives. @@ -79,7 +79,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(bool isElevated, string devic /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . - /// Returns a instance that represents the physical disk on the Computer or null on error/no data available. + /// Returns a instance that represents the physical disk on the Computer or null if the device can not be retrieved. /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. /// Do not call this method for every logical drive/volume on the Computer as each call queries all physical disks, associated volumes and logical drives. diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs new file mode 100644 index 000000000..521569c72 --- /dev/null +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs @@ -0,0 +1,90 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; +using Alphaleonis.Win32.Filesystem; + +namespace Alphaleonis.Win32.Device +{ + public sealed partial class PhysicalDiskInfo + { + /// [AlphaFS] Initializes a instance that is related to the logical drive name, volume or . + /// Returns a instance that represents the physical disk on the Computer or null if the device can not be retrieved. + /// Use either or , not both. + /// + /// + /// + /// + /// true indicates the current process is in an elevated state, allowing to retrieve more data. + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + /// A instance. + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] + [SecurityCritical] + internal static PhysicalDiskInfo InitializePhysicalDiskInfo(bool isElevated, string devicePath, DeviceInfo deviceInfo) + { + if (null == devicePath && null == deviceInfo) + return null; + + var isDevice = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); + + if (isDevice) + devicePath = deviceInfo.DevicePath; + + var storageDeviceInfo = Local.GetStorageDeviceInfoCore(isElevated, devicePath); + + if (null == storageDeviceInfo) + return null; + + + var pDiskInfo = new PhysicalDiskInfo + { + DevicePath = devicePath, + + DeviceDescription = isDevice ? deviceInfo.DeviceDescription : null, + + Name = isDevice ? deviceInfo.FriendlyName : null, + + PhysicalDeviceObjectName = isDevice ? deviceInfo.PhysicalDeviceObjectName : null, + + + StorageAdapterInfo = Local.GetStorageAdapterInfo(isElevated, devicePath), + + StorageDeviceInfo = storageDeviceInfo, + + StoragePartitionInfo = Local.GetStoragePartitionInfo(isElevated, devicePath) + }; + + + if (isDevice) + pDiskInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; + + + return pDiskInfo; + } + } +} diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index b66af9963..4a137f332 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -53,75 +53,8 @@ public PhysicalDiskInfo(int deviceNumber) } #endregion // Constructors - - - /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . - /// A instance that represents the physical disk on the Computer or null on error/no data available. - /// - /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every logical drive/volume on the Computer as each call queries all physical disks, associated volumes and logical drives. - /// Instead, use method and property or . - /// - /// - /// - /// - /// - /// true indicates the current process is in an elevated state, allowing to retrieve more data. - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// - /// A instance. - /// Use either or , not both. - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] - [SecurityCritical] - internal static PhysicalDiskInfo InitializePhysicalDiskInfo(bool isElevated, string devicePath, DeviceInfo deviceInfo) - { - if (null == devicePath && null == deviceInfo) - return null; - - var isDevice = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); - - if (isDevice) - devicePath = deviceInfo.DevicePath; - - var storageDeviceInfo = Local.GetStorageDeviceInfoCore(isElevated, devicePath); - - if (null == storageDeviceInfo) - return null; - - - var pDiskInfo = new PhysicalDiskInfo - { - DevicePath = devicePath, - - DeviceDescription = isDevice ? deviceInfo.DeviceDescription : null, - - Name = isDevice ? deviceInfo.FriendlyName : null, - - PhysicalDeviceObjectName = isDevice ? deviceInfo.PhysicalDeviceObjectName : null, - - - StorageAdapterInfo = Local.GetStorageAdapterInfo(isElevated, devicePath), - - StorageDeviceInfo = storageDeviceInfo, - - StoragePartitionInfo = Local.GetStoragePartitionInfo(isElevated, devicePath) - }; - - - if (isDevice) - pDiskInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; - - - return pDiskInfo; - } - - /// Returns the "FriendlyName" of the physical disk. /// Returns a string that represents this instance. public override string ToString() diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 1c6ccac98..309e41ded 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -111,11 +111,11 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public string SerialNumber { get; internal set; } - /// The total size of the physical disk. If the session is not elevated 0 is returned. + /// The total size of the physical disk or 0 if the process is not elevated. public long TotalSize { get; internal set; } - /// The total size of the physical disk, formatted as a unit size. If the session is not elevated 0 is returned. + /// The of the physical disk, formatted as a unit size. public string TotalSizeUnitSize { get { return Utils.UnitSizeToText(TotalSize); } diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index e6eea3c7d..f6ea9de71 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -106,7 +106,8 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri storageDeviceInfo = null != safeBuffer ? new StorageDeviceInfo(safeBuffer.PtrToStructure()) : null; if (null != storageDeviceInfo) - SetStorageDeviceInfoData(isElevated, safeHandle, localDevicePath, storageDeviceInfo); + + SetStorageDeviceInfoData(isElevated, isDevice, safeHandle, localDevicePath, storageDeviceInfo); } @@ -116,7 +117,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] - private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle safeHandle, string pathForException, StorageDeviceInfo storageDeviceInfo) + private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, SafeFileHandle safeHandle, string localDevicePath, StorageDeviceInfo storageDeviceInfo) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { @@ -125,7 +126,7 @@ private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle saf }; - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathForException, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) { var deviceDescriptor = safeBuffer.PtrToStructure(); @@ -159,10 +160,18 @@ private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle saf // Get disk total size. if (isElevated) - - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, pathForException)) + { + using (var safeBuffer = GetDeviceIoData(safeHandle,NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, localDevicePath)) storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; + } + + else if (!isDevice) + { + var diskSpaceInfo = Volume.GetDiskFreeSpace(localDevicePath, false); + + storageDeviceInfo.TotalSize = diskSpaceInfo.TotalNumberOfBytes; + } } } } diff --git a/AlphaFS/Filesystem/DiskSpaceInfo.cs b/AlphaFS/Filesystem/DiskSpaceInfo.cs index a80fbb672..1876f6ed3 100644 --- a/AlphaFS/Filesystem/DiskSpaceInfo.cs +++ b/AlphaFS/Filesystem/DiskSpaceInfo.cs @@ -88,8 +88,8 @@ public DiskSpaceInfo(string driveName, bool? spaceInfoType, bool refresh, bool c else { - _initGetSpaceInfo = (bool)!spaceInfoType; - _initGetClusterInfo = (bool)spaceInfoType; + _initGetSpaceInfo = (bool) !spaceInfoType; + _initGetClusterInfo = (bool) spaceInfoType; } _continueOnAccessError = continueOnException; diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.EncryptedFileRaw.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.EncryptedFileRaw.cs index 6fa078190..a373d7204 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.EncryptedFileRaw.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.EncryptedFileRaw.cs @@ -17,7 +17,7 @@ internal partial class NativeMethods /// [out] The address of a context block that must be presented in subsequent calls to /// ReadEncryptedFileRaw, WriteEncryptedFileRaw, or CloseEncryptedFileRaw. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] - [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode, EntryPoint = "OpenEncryptedFileRawW"), SuppressUnmanagedCodeSecurity] + [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); @@ -27,7 +27,7 @@ internal partial class NativeMethods /// Minimum supported server: Windows Server 2003 [desktop apps only] /// A pointer to a system-defined context block. The OpenEncryptedFileRaw function returns the context block. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] - [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] + [DllImport("advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void CloseEncryptedFileRaw(IntPtr pvContext); @@ -37,7 +37,7 @@ internal partial class NativeMethods /// Minimum supported client: Windows XP Professional [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule"), SuppressUnmanagedCodeSecurity] - [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode), 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); @@ -48,7 +48,7 @@ internal partial class NativeMethods /// Minimum supported client: Windows XP Professional [desktop apps only] /// Minimum supported server: Windows Server 2003 [desktop apps only] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] - [DllImport("Advapi32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] + [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); From ed6b0f2342ab61388b2a6cfb4a24157bf317dbbc Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 13 Jun 2018 18:44:59 +0200 Subject: [PATCH 105/133] Code improvement. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 4 +- ...ngDevicePathFromSystemDrive_ReturnsNull.cs | 19 ++++ ...ragePartitionInfo_UsingLogicalDrivePath.cs | 2 +- ...tionInfo_UsingVolumePathFromSystemDrive.cs | 16 +++ .../Local.EnumeratePhysicalDisks.cs | 106 +++++++----------- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 32 +----- ...icalDiskInfo.InitializePhysicalDiskInfo.cs | 24 +--- .../Storage/Local.GetStorageAdapterInfo.cs | 27 +++-- .../Storage/Local.GetStorageDeviceInfo.cs | 12 +- .../Device/Volume/Volume.EnumerateVolumes.cs | 5 +- .../Volume/Volume.GetVolumeDisplayName.cs | 8 +- 11 files changed, 116 insertions(+), 139 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index 5376c6398..7c7183b47 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -31,7 +31,7 @@ public partial class EnumerationTest [TestMethod] - public void AlphaFS_Device_EnumeratePhysicalDisks_Local_Success() + public void AlphaFS_Device_EnumeratePhysicalDisks_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -49,7 +49,7 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Local_Success() foreach (var pDisk in pDrives) { - Console.WriteLine("#{0:000}\tPhysical Disk: [{1}]\t\t{2}\t\t{3}", ++pDriveCount, pDisk.StorageDeviceInfo.DeviceNumber, pDisk.StorageAdapterInfo.ToString(), pDisk.StorageDeviceInfo.ToString()); + Console.WriteLine("#{0:000}\tPhysical Disk: [{1}]", ++pDriveCount, pDisk.StorageDeviceInfo.DeviceNumber); UnitTestConstants.Dump(pDisk); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs index f3568c439..819b9f5fa 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs @@ -47,6 +47,25 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingDevicePathFromSystemDriv UnitTestConstants.Dump(storagePartitionInfo); + + + if (null != storagePartitionInfo) + { + // Show all partition information. + + if (null != storagePartitionInfo.GptPartitionInfo) + { + foreach (var partition in storagePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, true); + } + + + if (null != storagePartitionInfo.MbrPartitionInfo) + { + foreach (var partition in storagePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, true); + } + } } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs index 5f6e4aa03..fb504e0f4 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs @@ -68,7 +68,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingLogicalDrivePath_Success Assert.IsNotNull(storagePartitionInfo); - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, storagePartitionInfo.ToString()); + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); UnitTestConstants.Dump(storagePartitionInfo); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs index 3c8153281..6cfadf2a6 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs @@ -58,6 +58,22 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingVolumePathFromSystemDriv Assert.AreEqual(pDisk.StorageDeviceInfo.DeviceNumber, storagePartitionInfo.DeviceNumber); Assert.AreEqual(pDisk.StoragePartitionInfo, storagePartitionInfo); + + + // Show all partition information. + + if (null != storagePartitionInfo.GptPartitionInfo) + { + foreach (var partition in storagePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, true); + } + + + if (null != storagePartitionInfo.MbrPartitionInfo) + { + foreach (var partition in storagePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, true); + } } } } diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 9d6943edc..4c99eb316 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -21,7 +21,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Linq; using System.Security; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; @@ -36,7 +35,7 @@ public static partial class Local [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() { - return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess); + return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess, -1); } @@ -45,92 +44,71 @@ public static IEnumerable EnumeratePhysicalDisks() /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// Retrieve a instance by device number. [SecurityCritical] - private static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, int deviceNumber = -1) + private static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, int deviceNumber) { var isDeviceNumber = deviceNumber > -1; - var physicalDisks = new Collection(); - var volumeGuids = new Collection(); - var logicalDrives = new Collection(); - foreach (var deviceInfo in EnumerateDevicesCore(null, DeviceGuid.Disk, false)) { - var storageDeviceInfo = GetStorageDeviceInfoCore(false, deviceInfo.DevicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(false, deviceNumber, deviceInfo.DevicePath); - if (null == storageDeviceInfo || isDeviceNumber && storageDeviceInfo.DeviceNumber != deviceNumber) + if (null == storageDeviceInfo) continue; - physicalDisks.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, deviceInfo)); + + var pDiskInfo = PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, storageDeviceInfo, deviceInfo); + + yield return PopulatePhysicalDisk(deviceNumber, pDiskInfo); + // There can only be one. if (isDeviceNumber) break; } + } - if (physicalDisks.Count == 0) - yield break; - - - // Retrieve volumes belonging to deviceNumber. + /// Retrieves volumes and logical drives that belong to + private static PhysicalDiskInfo PopulatePhysicalDisk(int deviceNumber, PhysicalDiskInfo pDiskInfo) + { + var newPDiskInfo = Utils.CopyFrom(pDiskInfo); - foreach (var volume in Volume.EnumerateVolumes()) + foreach (var volumeGuid in Volume.EnumerateVolumes()) { - var storageDeviceInfo = GetStorageDeviceInfoCore(false, volume); + var storageDeviceInfo = GetStorageDeviceInfoCore(false, deviceNumber, volumeGuid); - if (null == storageDeviceInfo || isDeviceNumber && deviceNumber != storageDeviceInfo.DeviceNumber) + if (null == storageDeviceInfo || storageDeviceInfo.DeviceNumber != newPDiskInfo.StorageDeviceInfo.DeviceNumber) continue; + + AddToPartitionIndex(newPDiskInfo, storageDeviceInfo.PartitionNumber); + + AddToVolumeGuids(newPDiskInfo, volumeGuid); + + // Resolve logical drive from volume matching DeviceNumber and PartitionNumber. - volumeGuids.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, volume, null)); - - - // Resolve logical drives. - - var driveName = Volume.GetVolumeDisplayName(volume); + var driveName = Volume.GetVolumeDisplayName(volumeGuid); if (!Utils.IsNullOrWhiteSpace(driveName)) - logicalDrives.Add(PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, driveName, null)); - } - - - foreach (var pDisk in physicalDisks) - yield return PopulatePhysicalDisk(pDisk, volumeGuids, logicalDrives); + AddToLogicalDrives(newPDiskInfo, driveName); + } + + return newPDiskInfo; } - - - private static PhysicalDiskInfo PopulatePhysicalDisk(PhysicalDiskInfo pDisk, ICollection pVolumes, ICollection pLogicalDrives) - { - var pDiskInfo = Utils.CopyFrom(pDisk); - - if (null != pVolumes && pVolumes.Count > 0) - foreach (var pVolume in pVolumes.Where(pVol => pVol.StorageDeviceInfo.DeviceNumber == pDiskInfo.StorageDeviceInfo.DeviceNumber)) - { - var driveNumber = pVolume.StorageDeviceInfo.DeviceNumber; - - var partitionNumber = pVolume.StorageDeviceInfo.PartitionNumber; - - - PopulateVolumeDetails(pDiskInfo, partitionNumber, pVolume.DevicePath); - - - // Get logical drive from volume matching DeviceNumber and PartitionNumber. - - if (null != pLogicalDrives && pLogicalDrives.Count > 0) - - foreach (var pLogicalDrive in pLogicalDrives.Where(pDriveLogical => driveNumber == pDriveLogical.StorageDeviceInfo.DeviceNumber && partitionNumber == pDriveLogical.StorageDeviceInfo.PartitionNumber)) - - PopulateLogicalDriveDetails(pDiskInfo, pLogicalDrive.DevicePath); - } + private static void AddToPartitionIndex(PhysicalDiskInfo pDiskInfo, int deviceNumber) + { + // Add device partition index numbers. + if (null == pDiskInfo.PartitionIndexes) + pDiskInfo.PartitionIndexes = new Collection(); - return pDiskInfo; + pDiskInfo.PartitionIndexes.Add(deviceNumber); } - - private static void PopulateVolumeDetails(PhysicalDiskInfo pDiskInfo, int partitionNumber, string volumeGuid) + + private static void AddToVolumeGuids(PhysicalDiskInfo pDiskInfo, string volumeGuid) { //// Add device volume labels. @@ -138,15 +116,7 @@ private static void PopulateVolumeDetails(PhysicalDiskInfo pDiskInfo, int partit // pDiskInfo.VolumeLabels = new Collection(); //pDiskInfo.VolumeLabels.Add(pVolume.Name); - - - // Add device partition index numbers. - - if (null == pDiskInfo.PartitionIndexes) - pDiskInfo.PartitionIndexes = new Collection(); - - pDiskInfo.PartitionIndexes.Add(partitionNumber); - + // Add device volume GUIDs. @@ -157,7 +127,7 @@ private static void PopulateVolumeDetails(PhysicalDiskInfo pDiskInfo, int partit } - private static void PopulateLogicalDriveDetails(PhysicalDiskInfo pDiskInfo, string drivePath) + private static void AddToLogicalDrives(PhysicalDiskInfo pDiskInfo, string drivePath) { // Add device logical drive. diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index bcbc7dfd9..91b6a34bf 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -21,6 +21,7 @@ using System; using System.Globalization; +using System.Linq; using System.Security; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; @@ -112,7 +113,7 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de // StorageDeviceInfo contains the device number. - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, localDevicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath); if (null == storageDeviceInfo) return null; @@ -120,35 +121,8 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de if (!isDeviceNumber) deviceNumber = storageDeviceInfo.DeviceNumber; - PhysicalDiskInfo physicalDiskInfo = null; - - - foreach (var pDiskInfo in EnumeratePhysicalDisksCore(isElevated, deviceNumber)) - { - if (isDrive || isVolume) - { - physicalDiskInfo = pDiskInfo; - break; - } - - - if (isDeviceNumber) - { - if (pDiskInfo.StorageDeviceInfo.DeviceNumber != storageDeviceInfo.DeviceNumber) - continue; - - physicalDiskInfo = pDiskInfo; - break; - } - - - if (pDiskInfo.StorageDeviceInfo.DeviceNumber != storageDeviceInfo.DeviceNumber && pDiskInfo.StorageDeviceInfo.PartitionNumber != storageDeviceInfo.PartitionNumber) - continue; - - physicalDiskInfo = pDiskInfo; - break; - } + var physicalDiskInfo = EnumeratePhysicalDisksCore(isElevated, deviceNumber).FirstOrDefault(); if (null != physicalDiskInfo) { diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs index 521569c72..f49abaa9c 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs @@ -42,10 +42,11 @@ public sealed partial class PhysicalDiskInfo /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// - /// A instance. + /// An initialized instance. + /// An initialized instance. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] [SecurityCritical] - internal static PhysicalDiskInfo InitializePhysicalDiskInfo(bool isElevated, string devicePath, DeviceInfo deviceInfo) + internal static PhysicalDiskInfo InitializePhysicalDiskInfo(bool isElevated, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) { if (null == devicePath && null == deviceInfo) return null; @@ -55,13 +56,7 @@ internal static PhysicalDiskInfo InitializePhysicalDiskInfo(bool isElevated, str if (isDevice) devicePath = deviceInfo.DevicePath; - var storageDeviceInfo = Local.GetStorageDeviceInfoCore(isElevated, devicePath); - - if (null == storageDeviceInfo) - return null; - - - var pDiskInfo = new PhysicalDiskInfo + return new PhysicalDiskInfo { DevicePath = devicePath, @@ -72,19 +67,12 @@ internal static PhysicalDiskInfo InitializePhysicalDiskInfo(bool isElevated, str PhysicalDeviceObjectName = isDevice ? deviceInfo.PhysicalDeviceObjectName : null, - StorageAdapterInfo = Local.GetStorageAdapterInfo(isElevated, devicePath), + StorageAdapterInfo = Local.GetStorageAdapterInfoCore(devicePath, deviceInfo), - StorageDeviceInfo = storageDeviceInfo, + StorageDeviceInfo = null != storageDeviceInfo ? storageDeviceInfo : Local.GetStorageDeviceInfoCore(isElevated, -1, devicePath), StoragePartitionInfo = Local.GetStoragePartitionInfo(isElevated, devicePath) }; - - - if (isDevice) - pDiskInfo.StorageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; - - - return pDiskInfo; } } } diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index 5e3a8fb3b..0f059727c 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -21,9 +21,7 @@ using System; using System.Security; -using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; -using Alphaleonis.Win32.Security; namespace Alphaleonis.Win32.Device { @@ -44,7 +42,7 @@ public static partial class Local [SecurityCritical] public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) { - return GetStorageAdapterInfo(ProcessContext.IsElevatedProcess, devicePath); + return GetStorageAdapterInfoCore(devicePath); } @@ -54,15 +52,15 @@ public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) /// /// /// - /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// + /// An initialized instance. [SecurityCritical] - public static StorageAdapterInfo GetStorageAdapterInfo(bool isElevated, string devicePath) + internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath, DeviceInfo deviceInfo = null) { bool isDrive; bool isVolume; @@ -79,13 +77,18 @@ public static StorageAdapterInfo GetStorageAdapterInfo(bool isElevated, string d PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery }; - - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, NativeMethods.FILE_ANY_ACCESS)) using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) { - return null == safeBuffer ? null : new StorageAdapterInfo(safeBuffer.PtrToStructure()); + var storageAdapterInfo = null == safeBuffer ? null : new StorageAdapterInfo(safeBuffer.PtrToStructure()); + + if (null != deviceInfo && null != storageAdapterInfo) + storageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; + + return storageAdapterInfo; } } } diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index f6ea9de71..8c23914dd 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -47,7 +47,7 @@ public static partial class Local [SecurityCritical] public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { - return GetStorageDeviceInfoCore(ProcessContext.IsElevatedProcess, devicePath); + return GetStorageDeviceInfoCore(ProcessContext.IsElevatedProcess, -1, devicePath); } @@ -67,7 +67,7 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) [SecurityCritical] public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string devicePath) { - return GetStorageDeviceInfoCore(isElevated, devicePath); + return GetStorageDeviceInfoCore(isElevated, -1, devicePath); } @@ -78,6 +78,7 @@ public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string dev /// /// /// true indicates the current process is in an elevated state, allowing to retrieve more data. + /// Retrieve a instance by device number. /// /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ @@ -85,8 +86,9 @@ public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string dev /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// [SecurityCritical] - internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, string devicePath) + internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int deviceNumber, string devicePath) { + var isDeviceNumber = deviceNumber > -1; bool isDrive; bool isVolume; bool isDevice; @@ -106,8 +108,12 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, stri storageDeviceInfo = null != safeBuffer ? new StorageDeviceInfo(safeBuffer.PtrToStructure()) : null; if (null != storageDeviceInfo) + { + if (isDeviceNumber && storageDeviceInfo.DeviceNumber != deviceNumber) + return null; SetStorageDeviceInfoData(isElevated, isDevice, safeHandle, localDevicePath, storageDeviceInfo); + } } diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs index 3c83beb02..0e650227a 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; @@ -28,8 +29,8 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { - /// [AlphaFS] Returns an collection of volumes on the Computer. - /// Returns an collection of volume names on the Computer. + /// [AlphaFS] Returns an collection of volume s on the Computer. + /// Returns an collection of volume s on the Computer. [SecurityCritical] public static IEnumerable EnumerateVolumes() { diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs index 5f5df4e5b..d439e0f6f 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs @@ -28,21 +28,21 @@ namespace Alphaleonis.Win32.Filesystem { public static partial class Volume { - /// [AlphaFS] Gets the shortest display name for the specified . + /// [AlphaFS] Gets the shortest display name for the specified . /// This method basically returns the shortest string returned by - /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A volume path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// /// The shortest display name for the specified volume found, or null if no display names were found. /// [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] - public static string GetVolumeDisplayName(string volumeName) + public static string GetVolumeDisplayName(string volumeGuid) { string[] smallestMountPoint = {new string(Path.WildcardStarMatchAllChar, NativeMethods.MaxPathUnicode)}; try { - foreach (var mountPoint in EnumerateVolumePathNames(volumeName).Where(mPoint => !Utils.IsNullOrWhiteSpace(mPoint) && mPoint.Length < smallestMountPoint[0].Length)) + foreach (var mountPoint in EnumerateVolumePathNames(volumeGuid).Where(mPoint => !Utils.IsNullOrWhiteSpace(mPoint) && mPoint.Length < smallestMountPoint[0].Length)) smallestMountPoint[0] = mountPoint; } From f5f00e97badf07997f3f161a703754c2e3edf941 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 14 Jun 2018 15:20:22 +0200 Subject: [PATCH 106/133] Code improvement. --- ...tionInfo_UsingVolumePathFromSystemDrive.cs | 5 ++-- ...tializeInstanceUsingPhysicalDriveNumber.cs | 4 +++ .../Local.EnumeratePhysicalDisks.cs | 29 +++++++++++-------- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 10 +++---- .../Storage/Device.StorageDeviceInfo.cs | 2 +- .../Storage/Device.StoragePartitionInfo.cs | 2 +- .../Storage/Local.GetStorageDeviceInfo.cs | 21 +++++++------- AlphaFS/Filesystem/DiskSpaceInfo.cs | 9 ++++-- 8 files changed, 47 insertions(+), 35 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs index 6cfadf2a6..9040ee435 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs @@ -40,11 +40,10 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingVolumePathFromSystemDriv var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); - + Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]", ++volumeCount, sourceVolume); - Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]\t\t{2}", ++volumeCount, sourceVolume, pDisk.StoragePartitionInfo.ToString()); + var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(sourceVolume); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs index 92047f3b2..dfa4669b3 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs @@ -50,6 +50,10 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingPhysicalDriveNumber_ UnitTestConstants.Dump(pDisk); + Assert.AreEqual(physicalDiskNumber, pDisk.StorageDeviceInfo.DeviceNumber); + + Assert.AreEqual(0, pDisk.StorageDeviceInfo.PartitionNumber); + Console.WriteLine(); } } diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 4c99eb316..4871389ee 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -21,6 +21,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Linq; using System.Security; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; @@ -50,15 +51,15 @@ private static IEnumerable EnumeratePhysicalDisksCore(bool isE foreach (var deviceInfo in EnumerateDevicesCore(null, DeviceGuid.Disk, false)) { - var storageDeviceInfo = GetStorageDeviceInfoCore(false, deviceNumber, deviceInfo.DevicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, deviceInfo.DevicePath); - if (null == storageDeviceInfo) + if (null == storageDeviceInfo || isDeviceNumber && deviceNumber != storageDeviceInfo.DeviceNumber) continue; - + var pDiskInfo = PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, storageDeviceInfo, deviceInfo); - yield return PopulatePhysicalDisk(deviceNumber, pDiskInfo); + yield return PopulatePhysicalDisk(isElevated, pDiskInfo); // There can only be one. @@ -68,18 +69,22 @@ private static IEnumerable EnumeratePhysicalDisksCore(bool isE } - /// Retrieves volumes and logical drives that belong to - private static PhysicalDiskInfo PopulatePhysicalDisk(int deviceNumber, PhysicalDiskInfo pDiskInfo) + /// Retrieves volumes and logical drives that belong to + private static PhysicalDiskInfo PopulatePhysicalDisk(bool isElevated, PhysicalDiskInfo pDiskInfo) { var newPDiskInfo = Utils.CopyFrom(pDiskInfo); - foreach (var volumeGuid in Volume.EnumerateVolumes()) + var deviceNumber = newPDiskInfo.StorageDeviceInfo.DeviceNumber; + + + foreach (var volumeGuid in Volume.EnumerateVolumes().ToArray()) { - var storageDeviceInfo = GetStorageDeviceInfoCore(false, deviceNumber, volumeGuid); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, volumeGuid); - if (null == storageDeviceInfo || storageDeviceInfo.DeviceNumber != newPDiskInfo.StorageDeviceInfo.DeviceNumber) + if (null == storageDeviceInfo || deviceNumber != storageDeviceInfo.DeviceNumber) continue; - + + AddToPartitionIndex(newPDiskInfo, storageDeviceInfo.PartitionNumber); AddToVolumeGuids(newPDiskInfo, volumeGuid); @@ -89,10 +94,10 @@ private static PhysicalDiskInfo PopulatePhysicalDisk(int deviceNumber, PhysicalD var driveName = Volume.GetVolumeDisplayName(volumeGuid); if (!Utils.IsNullOrWhiteSpace(driveName)) - AddToLogicalDrives(newPDiskInfo, driveName); } - + + return newPDiskInfo; } diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index 91b6a34bf..c259c3dea 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -104,16 +104,16 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de bool isDevice; var isDrive = false; var isVolume = false; - + var localDevicePath = isDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - - // StorageDeviceInfo contains the device number. - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath); + // The StorageDeviceInfo is always needed because it contains the device- and partition number. + + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, localDevicePath); if (null == storageDeviceInfo) return null; @@ -126,7 +126,7 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de if (null != physicalDiskInfo) { - if (!isDeviceNumber) + if (isDrive || isVolume) physicalDiskInfo.StorageDeviceInfo = storageDeviceInfo; if (null == physicalDiskInfo.StoragePartitionInfo) diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 309e41ded..50b7a7492 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -111,7 +111,7 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public string SerialNumber { get; internal set; } - /// The total size of the physical disk or 0 if the process is not elevated. + /// The total size of the physical disk or 0 if the process is not elevated or the device is a controller. public long TotalSize { get; internal set; } diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index 222904115..199cb81b8 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -61,7 +61,7 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis MediaType = (StorageMediaType) disk.Geometry.MediaType; - PartitionCount = (int)drive.PartitionCount; + PartitionCount = (int) drive.PartitionCount; MbrSignature = disk.PartitionInformation.MbrSignature; diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index 8c23914dd..1e1d6a989 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -21,6 +21,7 @@ using System; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; @@ -89,11 +90,12 @@ public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string dev internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int deviceNumber, string devicePath) { var isDeviceNumber = deviceNumber > -1; - bool isDrive; + var isDrive = false; bool isVolume; - bool isDevice; + var isDevice = false; - var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + var localDevicePath = isDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + //var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); @@ -103,15 +105,18 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, devicePath)) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, localDevicePath)) { storageDeviceInfo = null != safeBuffer ? new StorageDeviceInfo(safeBuffer.PtrToStructure()) : null; if (null != storageDeviceInfo) { - if (isDeviceNumber && storageDeviceInfo.DeviceNumber != deviceNumber) + // Get by deviceNumber. + + if (isDeviceNumber && deviceNumber != storageDeviceInfo.DeviceNumber) return null; + SetStorageDeviceInfoData(isElevated, isDevice, safeHandle, localDevicePath, storageDeviceInfo); } } @@ -173,11 +178,7 @@ private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, Saf } else if (!isDevice) - { - var diskSpaceInfo = Volume.GetDiskFreeSpace(localDevicePath, false); - - storageDeviceInfo.TotalSize = diskSpaceInfo.TotalNumberOfBytes; - } + storageDeviceInfo.TotalSize = new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; } } } diff --git a/AlphaFS/Filesystem/DiskSpaceInfo.cs b/AlphaFS/Filesystem/DiskSpaceInfo.cs index 1876f6ed3..f1a1025b7 100644 --- a/AlphaFS/Filesystem/DiskSpaceInfo.cs +++ b/AlphaFS/Filesystem/DiskSpaceInfo.cs @@ -48,8 +48,8 @@ public sealed class DiskSpaceInfo #region Constructors /// Initializes a DiskSpaceInfo instance. - /// 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 /// This is a Lazyloading object; call to populate all properties first before accessing. + /// 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 [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] public DiskSpaceInfo(string driveName) @@ -83,8 +83,11 @@ public DiskSpaceInfo(string driveName) [SecurityCritical] public DiskSpaceInfo(string driveName, bool? spaceInfoType, bool refresh, bool continueOnException) : this(driveName) { - if (spaceInfoType == null) - _initGetSpaceInfo = _initGetClusterInfo = true; + if (null == spaceInfoType) + { + _initGetSpaceInfo = true; + _initGetClusterInfo = true; + } else { From 5d3a71c0d70fada1eed1893338887a37ba1dc8e8 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 14 Jun 2018 19:26:06 +0200 Subject: [PATCH 107/133] Code improvement. --- AlphaFS/AlphaFS.csproj | 3 +- .../Local.EnumeratePhysicalDisks.cs | 37 +++++++++++++++---- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 4 +- ...icalDiskInfo.InitializePhysicalDiskInfo.cs | 2 +- .../Storage/Local.GetStorageDeviceInfo.cs | 15 +++----- .../Storage/Local.GetStoragePartitionInfo.cs | 20 ++++------ 6 files changed, 46 insertions(+), 35 deletions(-) diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index bc0b2bd0e..797cb6139 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -198,7 +198,6 @@ - @@ -744,7 +743,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 4871389ee..12b2a04e8 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -21,7 +21,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Linq; using System.Security; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; @@ -51,13 +50,35 @@ private static IEnumerable EnumeratePhysicalDisksCore(bool isE foreach (var deviceInfo in EnumerateDevicesCore(null, DeviceGuid.Disk, false)) { - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, deviceInfo.DevicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, deviceInfo.DevicePath); - if (null == storageDeviceInfo || isDeviceNumber && deviceNumber != storageDeviceInfo.DeviceNumber) + if (null == storageDeviceInfo) continue; - - var pDiskInfo = PhysicalDiskInfo.InitializePhysicalDiskInfo(isElevated, null, storageDeviceInfo, deviceInfo); + + var devicePath = deviceInfo.DevicePath; + + var pDiskInfo = new PhysicalDiskInfo + { + DevicePath = devicePath, + + DeviceDescription = deviceInfo.DeviceDescription, + + Name = deviceInfo.FriendlyName, + + PhysicalDeviceObjectName = deviceInfo.PhysicalDeviceObjectName, + + + StorageAdapterInfo = GetStorageAdapterInfoCore(devicePath, deviceInfo), + + StorageDeviceInfo = storageDeviceInfo, + + StoragePartitionInfo = GetStoragePartitionInfoCore(isElevated, devicePath) + }; + + + //if (pDiskInfo.StorageDeviceInfo.TotalSize == 0) + // pDiskInfo.StorageDeviceInfo.TotalSize = new DiskSpaceInfo(devicePath, false, true, true).TotalNumberOfBytes; yield return PopulatePhysicalDisk(isElevated, pDiskInfo); @@ -77,11 +98,11 @@ private static PhysicalDiskInfo PopulatePhysicalDisk(bool isElevated, PhysicalDi var deviceNumber = newPDiskInfo.StorageDeviceInfo.DeviceNumber; - foreach (var volumeGuid in Volume.EnumerateVolumes().ToArray()) + foreach (var volumeGuid in Volume.EnumerateVolumes()) { - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, volumeGuid); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, volumeGuid); - if (null == storageDeviceInfo || deviceNumber != storageDeviceInfo.DeviceNumber) + if (null == storageDeviceInfo) continue; diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index c259c3dea..dc940aa5c 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -113,7 +113,7 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de // The StorageDeviceInfo is always needed because it contains the device- and partition number. - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, localDevicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath); if (null == storageDeviceInfo) return null; @@ -130,7 +130,7 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de physicalDiskInfo.StorageDeviceInfo = storageDeviceInfo; if (null == physicalDiskInfo.StoragePartitionInfo) - physicalDiskInfo.StoragePartitionInfo = GetStoragePartitionInfoCore(isElevated, -1, localDevicePath); + physicalDiskInfo.StoragePartitionInfo = GetStoragePartitionInfoCore(isElevated, localDevicePath); } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs index f49abaa9c..c03abb9fe 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs @@ -71,7 +71,7 @@ internal static PhysicalDiskInfo InitializePhysicalDiskInfo(bool isElevated, str StorageDeviceInfo = null != storageDeviceInfo ? storageDeviceInfo : Local.GetStorageDeviceInfoCore(isElevated, -1, devicePath), - StoragePartitionInfo = Local.GetStoragePartitionInfo(isElevated, devicePath) + StoragePartitionInfo = Local.GetStoragePartitionInfoCore(isElevated, devicePath) }; } } diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index 1e1d6a989..8822f3e9f 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -79,7 +79,7 @@ public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string dev /// /// /// true indicates the current process is in an elevated state, allowing to retrieve more data. - /// Retrieve a instance by device number. + /// A number that indicates a physical disk on the Computer. /// /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ @@ -89,13 +89,11 @@ public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string dev [SecurityCritical] internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int deviceNumber, string devicePath) { - var isDeviceNumber = deviceNumber > -1; - var isDrive = false; + bool isDrive; bool isVolume; - var isDevice = false; + bool isDevice; - var localDevicePath = isDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); - //var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); @@ -111,12 +109,9 @@ internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int if (null != storageDeviceInfo) { - // Get by deviceNumber. - - if (isDeviceNumber && deviceNumber != storageDeviceInfo.DeviceNumber) + if (deviceNumber > -1 && deviceNumber != storageDeviceInfo.DeviceNumber) return null; - SetStorageDeviceInfoData(isElevated, isDevice, safeHandle, localDevicePath, storageDeviceInfo); } } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 99817fbf5..b00f9b1be 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -47,7 +47,7 @@ public static partial class Local [SecurityCritical] public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) { - return GetStoragePartitionInfoCore(ProcessContext.IsElevatedProcess, -1, devicePath); + return GetStoragePartitionInfoCore(ProcessContext.IsElevatedProcess, devicePath); } @@ -67,12 +67,10 @@ public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) [SecurityCritical] public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, string devicePath) { - return GetStoragePartitionInfoCore(isElevated, -1, devicePath); + return GetStoragePartitionInfoCore(isElevated, devicePath); } - - /// [AlphaFS] Retrieves information about the partitions on a disk and the features of each partition. /// Returns a instance that represent the partition info that is related to . /// @@ -80,22 +78,20 @@ public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, stri /// /// /// true indicates the current process is in an elevated state, allowing to retrieve more data. - /// Retrieve a instance by device number. /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// [SecurityCritical] - private static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, int deviceNumber, string devicePath) + internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, string devicePath) { - var isDeviceNumber = deviceNumber > -1; bool isDevice; var isDrive = false; bool isVolume; - var localDevicePath = isDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); From bc5a676f3254ce23a186a0d666d2dcc660059b4d Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 15 Jun 2018 13:10:52 +0200 Subject: [PATCH 108/133] Dynamic disk code improvement. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 14 ++-- ...tPhysicalDiskInfo_UsingLogicalDrivePath.cs | 21 ----- ...torageAdapterInfo_UsingLogicalDrivePath.cs | 7 +- ...ngDevicePathFromSystemDrive_ReturnsNull.cs | 27 ++++--- ...ragePartitionInfo_UsingLogicalDrivePath.cs | 13 ++-- ...InitializeInstanceUsingLogicalDrivePath.cs | 2 + ...tializeInstanceUsingPhysicalDriveNumber.cs | 13 +++- AlphaFS/Device/Local.InvokeDeviceIoData.cs | 15 +++- .../Device/Storage/Local.GetDeviceIoData.cs | 4 +- .../Storage/Local.GetStorageAdapterInfo.cs | 62 +++++++++++++-- .../Storage/Local.GetStoragePartitionInfo.cs | 77 ++++++++++++------- 11 files changed, 162 insertions(+), 93 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index 7c7183b47..a2747016d 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -35,7 +35,7 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() { UnitTestConstants.PrintUnitTestHeader(false); - var pDriveCount = 0; + var driveCount = 0; var physicalDrives = Alphaleonis.Win32.Filesystem.Volume.QueryAllDosDevices().Where(device => device.StartsWith("PhysicalDrive", StringComparison.OrdinalIgnoreCase)).ToArray(); @@ -49,7 +49,7 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() foreach (var pDisk in pDrives) { - Console.WriteLine("#{0:000}\tPhysical Disk: [{1}]", ++pDriveCount, pDisk.StorageDeviceInfo.DeviceNumber); + Console.WriteLine("#{0:000}\tPhysical Disk: [{1}]", driveCount, pDisk.StorageDeviceInfo.DeviceNumber); UnitTestConstants.Dump(pDisk); @@ -60,16 +60,12 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); - // Show all partition information. + Assert.AreEqual(driveCount, pDisk.StorageDeviceInfo.DeviceNumber); - if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) - foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) - UnitTestConstants.Dump(partition, true); + Assert.AreEqual(driveCount, pDisk.StoragePartitionInfo.DeviceNumber); - if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) - foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) - UnitTestConstants.Dump(partition, true); + driveCount++; Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs index 0e1a54535..e82e49342 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs @@ -35,7 +35,6 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePath_Success() { UnitTestConstants.PrintUnitTestHeader(false); - var gotDisk = false; var driveCount = 0; foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) @@ -97,27 +96,7 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePath_Success() Assert.AreEqual(pDisk.LogicalDrives.Contains(driveInfo.Name.TrimEnd('\\'), StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(driveInfo.Name)); - // Show all partition information. - - if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) - { - gotDisk = true; - - foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) - UnitTestConstants.Dump(partition, true); - } - - if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) - { - gotDisk = true; - - foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) - UnitTestConstants.Dump(partition, true); - } - Console.WriteLine(); - - Assert.IsTrue(gotDisk); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs index 194ad978d..fb4377466 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs @@ -40,7 +40,12 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingLogicalDrivePath_Success() foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { - // Works with System.IO.DriveType.CDRom. + // System.IO.DriveType.CDRom = null. + if (driveInfo.DriveType == System.IO.DriveType.CDRom) + { + Console.WriteLine("#{0:000}\tSkipped CDRom Drive: [{1}]\n", ++driveCount, driveInfo.Name); + continue; + } // System.UnauthorizedAccessException: (5) Access is denied. if (driveInfo.DriveType == System.IO.DriveType.Network) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs index 819b9f5fa..29a4732db 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs @@ -44,27 +44,26 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingDevicePathFromSystemDriv var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(devicePath); - + UnitTestConstants.Dump(storagePartitionInfo); + Assert.IsNotNull(storagePartitionInfo); - if (null != storagePartitionInfo) - { - // Show all partition information. - if (null != storagePartitionInfo.GptPartitionInfo) - { - foreach (var partition in storagePartitionInfo.GptPartitionInfo) - UnitTestConstants.Dump(partition, true); - } + // Show all partition information. + + if (null != storagePartitionInfo.GptPartitionInfo) + { + foreach (var partition in storagePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, true); + } - if (null != storagePartitionInfo.MbrPartitionInfo) - { - foreach (var partition in storagePartitionInfo.MbrPartitionInfo) - UnitTestConstants.Dump(partition, true); - } + if (null != storagePartitionInfo.MbrPartitionInfo) + { + foreach (var partition in storagePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, true); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs index fb504e0f4..bca65c0a6 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs @@ -43,28 +43,31 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingLogicalDrivePath_Success // System.IO.DriveType.CDRom = null. if (driveInfo.DriveType == System.IO.DriveType.CDRom) { - Console.WriteLine("#{0:000}\tSkipped CDRom drive: [{1}]\n", ++driveCount, driveInfo.Name); + Console.WriteLine("#{0:000}\tSkipped CDRom Drive: [{1}]\n", ++driveCount, driveInfo.Name); continue; } // System.UnauthorizedAccessException: (5) Access is denied. if (driveInfo.DriveType == System.IO.DriveType.Network) { - Console.WriteLine("#{0:000}\tSkipped Network drive: [{1}]\n", ++driveCount, driveInfo.Name); + Console.WriteLine("#{0:000}\tSkipped Network Drive: [{1}]\n", ++driveCount, driveInfo.Name); continue; } if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) { - Console.WriteLine("#{0:000}\tSkipped NoRootDirectory drive: [{1}]\n", ++driveCount, driveInfo.Name); + Console.WriteLine("#{0:000}\tSkipped NoRootDirectory Drive: [{1}]\n", ++driveCount, driveInfo.Name); continue; } var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(driveInfo.Name); - if (null == storagePartitionInfo) - Console.WriteLine(); + //if (null == storagePartitionInfo) + //{ + // Console.WriteLine("#{0:000}\tSkipped Logical Drive: [{1}]\n", ++driveCount, driveInfo.Name); + // continue; + //} Assert.IsNotNull(storagePartitionInfo); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs index 3a65f6c8e..d308b3677 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs @@ -34,6 +34,8 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Loc { UnitTestConstants.PrintUnitTestHeader(false); + Assert.Inconclusive("TODO"); + //var gotDisk = false; var driveCount = 0; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs index dfa4669b3..39c4b2360 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs @@ -35,8 +35,6 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingPhysicalDriveNumber_ { UnitTestConstants.PrintUnitTestHeader(false); - var driveCount = 0; - var physicalDisks = Alphaleonis.Win32.Filesystem.Volume.QueryAllDosDevices().Where(device => device.StartsWith("PhysicalDrive", StringComparison.OrdinalIgnoreCase)).ToArray(); Console.WriteLine("Found: [{0}] physical drives.\n", physicalDisks.Length); @@ -44,15 +42,22 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingPhysicalDriveNumber_ for (var physicalDiskNumber = 0; physicalDiskNumber < physicalDisks.Length; physicalDiskNumber++) { - Console.WriteLine("#{0:000}\tInput Physical Disk Number: [{1}]", ++driveCount, physicalDiskNumber); + Console.WriteLine("#{0:000}\tInput Physical Disk Number: [{1}]", physicalDiskNumber + 1, physicalDiskNumber); var pDisk = new Alphaleonis.Win32.Device.PhysicalDiskInfo(physicalDiskNumber); UnitTestConstants.Dump(pDisk); + UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); + + UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + + UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + + Assert.AreEqual(physicalDiskNumber, pDisk.StorageDeviceInfo.DeviceNumber); - Assert.AreEqual(0, pDisk.StorageDeviceInfo.PartitionNumber); + Assert.AreEqual(physicalDiskNumber, pDisk.StoragePartitionInfo.DeviceNumber); Console.WriteLine(); } diff --git a/AlphaFS/Device/Local.InvokeDeviceIoData.cs b/AlphaFS/Device/Local.InvokeDeviceIoData.cs index 2abab8f59..fd15d38f0 100644 --- a/AlphaFS/Device/Local.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Local.InvokeDeviceIoData.cs @@ -33,6 +33,17 @@ public static partial class Local [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string pathForException, int size = -1) + { + int unusedLastError; + + return InvokeDeviceIoData(safeHandle, controlCode, anyObject, pathForException, out unusedLastError, size); + } + + + /// Invokes InvokeIoControl with the specified input and specified size. + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] + [SecurityCritical] + private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string pathForException, out int lastError, int size = -1) { Utils.IsValidHandle(safeHandle); @@ -45,7 +56,7 @@ internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandl var success = NativeMethods.DeviceIoControlAnyObjectGetSet(safeHandle, controlCode, anyObject, (uint) bufferSize, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); - var lastError = Marshal.GetLastWin32Error(); + lastError = Marshal.GetLastWin32Error(); if (success) @@ -56,7 +67,7 @@ internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandl { if (lastError == Win32Errors.ERROR_NOT_READY || - // Dynamic disk. + // A logical drive path like \\.\D: fails on a dynamic disk. lastError == Win32Errors.ERROR_INVALID_FUNCTION || // Request device number from a DeviceGuid.Image device. diff --git a/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs b/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs index b7c1acbe1..efe4b21b9 100644 --- a/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs +++ b/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs @@ -31,7 +31,7 @@ public static partial class Local { [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] - internal static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) + private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) { Utils.IsValidHandle(safeHandle); @@ -55,7 +55,7 @@ internal static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle s { if (lastError == Win32Errors.ERROR_NOT_READY || - // Dynamic disk. + // A logical drive path like \\.\D: fails on a dynamic disk. lastError == Win32Errors.ERROR_INVALID_FUNCTION || // Request device number from a DeviceGuid.Image device. diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index 0f059727c..ee844152e 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -20,6 +20,7 @@ */ using System; +using System.Globalization; using System.Security; using Alphaleonis.Win32.Filesystem; @@ -60,11 +61,11 @@ public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) /// /// An initialized instance. [SecurityCritical] - internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath, DeviceInfo deviceInfo = null) + private static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath, DeviceInfo deviceInfo = null) { + bool isDevice; bool isDrive; bool isVolume; - bool isDevice; var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); @@ -72,23 +73,68 @@ internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath, localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); + // The StorageDeviceInfo is always needed because it contains the device- and partition number. + + var storageDeviceInfo = GetStorageDeviceInfoCore(false, -1, localDevicePath); + + //if (null == storageDeviceInfo) + // return null; + + + var deviceNumber = null != storageDeviceInfo ? storageDeviceInfo.DeviceNumber : -1; + var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery }; + var retry = false; - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, NativeMethods.FILE_ANY_ACCESS)) - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) + Retry: + + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, NativeMethods.FILE_ANY_ACCESS)) { - var storageAdapterInfo = null == safeBuffer ? null : new StorageAdapterInfo(safeBuffer.PtrToStructure()); + if (!retry && !isDevice) + { + var volDiskExtents = GetVolumeDiskExtents(safeHandle, localDevicePath); + + if (null == volDiskExtents || volDiskExtents.Value.NumberOfDiskExtents == 0) + return null; + + // Use the first disk extent. + deviceNumber = (int) volDiskExtents.Value.Extents[0].DiskNumber; + } + + + int lastError; + + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, out lastError, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) + { + if (null != safeBuffer) + { + var storageAdapterInfo = new StorageAdapterInfo(safeBuffer.PtrToStructure()); + + if (null != deviceInfo) + storageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; + + return storageAdapterInfo; + } + + + // A logical drive path like \\.\D: fails on a dynamic disk. + + if (!retry && lastError == Win32Errors.ERROR_INVALID_FUNCTION) + { + localDevicePath = Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture); - if (null != deviceInfo && null != storageAdapterInfo) - storageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; + retry = true; + goto Retry; + } - return storageAdapterInfo; + return null; + } } } } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index b00f9b1be..6ecc7f015 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -85,10 +85,10 @@ public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, stri /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// [SecurityCritical] - internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, string devicePath) + private static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, string devicePath) { bool isDevice; - var isDrive = false; + bool isDrive; bool isVolume; var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); @@ -97,50 +97,73 @@ internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + // The StorageDeviceInfo is always needed because it contains the device- and partition number. - return GetStoragePartitionInfoNative(safeHandle, localDevicePath); - } + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath); + if (null == storageDeviceInfo) + return null; - [SecurityCritical] - private static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeHandle, string pathForException) - { - var volDiskExtents = GetVolumeDiskExtents(safeHandle, pathForException); - if (null == volDiskExtents || volDiskExtents.Value.NumberOfDiskExtents == 0) - return null; + var deviceNumber = storageDeviceInfo.DeviceNumber; + + var retry = false; + + Retry: - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, pathForException, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) - if (null != safeBuffer) + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + { + if (!retry && !isDevice) { - var layout = safeBuffer.PtrToStructure(); + var volDiskExtents = GetVolumeDiskExtents(safeHandle, localDevicePath); + + if (null == volDiskExtents || volDiskExtents.Value.NumberOfDiskExtents == 0) + return null; - // Sanity check. - if (layout.PartitionCount <= 256) + // Use the first disk extent. + deviceNumber = (int) volDiskExtents.Value.Extents[0].DiskNumber; + } + + + int lastError; + + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, localDevicePath, out lastError, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) + if (null != safeBuffer) { - var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 + var layout = safeBuffer.PtrToStructure(); + + // Sanity check. + if (layout.PartitionCount <= 256) + { + var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 - var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 + var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 - var partitions = new NativeMethods.PARTITION_INFORMATION_EX[layout.PartitionCount]; + var partitions = new NativeMethods.PARTITION_INFORMATION_EX[layout.PartitionCount]; - for (var i = 0; i <= layout.PartitionCount - 1; i++) + for (var i = 0; i <= layout.PartitionCount - 1; i++) - partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); + partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); - var disk = GetDiskGeometryExNative(safeHandle, pathForException); + var disk = GetDiskGeometryExNative(safeHandle, localDevicePath); + return deviceNumber == -1 ? null : new StoragePartitionInfo(deviceNumber, disk, layout, partitions); + } + } - // Use the first disk extent. - var diskNumber = volDiskExtents.Value.Extents[0].DiskNumber; + // A logical drive path like \\.\D: fails on a dynamic disk. - return new StoragePartitionInfo((int) diskNumber, disk, layout, partitions); + else if (!retry && lastError == Win32Errors.ERROR_INVALID_FUNCTION) + { + localDevicePath = Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture); + + retry = true; + goto Retry; } - } + } return null; } @@ -191,7 +214,7 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHa if (lastError == Win32Errors.ERROR_NOT_READY || - // Dynamic disk. + // A logical drive path like \\.\D: fails on a dynamic disk. lastError == Win32Errors.ERROR_INVALID_FUNCTION || // Request device number from a DeviceGuid.Image device. From f61fa3945153086cfe43e1cdfcb90a948fb815be Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 15 Jun 2018 16:02:54 +0200 Subject: [PATCH 109/133] Dynamic disk code improvement. --- ...torageAdapterInfo_UsingLogicalDrivePath.cs | 7 +- ...viceInfo_UsingDevicePathFromSystemDrive.cs | 2 + ...viceInfo_UsingVolumePathFromSystemDrive.cs | 2 + ...ionInfo_UsingDevicePathFromSystemDrive.cs} | 8 +- ...ragePartitionInfo_UsingLogicalDrivePath.cs | 13 +-- ...tionInfo_UsingVolumePathFromSystemDrive.cs | 2 + AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 2 +- AlphaFS/AlphaFS.csproj | 6 +- AlphaFS/Device/Local.EnumerateDevices.cs | 8 +- .../{Storage => }/Local.GetDeviceIoData.cs | 13 ++- .../Local.GetVolumeDiskExtents.cs | 0 AlphaFS/Device/Local.InvokeDeviceIoData.cs | 16 +--- .../Local.EnumeratePhysicalDisks.cs | 12 ++- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 6 +- .../Storage/Local.GetStorageAdapterInfo.cs | 72 ++++------------- .../Storage/Local.GetStorageDeviceInfo.cs | 71 ++++++++++++----- .../Storage/Local.GetStoragePartitionInfo.cs | 79 +++++-------------- 17 files changed, 135 insertions(+), 184 deletions(-) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs => AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs} (96%) rename AlphaFS/Device/{Storage => }/Local.GetDeviceIoData.cs (82%) rename AlphaFS/Device/{Storage => }/Local.GetVolumeDiskExtents.cs (100%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs index fb4377466..194ad978d 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs @@ -40,12 +40,7 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingLogicalDrivePath_Success() foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { - // System.IO.DriveType.CDRom = null. - if (driveInfo.DriveType == System.IO.DriveType.CDRom) - { - Console.WriteLine("#{0:000}\tSkipped CDRom Drive: [{1}]\n", ++driveCount, driveInfo.Name); - continue; - } + // Works with System.IO.DriveType.CDRom. // System.UnauthorizedAccessException: (5) Access is denied. if (driveInfo.DriveType == System.IO.DriveType.Network) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs index d7cc5ef46..434ae3233 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs @@ -52,6 +52,8 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingDevicePathFromSystemDrive_S Assert.IsNotNull(storageDeviceInfo); + Assert.AreEqual(0, storageDeviceInfo.DeviceNumber); + Assert.IsNotNull(pDisk); Assert.AreEqual(pDisk.StorageDeviceInfo, storageDeviceInfo); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs index 5d32e5e64..923c0a1a3 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs @@ -52,6 +52,8 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingVolumePathFromSystemDrive_S Assert.IsNotNull(storageDeviceInfo); + Assert.AreEqual(0, storageDeviceInfo.DeviceNumber); + Assert.IsNotNull(pDisk); Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs similarity index 96% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs index 29a4732db..e12044a16 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_ReturnsNull() + public void AlphaFS_Device_GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -50,21 +50,19 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingDevicePathFromSystemDriv Assert.IsNotNull(storagePartitionInfo); + Assert.AreEqual(0, storagePartitionInfo.DeviceNumber); + // Show all partition information. if (null != storagePartitionInfo.GptPartitionInfo) - { foreach (var partition in storagePartitionInfo.GptPartitionInfo) UnitTestConstants.Dump(partition, true); - } if (null != storagePartitionInfo.MbrPartitionInfo) - { foreach (var partition in storagePartitionInfo.MbrPartitionInfo) UnitTestConstants.Dump(partition, true); - } } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs index bca65c0a6..eb8f83086 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs @@ -40,12 +40,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingLogicalDrivePath_Success foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { - // System.IO.DriveType.CDRom = null. - if (driveInfo.DriveType == System.IO.DriveType.CDRom) - { - Console.WriteLine("#{0:000}\tSkipped CDRom Drive: [{1}]\n", ++driveCount, driveInfo.Name); - continue; - } + // Works with System.IO.DriveType.CDRom. // System.UnauthorizedAccessException: (5) Access is denied. if (driveInfo.DriveType == System.IO.DriveType.Network) @@ -68,14 +63,14 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingLogicalDrivePath_Success // Console.WriteLine("#{0:000}\tSkipped Logical Drive: [{1}]\n", ++driveCount, driveInfo.Name); // continue; //} - - Assert.IsNotNull(storagePartitionInfo); - + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); UnitTestConstants.Dump(storagePartitionInfo); + Assert.IsNotNull(storagePartitionInfo); + // Show all partition information. if (null != storagePartitionInfo.GptPartitionInfo) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs index 9040ee435..7addd35e8 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs @@ -52,6 +52,8 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingVolumePathFromSystemDriv Assert.IsNotNull(storagePartitionInfo); + Assert.AreEqual(0, storagePartitionInfo.DeviceNumber); + Assert.IsNotNull(pDisk); Assert.AreEqual(pDisk.StorageDeviceInfo.DeviceNumber, storagePartitionInfo.DeviceNumber); diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 7b9e95ac3..14a073e64 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -148,7 +148,7 @@ - + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 797cb6139..f61aefc66 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -205,9 +205,9 @@ - + - + @@ -743,7 +743,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Local.EnumerateDevices.cs b/AlphaFS/Device/Local.EnumerateDevices.cs index 6971c73be..0c1ffa906 100644 --- a/AlphaFS/Device/Local.EnumerateDevices.cs +++ b/AlphaFS/Device/Local.EnumerateDevices.cs @@ -38,7 +38,7 @@ public static partial class Local [SecurityCritical] public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) { - return EnumerateDevicesCore(null, deviceGuid, true); + return EnumerateDevicesCore(null, new[] {deviceGuid}, true); } @@ -54,7 +54,7 @@ public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) [SecurityCritical] public static IEnumerable EnumerateDevices(string hostName, DeviceGuid deviceGuid) { - return EnumerateDevicesCore(hostName, deviceGuid, true); + return EnumerateDevicesCore(hostName, new[] {deviceGuid}, true); } @@ -69,7 +69,7 @@ public static IEnumerable EnumerateDevices(string hostName, DeviceGu /// One of the devices. /// true to retrieve all device properties. [SecurityCritical] - private static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid deviceGuid, bool getAllProperties) + private static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid[] deviceGuid, bool getAllProperties) { if (Utils.IsNullOrWhiteSpace(hostName)) hostName = Environment.MachineName; @@ -81,7 +81,7 @@ private static IEnumerable EnumerateDevicesCore(string hostName, Dev Utils.IsValidHandle(safeMachineHandle, lastError); - var classGuid = new Guid(Utils.GetEnumDescription(deviceGuid)); + var classGuid = new Guid(Utils.GetEnumDescription(deviceGuid[0])); // Start at the "Root" of the device tree of the specified machine. diff --git a/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs b/AlphaFS/Device/Local.GetDeviceIoData.cs similarity index 82% rename from AlphaFS/Device/Storage/Local.GetDeviceIoData.cs rename to AlphaFS/Device/Local.GetDeviceIoData.cs index efe4b21b9..2ee4b2fa1 100644 --- a/AlphaFS/Device/Storage/Local.GetDeviceIoData.cs +++ b/AlphaFS/Device/Local.GetDeviceIoData.cs @@ -33,9 +33,18 @@ public static partial class Local [SecurityCritical] private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) { - Utils.IsValidHandle(safeHandle); + int unusedLastError; + + return GetDeviceIoData(safeHandle, controlCode, pathForException, out unusedLastError, size); + } + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] + [SecurityCritical] + private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, out int lastError, int size = -1) + { + Utils.IsValidHandle(safeHandle); + var bufferSize = size > -1 ? size : Marshal.SizeOf(typeof(T)); while (true) @@ -44,7 +53,7 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); - var lastError = Marshal.GetLastWin32Error(); + lastError = Marshal.GetLastWin32Error(); if (success) diff --git a/AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs b/AlphaFS/Device/Local.GetVolumeDiskExtents.cs similarity index 100% rename from AlphaFS/Device/Storage/Local.GetVolumeDiskExtents.cs rename to AlphaFS/Device/Local.GetVolumeDiskExtents.cs diff --git a/AlphaFS/Device/Local.InvokeDeviceIoData.cs b/AlphaFS/Device/Local.InvokeDeviceIoData.cs index fd15d38f0..21c7e7ef7 100644 --- a/AlphaFS/Device/Local.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Local.InvokeDeviceIoData.cs @@ -33,21 +33,9 @@ public static partial class Local [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string pathForException, int size = -1) - { - int unusedLastError; - - return InvokeDeviceIoData(safeHandle, controlCode, anyObject, pathForException, out unusedLastError, size); - } - - - /// Invokes InvokeIoControl with the specified input and specified size. - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] - [SecurityCritical] - private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string pathForException, out int lastError, int size = -1) { Utils.IsValidHandle(safeHandle); - - + var bufferSize = size > -1 ? size : Marshal.SizeOf(anyObject); while (true) @@ -56,7 +44,7 @@ private static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle var success = NativeMethods.DeviceIoControlAnyObjectGetSet(safeHandle, controlCode, anyObject, (uint) bufferSize, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); - lastError = Marshal.GetLastWin32Error(); + var lastError = Marshal.GetLastWin32Error(); if (success) diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 12b2a04e8..a8aa9d6cb 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -48,9 +48,11 @@ private static IEnumerable EnumeratePhysicalDisksCore(bool isE { var isDeviceNumber = deviceNumber > -1; - foreach (var deviceInfo in EnumerateDevicesCore(null, DeviceGuid.Disk, false)) + foreach (var deviceInfo in EnumerateDevicesCore(null, new []{DeviceGuid.Disk}, false)) { - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, deviceInfo.DevicePath); + string unusedLocalDevicePath; + + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, deviceInfo.DevicePath, out unusedLocalDevicePath); if (null == storageDeviceInfo) continue; @@ -69,7 +71,7 @@ private static IEnumerable EnumeratePhysicalDisksCore(bool isE PhysicalDeviceObjectName = deviceInfo.PhysicalDeviceObjectName, - StorageAdapterInfo = GetStorageAdapterInfoCore(devicePath, deviceInfo), + StorageAdapterInfo = GetStorageAdapterInfoCore(isElevated, devicePath, deviceInfo.BusReportedDeviceDescription), StorageDeviceInfo = storageDeviceInfo, @@ -100,7 +102,9 @@ private static PhysicalDiskInfo PopulatePhysicalDisk(bool isElevated, PhysicalDi foreach (var volumeGuid in Volume.EnumerateVolumes()) { - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, volumeGuid); + string unusedLocalDevicePath; + + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, volumeGuid, out unusedLocalDevicePath); if (null == storageDeviceInfo) continue; diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index dc940aa5c..e229f6f66 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -109,11 +109,11 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); + + // The StorageDeviceInfo is always needed as it contains the device- and partition number. - // The StorageDeviceInfo is always needed because it contains the device- and partition number. - - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath, out localDevicePath); if (null == storageDeviceInfo) return null; diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index ee844152e..aa0a1aa82 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -20,9 +20,9 @@ */ using System; -using System.Globalization; using System.Security; using Alphaleonis.Win32.Filesystem; +using Alphaleonis.Win32.Security; namespace Alphaleonis.Win32.Device { @@ -43,7 +43,7 @@ public static partial class Local [SecurityCritical] public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) { - return GetStorageAdapterInfoCore(devicePath); + return GetStorageAdapterInfoCore(ProcessContext.IsElevatedProcess, devicePath); } @@ -53,86 +53,48 @@ public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) /// /// /// + /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// - /// An initialized instance. + /// The bus reported bus reported device description of the instance. [SecurityCritical] - private static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath, DeviceInfo deviceInfo = null) + private static StorageAdapterInfo GetStorageAdapterInfoCore(bool isElevated, string devicePath, string busReportedDeviceDescription = null) { - bool isDevice; - bool isDrive; - bool isVolume; - - var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); - - if (isDrive) - localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - - - // The StorageDeviceInfo is always needed because it contains the device- and partition number. - - var storageDeviceInfo = GetStorageDeviceInfoCore(false, -1, localDevicePath); - - //if (null == storageDeviceInfo) - // return null; - - - var deviceNumber = null != storageDeviceInfo ? storageDeviceInfo.DeviceNumber : -1; + var localDevicePath = devicePath; - var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY - { - PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, - QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery - }; + // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var retry = false; + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath, out localDevicePath); + if (null == storageDeviceInfo) + return null; - Retry: using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, NativeMethods.FILE_ANY_ACCESS)) { - if (!retry && !isDevice) + var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { - var volDiskExtents = GetVolumeDiskExtents(safeHandle, localDevicePath); + PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, + QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery + }; - if (null == volDiskExtents || volDiskExtents.Value.NumberOfDiskExtents == 0) - return null; - // Use the first disk extent. - deviceNumber = (int) volDiskExtents.Value.Extents[0].DiskNumber; - } - - - int lastError; - - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, out lastError, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) { if (null != safeBuffer) { var storageAdapterInfo = new StorageAdapterInfo(safeBuffer.PtrToStructure()); - if (null != deviceInfo) - storageAdapterInfo.BusReportedDeviceDescription = deviceInfo.BusReportedDeviceDescription; + if (!Utils.IsNullOrWhiteSpace(busReportedDeviceDescription)) + storageAdapterInfo.BusReportedDeviceDescription = busReportedDeviceDescription; return storageAdapterInfo; } - - // A logical drive path like \\.\D: fails on a dynamic disk. - - if (!retry && lastError == Win32Errors.ERROR_INVALID_FUNCTION) - { - localDevicePath = Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture); - - retry = true; - goto Retry; - } - return null; } } diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index 8822f3e9f..6df8d371e 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -48,7 +48,9 @@ public static partial class Local [SecurityCritical] public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) { - return GetStorageDeviceInfoCore(ProcessContext.IsElevatedProcess, -1, devicePath); + string unusedLocalDevicePath; + + return GetStorageDeviceInfoCore(ProcessContext.IsElevatedProcess, -1, devicePath, out unusedLocalDevicePath); } @@ -68,7 +70,9 @@ public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) [SecurityCritical] public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string devicePath) { - return GetStorageDeviceInfoCore(isElevated, -1, devicePath); + string unusedLocalDevicePath; + + return GetStorageDeviceInfoCore(isElevated, -1, devicePath, out unusedLocalDevicePath); } @@ -86,38 +90,63 @@ public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string dev /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// + /// The resolved local device path such as \\.\C: or \\.\PhysicalDrive0 [SecurityCritical] - internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int deviceNumber, string devicePath) + private static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int deviceNumber, string devicePath, out string localDevicePath) { bool isDrive; bool isVolume; bool isDevice; - var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - StorageDeviceInfo storageDeviceInfo; - + var retry = false; + Retry: + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, localDevicePath)) { - storageDeviceInfo = null != safeBuffer ? new StorageDeviceInfo(safeBuffer.PtrToStructure()) : null; + int lastError; - if (null != storageDeviceInfo) + using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, localDevicePath, out lastError)) { - if (deviceNumber > -1 && deviceNumber != storageDeviceInfo.DeviceNumber) - return null; + if (null != safeBuffer) + { + var storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure()); + + if (!retry && deviceNumber > -1 && deviceNumber != storageDeviceInfo.DeviceNumber) + return null; + + SetStorageDeviceInfoData(isElevated, isDevice, safeHandle, localDevicePath, storageDeviceInfo); + + return storageDeviceInfo; + } - SetStorageDeviceInfoData(isElevated, isDevice, safeHandle, localDevicePath, storageDeviceInfo); - } - } + // A logical drive path like \\.\D: fails on a dynamic disk. - return storageDeviceInfo; + if (!retry && !isDevice && lastError == Win32Errors.ERROR_INVALID_FUNCTION) + { + var volDiskExtents = GetVolumeDiskExtents(safeHandle, localDevicePath); + + if (null != volDiskExtents && volDiskExtents.Value.NumberOfDiskExtents > 0) + { + // Use the first disk extent. + deviceNumber = (int) volDiskExtents.Value.Extents[0].DiskNumber; + + localDevicePath = Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture); + + retry = true; + goto Retry; + } + } + } + + return null; + } } @@ -165,14 +194,20 @@ private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, Saf // Get disk total size. + var lastError = 0; + if (isElevated) { - using (var safeBuffer = GetDeviceIoData(safeHandle,NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, localDevicePath)) + using (var safeBuffer = GetDeviceIoData(safeHandle,NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, localDevicePath, out lastError)) storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; } - else if (!isDevice) + + // A logical drive path like \\.\D: fails on a dynamic disk. + + else if (!isDevice || lastError == Win32Errors.ERROR_INVALID_FUNCTION) + storageDeviceInfo.TotalSize = new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; } } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 6ecc7f015..3c4d9cc5a 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -87,85 +87,44 @@ public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, stri [SecurityCritical] private static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, string devicePath) { - bool isDevice; - bool isDrive; - bool isVolume; + var localDevicePath = devicePath; + + // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); - - if (isDrive) - localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - - - // The StorageDeviceInfo is always needed because it contains the device- and partition number. - - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath, out localDevicePath); if (null == storageDeviceInfo) return null; - - - var deviceNumber = storageDeviceInfo.DeviceNumber; - - var retry = false; - - - Retry: + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - { - if (!retry && !isDevice) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) + if (null != safeBuffer) { - var volDiskExtents = GetVolumeDiskExtents(safeHandle, localDevicePath); - - if (null == volDiskExtents || volDiskExtents.Value.NumberOfDiskExtents == 0) - return null; - - // Use the first disk extent. - deviceNumber = (int) volDiskExtents.Value.Extents[0].DiskNumber; - } + var layout = safeBuffer.PtrToStructure(); - - int lastError; - - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, localDevicePath, out lastError, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) - if (null != safeBuffer) + // Sanity check. + if (layout.PartitionCount <= 256) { - var layout = safeBuffer.PtrToStructure(); - - // Sanity check. - if (layout.PartitionCount <= 256) - { - var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 + var driveStructureSize = Marshal.SizeOf(typeof(NativeMethods.DRIVE_LAYOUT_INFORMATION_EX)); // 48 - var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 + var partitionStructureSize = Marshal.SizeOf(typeof(NativeMethods.PARTITION_INFORMATION_EX)); // 144 - var partitions = new NativeMethods.PARTITION_INFORMATION_EX[layout.PartitionCount]; + var partitions = new NativeMethods.PARTITION_INFORMATION_EX[layout.PartitionCount]; - for (var i = 0; i <= layout.PartitionCount - 1; i++) + for (var i = 0; i <= layout.PartitionCount - 1; i++) - partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); + partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); - var disk = GetDiskGeometryExNative(safeHandle, localDevicePath); + var disk = GetDiskGeometryExNative(safeHandle, localDevicePath); - return deviceNumber == -1 ? null : new StoragePartitionInfo(deviceNumber, disk, layout, partitions); - } + return new StoragePartitionInfo(storageDeviceInfo.DeviceNumber, disk, layout, partitions); } + } - // A logical drive path like \\.\D: fails on a dynamic disk. - - else if (!retry && lastError == Win32Errors.ERROR_INVALID_FUNCTION) - { - localDevicePath = Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture); - - retry = true; - goto Retry; - } - } - - return null; + return null; } From 5dcac6bc6803365a860c5015492e2621b2a34b42 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Fri, 15 Jun 2018 18:06:18 +0200 Subject: [PATCH 110/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 2 + ...tializeInstanceUsingPhysicalDriveNumber.cs | 2 + ...ngDirectory_UsingGlobalRootAsSourcePath.cs | 10 ++- ...xistingFile_UsingGlobalRootAsSourcePath.cs | 10 ++- AlphaFS/AlphaFS.csproj | 1 + AlphaFS/Device/Local.GetDeviceIoData.cs | 10 --- AlphaFS/Device/Native Other/IoControlCode.cs | 1 - .../Local.EnumeratePhysicalDisks.cs | 4 +- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 6 +- .../Storage/Device.StorageAdapterInfo.cs | 10 ++- .../Storage/Local.GetStorageAdapterInfo.cs | 2 +- .../Storage/Local.GetStorageDeviceInfo.cs | 80 +++-------------- .../Storage/Local.GetStoragePartitionInfo.cs | 3 +- .../Storage/Local.SetStorageDeviceInfoData.cs | 90 +++++++++++++++++++ 14 files changed, 135 insertions(+), 96 deletions(-) create mode 100644 AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index a2747016d..c9d934968 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -60,6 +60,8 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + Assert.AreEqual(driveCount, pDisk.StorageAdapterInfo.DeviceNumber); + Assert.AreEqual(driveCount, pDisk.StorageDeviceInfo.DeviceNumber); Assert.AreEqual(driveCount, pDisk.StoragePartitionInfo.DeviceNumber); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs index 39c4b2360..eb69c272d 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs @@ -55,6 +55,8 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingPhysicalDriveNumber_ UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + Assert.AreEqual(physicalDiskNumber, pDisk.StorageAdapterInfo.DeviceNumber); + Assert.AreEqual(physicalDiskNumber, pDisk.StorageDeviceInfo.DeviceNumber); Assert.AreEqual(physicalDiskNumber, pDisk.StoragePartitionInfo.DeviceNumber); diff --git a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ExistingDirectory_UsingGlobalRootAsSourcePath.cs b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ExistingDirectory_UsingGlobalRootAsSourcePath.cs index d2158033d..a5915cd2a 100644 --- a/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ExistingDirectory_UsingGlobalRootAsSourcePath.cs +++ b/AlphaFS.UnitTest/Directory Class/AlphaFS_Directory.Copy/AlphaFS_Directory.Copy_ExistingDirectory_UsingGlobalRootAsSourcePath.cs @@ -40,7 +40,7 @@ public void AlphaFS_Directory_Copy_ExistingDirectory_UsingGlobalRootAsSourcePath private void AlphaFS_Directory_Copy_ExistingDirectory_UsingGlobalRootAsSourcePath(bool isNetwork) { - var testOk = false; + var foundShadowCopy = false; using (var tempRoot = new TemporaryDirectory(isNetwork)) { @@ -50,7 +50,7 @@ private void AlphaFS_Directory_Copy_ExistingDirectory_UsingGlobalRootAsSourcePat foreach (var dosDevice in dosDevices) { - if (testOk) + if (foundShadowCopy) break; var shadowSource = Alphaleonis.Win32.Filesystem.Path.GlobalRootDevicePrefix + dosDevice; @@ -98,7 +98,7 @@ private void AlphaFS_Directory_Copy_ExistingDirectory_UsingGlobalRootAsSourcePat Assert.AreEqual(0, cmr.ErrorCode); - testOk = true; + foundShadowCopy = true; copyCount++; } @@ -107,7 +107,9 @@ private void AlphaFS_Directory_Copy_ExistingDirectory_UsingGlobalRootAsSourcePat Console.WriteLine(); - Assert.IsTrue(testOk); + + if (!foundShadowCopy) + UnitTestAssert.InconclusiveBecauseFileNotFound("No volume shadow copy found."); } } } diff --git a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ExistingFile_UsingGlobalRootAsSourcePath.cs b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ExistingFile_UsingGlobalRootAsSourcePath.cs index 0e1b75adb..be1faf529 100644 --- a/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ExistingFile_UsingGlobalRootAsSourcePath.cs +++ b/AlphaFS.UnitTest/File Class/File.Copy/AlphaFS_File.Copy_ExistingFile_UsingGlobalRootAsSourcePath.cs @@ -40,7 +40,7 @@ public void AlphaFS_File_Copy_ExistingFile_UsingGlobalRootAsSourcePath_LocalAndN private void AlphaFS_File_Copy_ExistingFile_UsingGlobalRootAsSourcePath(bool isNetwork) { - var testOk = false; + var foundShadowCopy = false; using (var tempRoot = new TemporaryDirectory(isNetwork)) { @@ -50,7 +50,7 @@ private void AlphaFS_File_Copy_ExistingFile_UsingGlobalRootAsSourcePath(bool isN foreach (var dosDevice in dosDevices) { - if (testOk) + if (foundShadowCopy) break; var shadowSource = Alphaleonis.Win32.Filesystem.Path.GlobalRootDevicePrefix + dosDevice; @@ -95,7 +95,7 @@ private void AlphaFS_File_Copy_ExistingFile_UsingGlobalRootAsSourcePath(bool isN Assert.AreEqual(0, cmr.ErrorCode); - testOk = true; + foundShadowCopy = true; copyCount++; } @@ -103,8 +103,10 @@ private void AlphaFS_File_Copy_ExistingFile_UsingGlobalRootAsSourcePath(bool isN } Console.WriteLine(); + - Assert.IsTrue(testOk); + if (!foundShadowCopy) + UnitTestAssert.InconclusiveBecauseFileNotFound("No volume shadow copy found."); } } } diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index f61aefc66..60eebf211 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -200,6 +200,7 @@ + diff --git a/AlphaFS/Device/Local.GetDeviceIoData.cs b/AlphaFS/Device/Local.GetDeviceIoData.cs index 2ee4b2fa1..4198a31d0 100644 --- a/AlphaFS/Device/Local.GetDeviceIoData.cs +++ b/AlphaFS/Device/Local.GetDeviceIoData.cs @@ -29,16 +29,6 @@ namespace Alphaleonis.Win32.Device { public static partial class Local { - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] - [SecurityCritical] - private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, int size = -1) - { - int unusedLastError; - - return GetDeviceIoData(safeHandle, controlCode, pathForException, out unusedLastError, size); - } - - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, out int lastError, int size = -1) diff --git a/AlphaFS/Device/Native Other/IoControlCode.cs b/AlphaFS/Device/Native Other/IoControlCode.cs index 5baa7ad65..8a21ae51e 100644 --- a/AlphaFS/Device/Native Other/IoControlCode.cs +++ b/AlphaFS/Device/Native Other/IoControlCode.cs @@ -28,7 +28,6 @@ internal static partial class NativeMethods { /// Enumerable values that enter into DeviceIoControl function as dwIoControlCode parameter /// Some of the code was taken from: http://blogs.msdn.com/b/codedebate/archive/2007/12/18/6797175.aspx - [Flags] internal enum IoControlCode : uint { /// Retrieves the physical location of a specified volume on one or more disks. diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index a8aa9d6cb..9abaf04b3 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -46,7 +46,7 @@ public static IEnumerable EnumeratePhysicalDisks() [SecurityCritical] private static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, int deviceNumber) { - var isDeviceNumber = deviceNumber > -1; + var getByDeviceNumber = deviceNumber > -1; foreach (var deviceInfo in EnumerateDevicesCore(null, new []{DeviceGuid.Disk}, false)) { @@ -86,7 +86,7 @@ private static IEnumerable EnumeratePhysicalDisksCore(bool isE // There can only be one. - if (isDeviceNumber) + if (getByDeviceNumber) break; } } diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index e229f6f66..e2d979c7b 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -100,12 +100,12 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(bool isElevated, string devic [SecurityCritical] internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int deviceNumber, string devicePath) { - var isDeviceNumber = deviceNumber > -1; + var getByDeviceNumber = deviceNumber > -1; bool isDevice; var isDrive = false; var isVolume = false; - var localDevicePath = isDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + var localDevicePath = getByDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); @@ -118,7 +118,7 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de if (null == storageDeviceInfo) return null; - if (!isDeviceNumber) + if (!getByDeviceNumber) deviceNumber = storageDeviceInfo.DeviceNumber; diff --git a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs index 3ad92aa78..0d9906335 100644 --- a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs @@ -37,11 +37,15 @@ public sealed class StorageAdapterInfo public StorageAdapterInfo() { BusType = StorageBusType.Unknown; + + DeviceNumber = -1; } - internal StorageAdapterInfo(NativeMethods.STORAGE_ADAPTER_DESCRIPTOR adapter) : this() + internal StorageAdapterInfo(int diskNumber, NativeMethods.STORAGE_ADAPTER_DESCRIPTOR adapter) : this() { + DeviceNumber = diskNumber; + BusType = (StorageBusType) adapter.BusType; AcceleratedTransfer = adapter.AcceleratedTransfer; @@ -91,6 +95,10 @@ internal StorageAdapterInfo(NativeMethods.STORAGE_ADAPTER_DESCRIPTOR adapter) : public bool CommandQueueing { get; private set; } + /// The device number connected to this storage adapter, starting at 0. + public int DeviceNumber { get; private set; } + + /// Specifies the maximum number of bytes the storage adapter can transfer in a single operation. public int MaximumTransferBytes { get; private set; } diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index aa0a1aa82..c4df01aee 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -87,7 +87,7 @@ private static StorageAdapterInfo GetStorageAdapterInfoCore(bool isElevated, str { if (null != safeBuffer) { - var storageAdapterInfo = new StorageAdapterInfo(safeBuffer.PtrToStructure()); + var storageAdapterInfo = new StorageAdapterInfo(storageDeviceInfo.DeviceNumber, safeBuffer.PtrToStructure()); if (!Utils.IsNullOrWhiteSpace(busReportedDeviceDescription)) storageAdapterInfo.BusReportedDeviceDescription = busReportedDeviceDescription; diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index 6df8d371e..acdece00d 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -20,13 +20,11 @@ */ using System; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; -using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { @@ -94,6 +92,7 @@ public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string dev [SecurityCritical] private static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int deviceNumber, string devicePath, out string localDevicePath) { + var getByDeviceNumber = deviceNumber > -1; bool isDrive; bool isVolume; bool isDevice; @@ -106,7 +105,7 @@ private static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int d var retry = false; Retry: - + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) { int lastError; @@ -117,7 +116,7 @@ private static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int d { var storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure()); - if (!retry && deviceNumber > -1 && deviceNumber != storageDeviceInfo.DeviceNumber) + if (getByDeviceNumber && deviceNumber != storageDeviceInfo.DeviceNumber) return null; SetStorageDeviceInfoData(isElevated, isDevice, safeHandle, localDevicePath, storageDeviceInfo); @@ -135,9 +134,16 @@ private static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int d if (null != volDiskExtents && volDiskExtents.Value.NumberOfDiskExtents > 0) { // Use the first disk extent. - deviceNumber = (int) volDiskExtents.Value.Extents[0].DiskNumber; + // TODO 2018-06-15: Handle multiple disk extents. + + var newDeviceNumber = (int) volDiskExtents.Value.Extents[0].DiskNumber; + + getByDeviceNumber = deviceNumber > -1; - localDevicePath = Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture); + if (getByDeviceNumber && deviceNumber != newDeviceNumber) + return null; + + localDevicePath = Path.PhysicalDrivePrefix + newDeviceNumber.ToString(CultureInfo.InvariantCulture); retry = true; goto Retry; @@ -148,67 +154,5 @@ private static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int d return null; } } - - - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - [SecurityCritical] - private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, SafeFileHandle safeHandle, string localDevicePath, StorageDeviceInfo storageDeviceInfo) - { - var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY - { - PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageDeviceProperty, - QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery - }; - - - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) - { - var deviceDescriptor = safeBuffer.PtrToStructure(); - - - storageDeviceInfo.BusType = (StorageBusType) deviceDescriptor.BusType; - - storageDeviceInfo.CommandQueueing = deviceDescriptor.CommandQueueing; - - storageDeviceInfo.ProductId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductIdOffset).Trim(); - - storageDeviceInfo.ProductRevision = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductRevisionOffset).Trim(); - - storageDeviceInfo.RemovableMedia = deviceDescriptor.RemovableMedia; - - storageDeviceInfo.SerialNumber = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(); - - storageDeviceInfo.VendorId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.VendorIdOffset).Trim(); - - - if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.ProductRevision) || storageDeviceInfo.ProductRevision.Length == 1) - storageDeviceInfo.ProductRevision = null; - - if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.SerialNumber) || storageDeviceInfo.SerialNumber.Length == 1) - storageDeviceInfo.SerialNumber = null; - - if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.VendorId) || storageDeviceInfo.VendorId.Length == 1) - storageDeviceInfo.VendorId = null; - } - - - // Get disk total size. - - var lastError = 0; - - if (isElevated) - { - using (var safeBuffer = GetDeviceIoData(safeHandle,NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, localDevicePath, out lastError)) - - storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; - } - - - // A logical drive path like \\.\D: fails on a dynamic disk. - - else if (!isDevice || lastError == Win32Errors.ERROR_INVALID_FUNCTION) - - storageDeviceInfo.TotalSize = new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; - } } } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 3c4d9cc5a..98df9360f 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -140,8 +140,7 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHa var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); - - + if (success) { var typeOf = typeof(NativeMethods.DISK_GEOMETRY); diff --git a/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs b/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs new file mode 100644 index 000000000..bd3380f4b --- /dev/null +++ b/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs @@ -0,0 +1,90 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; +using Alphaleonis.Win32.Filesystem; +using Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32.Device +{ + public static partial class Local + { + [SecurityCritical] + private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, SafeFileHandle safeHandle, string localDevicePath, StorageDeviceInfo storageDeviceInfo) + { + var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY + { + PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageDeviceProperty, + QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery + }; + + + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) + { + var deviceDescriptor = safeBuffer.PtrToStructure(); + + + storageDeviceInfo.BusType = (StorageBusType) deviceDescriptor.BusType; + + storageDeviceInfo.CommandQueueing = deviceDescriptor.CommandQueueing; + + storageDeviceInfo.ProductId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductIdOffset).Trim(); + + storageDeviceInfo.ProductRevision = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.ProductRevisionOffset).Trim(); + + storageDeviceInfo.RemovableMedia = deviceDescriptor.RemovableMedia; + + storageDeviceInfo.SerialNumber = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.SerialNumberOffset).Trim(); + + storageDeviceInfo.VendorId = safeBuffer.PtrToStringAnsi((int) deviceDescriptor.VendorIdOffset).Trim(); + + + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.ProductRevision) || storageDeviceInfo.ProductRevision.Length == 1) + storageDeviceInfo.ProductRevision = null; + + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.SerialNumber) || storageDeviceInfo.SerialNumber.Length == 1) + storageDeviceInfo.SerialNumber = null; + + if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.VendorId) || storageDeviceInfo.VendorId.Length == 1) + storageDeviceInfo.VendorId = null; + } + + + // Get disk total size. + + var lastError = 0; + + if (isElevated) + { + using (var safeBuffer = GetDeviceIoData(safeHandle,NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, localDevicePath, out lastError)) + + storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; + } + + + // A logical drive path like \\.\D: fails on a dynamic disk. + + else if (!isDevice || lastError == Win32Errors.ERROR_INVALID_FUNCTION) + + storageDeviceInfo.TotalSize = new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; + } + } +} From 1a883d875dec89af0da1dad46e2b668455732696 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 16 Jun 2018 13:05:42 +0200 Subject: [PATCH 111/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 14 ++- AlphaFS/Device/Local.EnumerateDevices.cs | 102 +++++++++++++----- .../Local.EnumeratePhysicalDisks.cs | 10 +- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 2 +- .../PhysicalDiskInfo_Properties.cs | 2 +- .../Storage/Local.GetStorageDeviceInfo.cs | 24 ++--- AlphaFS/Network/Host Class/Host.GetUncName.cs | 10 +- 7 files changed, 106 insertions(+), 58 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index c9d934968..87a9da1e7 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -39,12 +39,16 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() var physicalDrives = Alphaleonis.Win32.Filesystem.Volume.QueryAllDosDevices().Where(device => device.StartsWith("PhysicalDrive", StringComparison.OrdinalIgnoreCase)).ToArray(); + var cdRoms = Alphaleonis.Win32.Filesystem.Volume.QueryAllDosDevices().Where(device => device.StartsWith("CdRom", StringComparison.OrdinalIgnoreCase)).ToArray(); + var pDrives = Alphaleonis.Win32.Device.Local.EnumeratePhysicalDisks().OrderBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber).ThenBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.PartitionNumber).ToArray(); + var allPhysicalDrives = physicalDrives.Length + cdRoms.Length; + - Console.WriteLine("Found: [{0}] physical drives.\n", physicalDrives.Length); + Console.WriteLine("Found: [{0}] physical drives.\n", allPhysicalDrives); - Assert.AreEqual(physicalDrives.Length, pDrives.Length); + Assert.AreEqual(allPhysicalDrives, pDrives.Length); foreach (var pDisk in pDrives) @@ -60,11 +64,11 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); - Assert.AreEqual(driveCount, pDisk.StorageAdapterInfo.DeviceNumber); + //Assert.AreEqual(driveCount, pDisk.StorageAdapterInfo.DeviceNumber); - Assert.AreEqual(driveCount, pDisk.StorageDeviceInfo.DeviceNumber); + //Assert.AreEqual(driveCount, pDisk.StorageDeviceInfo.DeviceNumber); - Assert.AreEqual(driveCount, pDisk.StoragePartitionInfo.DeviceNumber); + //Assert.AreEqual(driveCount, pDisk.StoragePartitionInfo.DeviceNumber); driveCount++; diff --git a/AlphaFS/Device/Local.EnumerateDevices.cs b/AlphaFS/Device/Local.EnumerateDevices.cs index 0c1ffa906..824e58e12 100644 --- a/AlphaFS/Device/Local.EnumerateDevices.cs +++ b/AlphaFS/Device/Local.EnumerateDevices.cs @@ -34,7 +34,7 @@ public static partial class Local { /// [AlphaFS] Enumerates all available devices on the local host. /// Returns an collection from the local host. - /// One of the devices. + /// One of the device guids. [SecurityCritical] public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) { @@ -42,6 +42,16 @@ public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) } + /// [AlphaFS] Enumerates all available devices of type on the local host. + /// Returns an collection from the local host. + /// One or more device guids. + [SecurityCritical] + public static IEnumerable EnumerateDevices(DeviceGuid[] deviceGuid) + { + return EnumerateDevicesCore(null, deviceGuid, true); + } + + /// [AlphaFS] Enumerates all available devices of type on the local or remote host. /// Returns an collection for the specified . /// @@ -50,7 +60,7 @@ public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) /// http://msdn.microsoft.com/en-us/library/windows/hardware/ff537948%28v=vs.85%29.aspx /// /// The name of the local or remote host on which the device resides. null refers to the local host. - /// One of the devices. + /// One of the device guids. [SecurityCritical] public static IEnumerable EnumerateDevices(string hostName, DeviceGuid deviceGuid) { @@ -66,30 +76,71 @@ public static IEnumerable EnumerateDevices(string hostName, DeviceGu /// http://msdn.microsoft.com/en-us/library/windows/hardware/ff537948%28v=vs.85%29.aspx /// /// The name of the local or remote host on which the device resides. null refers to the local host. - /// One of the devices. + /// One or more device guids. + [SecurityCritical] + public static IEnumerable EnumerateDevices(string hostName, DeviceGuid[] deviceGuid) + { + return EnumerateDevicesCore(hostName, deviceGuid, true); + } + + + /// [AlphaFS] Enumerates all available devices of type on the local or remote host. + /// Returns an collection for the specified . + /// + /// 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 + /// + /// The name of the local or remote host on which the device resides. null refers to the local host. + /// One or more device guids. /// true to retrieve all device properties. [SecurityCritical] private static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid[] deviceGuid, bool getAllProperties) { - if (Utils.IsNullOrWhiteSpace(hostName)) - hostName = Environment.MachineName; + SafeCmConnectMachineHandle safeMachineHandle = null; - SafeCmConnectMachineHandle safeMachineHandle; + var isRemote = !Utils.IsNullOrWhiteSpace(hostName); + if (isRemote) + { + var lastError = NativeMethods.CM_Connect_Machine(Host.GetUncName(hostName), out safeMachineHandle); - var lastError = NativeMethods.CM_Connect_Machine(Host.GetUncName(hostName), out safeMachineHandle); + Utils.IsValidHandle(safeMachineHandle, lastError); + } - Utils.IsValidHandle(safeMachineHandle, lastError); - - var classGuid = new Guid(Utils.GetEnumDescription(deviceGuid[0])); + using (safeMachineHandle) + foreach (var guid in deviceGuid) + foreach (var device in EnumerateDevicesNative(safeMachineHandle, hostName, guid, getAllProperties)) + yield return device; + } + + /// [AlphaFS] Enumerates all available devices of type on the local or remote host. + /// Returns an collection for the specified . + /// + /// 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 + /// + /// An initialized instance. + /// The name of the local or remote host on which the device resides. null refers to the local host. + /// One of the devices. + /// true to retrieve all device properties. + [SecurityCritical] + private static IEnumerable EnumerateDevicesNative(SafeCmConnectMachineHandle safeMachineHandle, string hostName, DeviceGuid deviceGuid, bool getAllProperties) + { + var nonNullHostName = !Utils.IsNullOrWhiteSpace(hostName) ? hostName : Environment.MachineName; + + var classGuid = new Guid(Utils.GetEnumDescription(deviceGuid)); - // Start at the "Root" of the device tree of the specified machine. - using (safeMachineHandle) + // Start at the "Root" of the device tree. + using (var safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref classGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_PRESENT | NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_DEVICEINTERFACE, IntPtr.Zero, hostName, IntPtr.Zero)) { - Utils.IsValidHandle(safeHandle, Marshal.GetLastWin32Error()); + var lastError = Marshal.GetLastWin32Error(); + + Utils.IsValidHandle(safeHandle, lastError); uint memberInterfaceIndex = 0; var interfaceStructSize = (uint) Marshal.SizeOf(typeof(NativeMethods.SP_DEVICE_INTERFACE_DATA)); @@ -97,7 +148,7 @@ private static IEnumerable EnumerateDevicesCore(string hostName, Dev // Start enumerating device interfaces. - + while (true) { var interfaceData = new NativeMethods.SP_DEVICE_INTERFACE_DATA {cbSize = interfaceStructSize}; @@ -109,7 +160,7 @@ private static IEnumerable EnumerateDevicesCore(string hostName, Dev if (!success) { if (lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_NO_MORE_ITEMS) - NativeError.ThrowException(lastError, hostName); + NativeError.ThrowException(lastError, nonNullHostName); break; } @@ -119,12 +170,12 @@ private static IEnumerable EnumerateDevicesCore(string hostName, Dev var diData = new NativeMethods.SP_DEVINFO_DATA {cbSize = dataStructSize}; - var deviceInfo = new DeviceInfo(hostName) {DevicePath = GetDeviceInterfaceDetail(safeHandle, ref interfaceData, ref diData).DevicePath}; + var deviceInfo = new DeviceInfo(nonNullHostName) {DevicePath = GetDeviceInterfaceDetail(safeHandle, ref interfaceData, ref diData).DevicePath}; if (getAllProperties) { - deviceInfo.InstanceId = GetDeviceInstanceId(safeMachineHandle, hostName, diData); + deviceInfo.InstanceId = GetDeviceInstanceId(safeMachineHandle, nonNullHostName, diData); SetDeviceProperties(safeHandle, deviceInfo, diData); } @@ -142,14 +193,14 @@ private static IEnumerable EnumerateDevicesCore(string hostName, Dev [SecurityCritical] - private static string GetDeviceInstanceId(SafeCmConnectMachineHandle safeMachineHandle, string hostName, NativeMethods.SP_DEVINFO_DATA diData) + private static string GetDeviceInstanceId(SafeCmConnectMachineHandle safeMachineHandle, string hostNameForException, 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); + NativeError.ThrowException(lastError, hostNameForException); using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Filesystem.NativeMethods.DefaultFileBufferSize / 8)) // 512 @@ -157,7 +208,7 @@ private static string GetDeviceInstanceId(SafeCmConnectMachineHandle safeMachine lastError = NativeMethods.CM_Get_Device_ID_Ex(diData.DevInst, safeBuffer, (uint) safeBuffer.Capacity, 0, safeMachineHandle); if (lastError != Win32Errors.CR_SUCCESS) - NativeError.ThrowException(lastError, hostName); + NativeError.ThrowException(lastError, hostNameForException); // Device InstanceID, such as: "USB\VID_8087&PID_0A2B\5&2EDA7E1E&0&7", "SCSI\DISK&VEN_SANDISK&PROD_X400\4&288ED25&0&000200", ... @@ -253,12 +304,6 @@ private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo device { SetMinimalDeviceProperties(safeHandle, deviceInfo, infoData); - //var guid = GetDeviceBusTypeGuid(safeHandle, infoData); - - //if (null != guid) - // deviceInfo.BusTypeGuid = (Guid)guid; - - deviceInfo.CompatibleIds = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.CompatibleIds); @@ -281,11 +326,10 @@ private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo device [SecurityCritical] private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) { - deviceInfo.BusReportedDeviceDescription = GetDeviceBusReportedDeviceDescription(safeHandle, infoData); - - deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.BaseContainerId)); + deviceInfo.BusReportedDeviceDescription = GetDeviceBusReportedDeviceDescription(safeHandle, infoData); + deviceInfo.ClassGuid = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.ClassGuid)); deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.Class); diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 9abaf04b3..e86c598b2 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Device { public static partial class Local { - /// [AlphaFS] Enumerates the physical disks on the Computer, populated with volume-/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CDRom's) on the Computer, populated with volume-/logical drive information. /// Returns an collection that represents the physical disks on the Computer. [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() @@ -39,7 +39,7 @@ public static IEnumerable EnumeratePhysicalDisks() } - /// [AlphaFS] Enumerates the physical disks on the Computer, populated with volume-/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CDRom's) on the Computer, populated with volume-/logical drive information. /// Returns an collection that represents the physical disks on the Computer. /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// Retrieve a instance by device number. @@ -48,10 +48,12 @@ private static IEnumerable EnumeratePhysicalDisksCore(bool isE { var getByDeviceNumber = deviceNumber > -1; - foreach (var deviceInfo in EnumerateDevicesCore(null, new []{DeviceGuid.Disk}, false)) + foreach (var deviceInfo in EnumerateDevicesCore(null, new []{DeviceGuid.Disk, DeviceGuid.CDRom}, false)) { string unusedLocalDevicePath; + // The StorageDeviceInfo is always needed as it contains the device- and partition number. + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, deviceInfo.DevicePath, out unusedLocalDevicePath); if (null == storageDeviceInfo) @@ -104,6 +106,8 @@ private static PhysicalDiskInfo PopulatePhysicalDisk(bool isElevated, PhysicalDi { string unusedLocalDevicePath; + // The StorageDeviceInfo is always needed as it contains the device- and partition number. + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, volumeGuid, out unusedLocalDevicePath); if (null == storageDeviceInfo) diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index e2d979c7b..609aeb8fb 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -113,7 +113,7 @@ internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int de // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath, out localDevicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, localDevicePath, out localDevicePath); if (null == storageDeviceInfo) return null; diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs index b2739b139..e9ca2048a 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs @@ -64,7 +64,7 @@ public sealed partial class PhysicalDiskInfo public StorageDeviceInfo StorageDeviceInfo { get; internal set; } - /// The storage device partitiion information. + /// The storage device partition information. public StoragePartitionInfo StoragePartitionInfo { get; internal set; } diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index acdece00d..c9892f76b 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -131,23 +131,19 @@ private static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int d { var volDiskExtents = GetVolumeDiskExtents(safeHandle, localDevicePath); - if (null != volDiskExtents && volDiskExtents.Value.NumberOfDiskExtents > 0) - { - // Use the first disk extent. - // TODO 2018-06-15: Handle multiple disk extents. + if (volDiskExtents.HasValue) + foreach (var extent in volDiskExtents.Value.Extents) + { + var newDeviceNumber = (int) extent.DiskNumber; - var newDeviceNumber = (int) volDiskExtents.Value.Extents[0].DiskNumber; + if (getByDeviceNumber && deviceNumber != newDeviceNumber) + continue; - getByDeviceNumber = deviceNumber > -1; + localDevicePath = Path.PhysicalDrivePrefix + newDeviceNumber.ToString(CultureInfo.InvariantCulture); - if (getByDeviceNumber && deviceNumber != newDeviceNumber) - return null; - - localDevicePath = Path.PhysicalDrivePrefix + newDeviceNumber.ToString(CultureInfo.InvariantCulture); - - retry = true; - goto Retry; - } + retry = true; + goto Retry; + } } } diff --git a/AlphaFS/Network/Host Class/Host.GetUncName.cs b/AlphaFS/Network/Host Class/Host.GetUncName.cs index 425e3c9ce..a953169db 100644 --- a/AlphaFS/Network/Host Class/Host.GetUncName.cs +++ b/AlphaFS/Network/Host Class/Host.GetUncName.cs @@ -30,8 +30,8 @@ namespace Alphaleonis.Win32.Network /// Provides static methods to retrieve network resource information from a local- or remote host. public static partial class Host { - /// Return the host name in UNC format, for example: \\hostname - /// The unc name. + /// Return the local host name in UNC format, for example: \\hostname + /// The UNC host name. [SecurityCritical] public static string GetUncName() { @@ -40,13 +40,13 @@ public static string GetUncName() /// Return the host name in UNC format, for example: \\hostname - /// Name of the computer. + /// The name of the local or remote Computer. /// The unc name. [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] [SecurityCritical] - public static string GetUncName(string computerName) + public static string GetUncName(string hostName) { - return Utils.IsNullOrWhiteSpace(computerName) ? GetUncName() : (computerName.StartsWith(Path.UncPrefix, StringComparison.Ordinal) ? computerName.Trim() : Path.UncPrefix + computerName.Trim()); + return Utils.IsNullOrWhiteSpace(hostName) ? GetUncName() : (hostName.StartsWith(Path.UncPrefix, StringComparison.Ordinal) ? hostName.Trim() : Path.UncPrefix + hostName.Trim()); } } } From a8db1144b41d82f6bafaeb0c1fed575d472ac1f3 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 16 Jun 2018 14:02:02 +0200 Subject: [PATCH 112/133] Code improvement, work in progress. --- ...InitializeInstanceUsingLogicalDrivePath.cs | 80 ++----------------- .../FilesystemHelper.OpenPhysicalDrive.cs | 4 +- .../Local.EnumeratePhysicalDisks.cs | 4 +- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 8 +- .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 54 ++++++++++++- .../Storage/Local.GetStorageAdapterInfo.cs | 4 +- .../Storage/Local.GetStoragePartitionInfo.cs | 7 +- .../Link Stream/BackupFileStream.cs | 2 +- AlphaFS/Security/ProcessContext.cs | 2 +- 9 files changed, 73 insertions(+), 92 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs index d308b3677..468ad84c4 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs @@ -34,9 +34,6 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Loc { UnitTestConstants.PrintUnitTestHeader(false); - Assert.Inconclusive("TODO"); - - //var gotDisk = false; var driveCount = 0; foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) @@ -52,85 +49,24 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Loc Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); - //var pDisk = new Alphaleonis.Win32.Device.PhysicalDiskInfo(driveInfo.Name); + var pDisk = new Alphaleonis.Win32.Device.PhysicalDiskInfo(driveInfo.Name); - //UnitTestConstants.Dump(pDisk); + UnitTestConstants.Dump(pDisk); + UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); - //// Works with System.IO.DriveType.CDRom. + UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); - //if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) - //{ - // Console.WriteLine("#{0:000}\tSkipped NoRootDirectory drive: [{1}]\n", ++driveCount, driveInfo.Name); - // continue; - //} + var physicalDiskNumber = pDisk.StorageDeviceInfo.DeviceNumber; + Assert.AreEqual(physicalDiskNumber, pDisk.StorageAdapterInfo.DeviceNumber); - //var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(driveInfo.Name); - - - //Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]\t\t{2}", ++driveCount, driveInfo.Name, pDisk.StorageAdapterInfo.ToString()); - - //UnitTestConstants.Dump(pDisk); - - //UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); - - //UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); - - //UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); - - - //Assert.IsNotNull(pDisk); - - //Assert.IsNotNull(pDisk.LogicalDrives); - - //Assert.IsNotNull(pDisk.VolumeGuids); - - - //if (pDisk.StorageDeviceInfo.PartitionNumber == -1) - // Assert.IsNull(pDisk.StoragePartitionInfo); - //else - // Assert.IsNotNull(pDisk.StoragePartitionInfo); - - - //// For CDRom, the PartitionNumber is always -1. - - //if (pDisk.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) - //{ - // Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - // Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.CDRom, pDisk.StorageDeviceInfo.DeviceType); - //} - - //else - // Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - - - //Assert.AreEqual(pDisk.LogicalDrives.Contains(driveInfo.Name.TrimEnd('\\'), StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(driveInfo.Name)); - - - //// Show all partition information. - - //if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) - //{ - // gotDisk = true; - - // foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) - // UnitTestConstants.Dump(partition, true); - //} - - //if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) - //{ - // gotDisk = true; - - // foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) - // UnitTestConstants.Dump(partition, true); - //} + Assert.AreEqual(physicalDiskNumber, pDisk.StoragePartitionInfo.DeviceNumber); Console.WriteLine(); - - //Assert.IsTrue(gotDisk); } } } diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs index dc400cabe..6ff790ae2 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs @@ -31,7 +31,7 @@ namespace Alphaleonis.Win32.Device { internal static partial class FileSystemHelper { - /// Opens a physical disk or logical drive/volume for read access. + /// Opens a physical disk or volume/logical drive for read access. /// Returns a instance. /// /// @@ -43,7 +43,7 @@ internal static partial class FileSystemHelper /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// - /// If no elevated access is needed to access the physical disk or logical drive/volume, specify 0 for this parameter. + /// If no elevated access is needed to access the physical disk or volume/logical drive, specify 0 for this parameter. [SecurityCritical] public static SafeFileHandle OpenPhysicalDisk(string devicePath, FileSystemRights fileSystemRights) { diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index e86c598b2..9e70d4abc 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32.Device { public static partial class Local { - /// [AlphaFS] Enumerates the physical disks (including CDRom's) on the Computer, populated with volume-/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CD/DVD devices) on the Computer, populated with volume-/logical drive information. /// Returns an collection that represents the physical disks on the Computer. [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() @@ -39,7 +39,7 @@ public static IEnumerable EnumeratePhysicalDisks() } - /// [AlphaFS] Enumerates the physical disks (including CDRom's) on the Computer, populated with volume-/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CD/DVD devices) on the Computer, populated with volume-/logical drive information. /// Returns an collection that represents the physical disks on the Computer. /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// Retrieve a instance by device number. diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs index 609aeb8fb..333ea541e 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs @@ -34,7 +34,7 @@ public static partial class Local /// Returns a instance that represents the physical disk on the Computer or null if the device can not be retrieved. /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every logical drive/volume on the Computer as each call queries all physical disks, associated volumes and logical drives. + /// Do not call this method for every volume/logical drive on the Computer as each call queries all physical disks, associated volumes and logical drives. /// Instead, use method and property or . /// /// @@ -57,7 +57,7 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) /// Returns a instance that represents the physical disk on the Computer or null if the device can not be retrieved. /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every logical drive/volume on the Computer as each call queries all physical disks, associated volumes and logical drives. + /// Do not call this method for every volume/logical drive on the Computer as each call queries all physical disks, associated volumes and logical drives. /// Instead, use method and property or . /// /// @@ -77,13 +77,11 @@ public static PhysicalDiskInfo GetPhysicalDiskInfo(bool isElevated, string devic } - - /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . /// Returns a instance that represents the physical disk on the Computer or null if the device can not be retrieved. /// /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every logical drive/volume on the Computer as each call queries all physical disks, associated volumes and logical drives. + /// Do not call this method for every volume/logical drive on the Computer as each call queries all physical disks, associated volumes and logical drives. /// Instead, use method and property or . /// /// diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index 4a137f332..3b8eadb0e 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -20,7 +20,6 @@ */ using System; -using System.Diagnostics.CodeAnalysis; using System.Security; using Alphaleonis.Win32.Filesystem; @@ -31,6 +30,17 @@ namespace Alphaleonis.Win32.Device [SecurityCritical] public sealed partial class PhysicalDiskInfo { + #region Fields + + private int _deviceNumber = -1; + private string _localDevicePath; + private bool _isDrive; + private bool _isVolume; + private bool _isDevice; + + #endregion // Fields + + #region Constructors /// [AlphaFS] Initializes an empty PhysicalDiskInfo instance. @@ -46,14 +56,52 @@ public PhysicalDiskInfo(int deviceNumber) if (deviceNumber < 0) throw new ArgumentOutOfRangeException("deviceNumber"); - var pDiskInfo = Local.GetPhysicalDiskInfoCore(Security.ProcessContext.IsElevatedProcess, deviceNumber, null); + _deviceNumber = deviceNumber; + + + var pDiskInfo = Local.GetPhysicalDiskInfoCore(Security.ProcessContext.IsElevatedProcess, _deviceNumber, null); + + if (null != pDiskInfo) + { + SetDevicePath(pDiskInfo.DevicePath); + + Utils.CopyTo(pDiskInfo, this); + } + } + + + /// [AlphaFS] Initializes a PhysicalDiskInfo instance from a physical disk number such as: 0, 1, ... + /// + /// Do not create and instance for every volume/logical drive on the Computer as each call queries all physical disks, associated volumes and logical drives. + /// Instead, use method and property or . + /// + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// + public PhysicalDiskInfo(string devicePath) + { + SetDevicePath(devicePath); + + var pDiskInfo = Local.GetPhysicalDiskInfoCore(Security.ProcessContext.IsElevatedProcess, -1, _localDevicePath); if (null != pDiskInfo) Utils.CopyTo(pDiskInfo, this); } #endregion // Constructors - + + + private void SetDevicePath(string devicePath) + { + _localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out _isDrive, out _isVolume, out _isDevice); + + if (_isDrive) + _localDevicePath = FileSystemHelper.GetLocalDevicePath(_localDevicePath); + } + /// Returns the "FriendlyName" of the physical disk. /// Returns a string that represents this instance. diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index c4df01aee..e4ab20c8e 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -43,7 +43,7 @@ public static partial class Local [SecurityCritical] public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) { - return GetStorageAdapterInfoCore(ProcessContext.IsElevatedProcess, devicePath); + return GetStorageAdapterInfoCore(ProcessContext.IsElevatedProcess, devicePath, null); } @@ -62,7 +62,7 @@ public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) /// /// The bus reported bus reported device description of the instance. [SecurityCritical] - private static StorageAdapterInfo GetStorageAdapterInfoCore(bool isElevated, string devicePath, string busReportedDeviceDescription = null) + private static StorageAdapterInfo GetStorageAdapterInfoCore(bool isElevated, string devicePath, string busReportedDeviceDescription) { var localDevicePath = devicePath; diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 98df9360f..e051d8685 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -20,7 +20,6 @@ */ using System; -using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; @@ -137,7 +136,7 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHa while (true) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) { - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); @@ -154,9 +153,9 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHa }; - var offset = (uint)sizeOf + sizeof(long); // 32 + var offset = (uint) sizeOf + sizeof(long); // 32 - diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure((int)offset); + diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure((int) offset); //// Intermittently throws: System.AccessViolationException: Attempted to read or write protected memory. diff --git a/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs b/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs index 5ace05b25..7af3ca7df 100644 --- a/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs +++ b/AlphaFS/Filesystem/Link Stream/BackupFileStream.cs @@ -404,7 +404,7 @@ public void Write(byte[] buffer, int offset, int count, bool processSecurity) uint bytesWritten; - var success = NativeMethods.BackupWrite(SafeFileHandle, safeBuffer, (uint)safeBuffer.Capacity, out bytesWritten, false, processSecurity, ref _context); + var success = NativeMethods.BackupWrite(SafeFileHandle, safeBuffer, (uint) safeBuffer.Capacity, out bytesWritten, false, processSecurity, ref _context); var lastError = Marshal.GetLastWin32Error(); if (!success) diff --git a/AlphaFS/Security/ProcessContext.cs b/AlphaFS/Security/ProcessContext.cs index 717340aac..64436e056 100644 --- a/AlphaFS/Security/ProcessContext.cs +++ b/AlphaFS/Security/ProcessContext.cs @@ -133,7 +133,7 @@ private static NativeMethods.TOKEN_ELEVATION_TYPE GetProcessElevationType() 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); + success = NativeMethods.GetTokenInformation(tokenHandle, NativeMethods.TOKEN_INFORMATION_CLASS.TokenElevationType, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned); lastError = Marshal.GetLastWin32Error(); From e948a2189d386483b3023513d7c2818502b9d54f Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sat, 16 Jun 2018 22:49:41 +0200 Subject: [PATCH 113/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 20 +-- ...DiskInfo_UsingDevicePathFromSystemDrive.cs | 44 +++--- ...tPhysicalDiskInfo_UsingLogicalDrivePath.cs | 30 ++-- ...DiskInfo_UsingVolumePathFromSystemDrive.cs | 44 +++--- ...pterInfo_UsingDevicePathFromSystemDrive.cs | 8 +- ...pterInfo_UsingVolumePathFromSystemDrive.cs | 6 +- ...viceInfo_UsingDevicePathFromSystemDrive.cs | 8 +- ...viceInfo_UsingVolumePathFromSystemDrive.cs | 8 +- ...tionInfo_UsingDevicePathFromSystemDrive.cs | 2 +- ...tionInfo_UsingVolumePathFromSystemDrive.cs | 8 +- ...InitializeInstanceUsingLogicalDrivePath.cs | 22 ++- ...tializeInstanceUsingPhysicalDriveNumber.cs | 16 +- AlphaFS/AlphaFS.csproj | 3 +- AlphaFS/Device/Local.EnumerateDevices.cs | 2 +- .../Local.EnumeratePhysicalDisks.cs | 8 +- .../PhysicalDisk/Local.GetPhysicalDiskInfo.cs | 138 ------------------ .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 127 +++++++++++++--- .../Storage/Local.GetStorageAdapterInfo.cs | 2 +- .../Storage/Local.GetStorageDeviceInfo.cs | 11 +- .../Storage/Local.GetStoragePartitionInfo.cs | 2 +- 20 files changed, 236 insertions(+), 273 deletions(-) delete mode 100644 AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index 87a9da1e7..8e5e3fbf8 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -41,7 +41,7 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() var cdRoms = Alphaleonis.Win32.Filesystem.Volume.QueryAllDosDevices().Where(device => device.StartsWith("CdRom", StringComparison.OrdinalIgnoreCase)).ToArray(); - var pDrives = Alphaleonis.Win32.Device.Local.EnumeratePhysicalDisks().OrderBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber).ThenBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.PartitionNumber).ToArray(); + var pDrives = Alphaleonis.Win32.Device.Local.EnumeratePhysicalDisks().OrderBy(pDiskInfo => pDiskInfo.StorageDeviceInfo.DeviceNumber).ThenByDescending(pDiskInfo => pDiskInfo.StorageDeviceInfo.PartitionNumber).ToArray(); var allPhysicalDrives = physicalDrives.Length + cdRoms.Length; @@ -51,24 +51,24 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() Assert.AreEqual(allPhysicalDrives, pDrives.Length); - foreach (var pDisk in pDrives) + foreach (var pDiskInfo in pDrives) { - Console.WriteLine("#{0:000}\tPhysical Disk: [{1}]", driveCount, pDisk.StorageDeviceInfo.DeviceNumber); + Console.WriteLine("#{0:000}\tPhysical Disk: [{1}]", driveCount, pDiskInfo.StorageDeviceInfo.DeviceNumber); - UnitTestConstants.Dump(pDisk); + UnitTestConstants.Dump(pDiskInfo); - UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); + UnitTestConstants.Dump(pDiskInfo.StorageAdapterInfo, true); - UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); - UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - //Assert.AreEqual(driveCount, pDisk.StorageAdapterInfo.DeviceNumber); + //Assert.AreEqual(driveCount, pDiskInfo.StorageAdapterInfo.DeviceNumber); - //Assert.AreEqual(driveCount, pDisk.StorageDeviceInfo.DeviceNumber); + //Assert.AreEqual(driveCount, pDiskInfo.StorageDeviceInfo.DeviceNumber); - //Assert.AreEqual(driveCount, pDisk.StoragePartitionInfo.DeviceNumber); + //Assert.AreEqual(driveCount, pDiskInfo.StoragePartitionInfo.DeviceNumber); driveCount++; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs index 65d230319..8b2c8ded6 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs @@ -41,48 +41,54 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive_Su var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; + var devicePath = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceDrive).DevicePath; Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); + var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(devicePath); - UnitTestConstants.Dump(pDisk); + UnitTestConstants.Dump(pDiskInfo); - UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); + UnitTestConstants.Dump(pDiskInfo.StorageAdapterInfo, true); - UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); - UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); Console.WriteLine(); - Assert.IsNotNull(pDisk); + Assert.IsNotNull(pDiskInfo); - Assert.IsNotNull(pDisk.LogicalDrives); + Assert.IsNotNull(pDiskInfo.LogicalDrives); - Assert.IsNotNull(pDisk.VolumeGuids); + Assert.IsNotNull(pDiskInfo.VolumeGuids); - Assert.AreEqual(pDisk.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceDrive)); - Assert.AreEqual(pDisk.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceVolume)); + Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); + + Assert.IsTrue(pDiskInfo.ContainsVolume(sourceDrive)); + + + Assert.IsTrue(pDiskInfo.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase)); + + Assert.IsTrue(pDiskInfo.ContainsVolume(sourceVolume)); + + + Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); // Show all partition information. - if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) - { - foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) + if (null != pDiskInfo.StoragePartitionInfo && null != pDiskInfo.StoragePartitionInfo.GptPartitionInfo) + foreach (var partition in pDiskInfo.StoragePartitionInfo.GptPartitionInfo) UnitTestConstants.Dump(partition, true); - } - if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) - { - foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) + if (null != pDiskInfo.StoragePartitionInfo && null != pDiskInfo.StoragePartitionInfo.MbrPartitionInfo) + foreach (var partition in pDiskInfo.StoragePartitionInfo.MbrPartitionInfo) UnitTestConstants.Dump(partition, true); - } + Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs index e82e49342..38e02204f 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs @@ -58,42 +58,42 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePath_Success() Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(driveInfo.Name); + var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(driveInfo.Name); - UnitTestConstants.Dump(pDisk); + UnitTestConstants.Dump(pDiskInfo); - UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); + UnitTestConstants.Dump(pDiskInfo.StorageAdapterInfo, true); - UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); - UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - Assert.IsNotNull(pDisk); + Assert.IsNotNull(pDiskInfo); - Assert.IsNotNull(pDisk.LogicalDrives); + Assert.IsNotNull(pDiskInfo.LogicalDrives); - Assert.IsNotNull(pDisk.VolumeGuids); + Assert.IsNotNull(pDiskInfo.VolumeGuids); - if (pDisk.StorageDeviceInfo.PartitionNumber > 0) - Assert.IsNotNull(pDisk.StoragePartitionInfo); + if (pDiskInfo.StorageDeviceInfo.PartitionNumber > 0) + Assert.IsNotNull(pDiskInfo.StoragePartitionInfo); // For CDRom, the PartitionNumber is always -1. - if (pDisk.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) + if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) { - Assert.AreEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.CDRom, pDisk.StorageDeviceInfo.DeviceType); + Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.CDRom, pDiskInfo.StorageDeviceInfo.DeviceType); } else - Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(pDisk.LogicalDrives.Contains(driveInfo.Name.TrimEnd('\\'), StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(driveInfo.Name)); + Assert.AreEqual(pDiskInfo.LogicalDrives.Contains(driveInfo.Name.TrimEnd('\\'), StringComparer.OrdinalIgnoreCase), pDiskInfo.ContainsVolume(driveInfo.Name)); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs index 2fdaf3223..4c11be04a 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs @@ -44,44 +44,48 @@ public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Su Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]", ++volumeCount, sourceVolume); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); + var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceVolume); - UnitTestConstants.Dump(pDisk); + UnitTestConstants.Dump(pDiskInfo); - UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); + UnitTestConstants.Dump(pDiskInfo.StorageAdapterInfo, true); - UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); - UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); - + UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); + Console.WriteLine(); + + + Assert.IsNotNull(pDiskInfo); - Assert.IsNotNull(pDisk); + Assert.IsNotNull(pDiskInfo.LogicalDrives); - Assert.IsNotNull(pDisk.LogicalDrives); + Assert.IsNotNull(pDiskInfo.VolumeGuids); - Assert.IsNotNull(pDisk.VolumeGuids); - Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); - Assert.AreEqual(pDisk.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceDrive)); + Assert.IsTrue(pDiskInfo.ContainsVolume(sourceDrive)); + + + Assert.IsTrue(pDiskInfo.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase)); + + Assert.IsTrue(pDiskInfo.ContainsVolume(sourceVolume)); + - Assert.AreEqual(pDisk.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase), pDisk.ContainsVolume(sourceVolume)); + Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); // Show all partition information. - if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.GptPartitionInfo) - { - foreach (var partition in pDisk.StoragePartitionInfo.GptPartitionInfo) + if (null != pDiskInfo.StoragePartitionInfo && null != pDiskInfo.StoragePartitionInfo.GptPartitionInfo) + foreach (var partition in pDiskInfo.StoragePartitionInfo.GptPartitionInfo) UnitTestConstants.Dump(partition, true); - } - if (null != pDisk.StoragePartitionInfo && null != pDisk.StoragePartitionInfo.MbrPartitionInfo) - { - foreach (var partition in pDisk.StoragePartitionInfo.MbrPartitionInfo) + if (null != pDiskInfo.StoragePartitionInfo && null != pDiskInfo.StoragePartitionInfo.MbrPartitionInfo) + foreach (var partition in pDiskInfo.StoragePartitionInfo.MbrPartitionInfo) UnitTestConstants.Dump(partition, true); - } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs index 454b88185..7937371b2 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs @@ -37,12 +37,12 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingDevicePathFromSystemDrive_ var deviceCount = 0; var sourceDrive = UnitTestConstants.SysDrive; - var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; + var devicePath = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceDrive).DevicePath; Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); + var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(devicePath); var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(devicePath); @@ -51,9 +51,9 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingDevicePathFromSystemDrive_ Assert.IsNotNull(storageAdapterInfo); - Assert.IsNotNull(pDisk); + Assert.IsNotNull(pDiskInfo); - Assert.AreEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); + Assert.AreEqual(pDiskInfo.StorageAdapterInfo, storageAdapterInfo); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs index c041426cc..08f4ebf3e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs @@ -43,7 +43,7 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingVolumePathFromSystemDrive_ Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]", ++volumeCount, sourceVolume); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); + var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceVolume); var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(sourceVolume); @@ -52,9 +52,9 @@ public void AlphaFS_Device_GetStorageAdapterInfo_UsingVolumePathFromSystemDrive_ Assert.IsNotNull(storageAdapterInfo); - Assert.IsNotNull(pDisk); + Assert.IsNotNull(pDiskInfo); - Assert.AreEqual(pDisk.StorageAdapterInfo, storageAdapterInfo); + Assert.AreEqual(pDiskInfo.StorageAdapterInfo, storageAdapterInfo); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs index 434ae3233..8fc3760c3 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs @@ -38,12 +38,12 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingDevicePathFromSystemDrive_S var sourceDrive = UnitTestConstants.SysDrive; - var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; + var devicePath = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceDrive).DevicePath; Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(devicePath); + var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(devicePath); var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(devicePath); @@ -54,9 +54,9 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingDevicePathFromSystemDrive_S Assert.AreEqual(0, storageDeviceInfo.DeviceNumber); - Assert.IsNotNull(pDisk); + Assert.IsNotNull(pDiskInfo); - Assert.AreEqual(pDisk.StorageDeviceInfo, storageDeviceInfo); + Assert.AreEqual(pDiskInfo.StorageDeviceInfo, storageDeviceInfo); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs index 923c0a1a3..7136d733e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs @@ -43,7 +43,7 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingVolumePathFromSystemDrive_S Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]", ++volumeCount, sourceVolume); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); + var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceVolume); var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(sourceVolume); @@ -54,11 +54,11 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingVolumePathFromSystemDrive_S Assert.AreEqual(0, storageDeviceInfo.DeviceNumber); - Assert.IsNotNull(pDisk); + Assert.IsNotNull(pDiskInfo); - Assert.AreNotEqual(-1, pDisk.StorageDeviceInfo.PartitionNumber); + Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(pDisk.StorageDeviceInfo, storageDeviceInfo); + Assert.AreEqual(pDiskInfo.StorageDeviceInfo, storageDeviceInfo); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs index e12044a16..bd6616919 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs @@ -38,7 +38,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingDevicePathFromSystemDriv var sourceDrive = UnitTestConstants.SysDrive; - var devicePath = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceDrive).DevicePath; + var devicePath = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceDrive).DevicePath; Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs index 7addd35e8..e2f10cfc7 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs @@ -43,7 +43,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingVolumePathFromSystemDriv Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]", ++volumeCount, sourceVolume); - var pDisk = Alphaleonis.Win32.Device.Local.GetPhysicalDiskInfo(sourceVolume); + var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceVolume); var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(sourceVolume); @@ -54,11 +54,11 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingVolumePathFromSystemDriv Assert.AreEqual(0, storagePartitionInfo.DeviceNumber); - Assert.IsNotNull(pDisk); + Assert.IsNotNull(pDiskInfo); - Assert.AreEqual(pDisk.StorageDeviceInfo.DeviceNumber, storagePartitionInfo.DeviceNumber); + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.DeviceNumber, storagePartitionInfo.DeviceNumber); - Assert.AreEqual(pDisk.StoragePartitionInfo, storagePartitionInfo); + Assert.AreEqual(pDiskInfo.StoragePartitionInfo, storagePartitionInfo); // Show all partition information. diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs index 468ad84c4..5ef80a2a4 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs @@ -35,6 +35,7 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Loc UnitTestConstants.PrintUnitTestHeader(false); var driveCount = 0; + Alphaleonis.Win32.Device.PhysicalDiskInfo prevDiskInfo = null; foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { @@ -49,22 +50,27 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Loc Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); - var pDisk = new Alphaleonis.Win32.Device.PhysicalDiskInfo(driveInfo.Name); + var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(driveInfo.Name); - UnitTestConstants.Dump(pDisk); + Assert.AreNotEqual(prevDiskInfo, pDiskInfo); - UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); + prevDiskInfo = pDiskInfo; - UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); - UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + UnitTestConstants.Dump(pDiskInfo); + UnitTestConstants.Dump(pDiskInfo.StorageAdapterInfo, true); - var physicalDiskNumber = pDisk.StorageDeviceInfo.DeviceNumber; + UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); - Assert.AreEqual(physicalDiskNumber, pDisk.StorageAdapterInfo.DeviceNumber); + UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - Assert.AreEqual(physicalDiskNumber, pDisk.StoragePartitionInfo.DeviceNumber); + + var physicalDiskNumber = pDiskInfo.StorageDeviceInfo.DeviceNumber; + + Assert.AreEqual(physicalDiskNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); + + Assert.AreEqual(physicalDiskNumber, pDiskInfo.StoragePartitionInfo.DeviceNumber); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs index eb69c272d..e46c6cbeb 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs @@ -44,22 +44,22 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingPhysicalDriveNumber_ { Console.WriteLine("#{0:000}\tInput Physical Disk Number: [{1}]", physicalDiskNumber + 1, physicalDiskNumber); - var pDisk = new Alphaleonis.Win32.Device.PhysicalDiskInfo(physicalDiskNumber); + var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(physicalDiskNumber); - UnitTestConstants.Dump(pDisk); + UnitTestConstants.Dump(pDiskInfo); - UnitTestConstants.Dump(pDisk.StorageAdapterInfo, true); + UnitTestConstants.Dump(pDiskInfo.StorageAdapterInfo, true); - UnitTestConstants.Dump(pDisk.StorageDeviceInfo, true); + UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); - UnitTestConstants.Dump(pDisk.StoragePartitionInfo, true); + UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - Assert.AreEqual(physicalDiskNumber, pDisk.StorageAdapterInfo.DeviceNumber); + Assert.AreEqual(physicalDiskNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); - Assert.AreEqual(physicalDiskNumber, pDisk.StorageDeviceInfo.DeviceNumber); + Assert.AreEqual(physicalDiskNumber, pDiskInfo.StorageDeviceInfo.DeviceNumber); - Assert.AreEqual(physicalDiskNumber, pDisk.StoragePartitionInfo.DeviceNumber); + Assert.AreEqual(physicalDiskNumber, pDiskInfo.StoragePartitionInfo.DeviceNumber); Console.WriteLine(); } diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 60eebf211..1bbf1d2a2 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -215,7 +215,6 @@ - @@ -744,7 +743,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Local.EnumerateDevices.cs b/AlphaFS/Device/Local.EnumerateDevices.cs index 824e58e12..7f36170ac 100644 --- a/AlphaFS/Device/Local.EnumerateDevices.cs +++ b/AlphaFS/Device/Local.EnumerateDevices.cs @@ -95,7 +95,7 @@ public static IEnumerable EnumerateDevices(string hostName, DeviceGu /// One or more device guids. /// true to retrieve all device properties. [SecurityCritical] - private static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid[] deviceGuid, bool getAllProperties) + internal static IEnumerable EnumerateDevicesCore(string hostName, DeviceGuid[] deviceGuid, bool getAllProperties) { SafeCmConnectMachineHandle safeMachineHandle = null; diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 9e70d4abc..448180492 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -38,13 +38,13 @@ public static IEnumerable EnumeratePhysicalDisks() return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess, -1); } - + /// [AlphaFS] Enumerates the physical disks (including CD/DVD devices) on the Computer, populated with volume-/logical drive information. /// Returns an collection that represents the physical disks on the Computer. /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// Retrieve a instance by device number. [SecurityCritical] - private static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, int deviceNumber) + internal static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, int deviceNumber) { var getByDeviceNumber = deviceNumber > -1; @@ -74,7 +74,7 @@ private static IEnumerable EnumeratePhysicalDisksCore(bool isE StorageAdapterInfo = GetStorageAdapterInfoCore(isElevated, devicePath, deviceInfo.BusReportedDeviceDescription), - + StorageDeviceInfo = storageDeviceInfo, StoragePartitionInfo = GetStoragePartitionInfoCore(isElevated, devicePath) @@ -95,7 +95,7 @@ private static IEnumerable EnumeratePhysicalDisksCore(bool isE /// Retrieves volumes and logical drives that belong to - private static PhysicalDiskInfo PopulatePhysicalDisk(bool isElevated, PhysicalDiskInfo pDiskInfo) + internal static PhysicalDiskInfo PopulatePhysicalDisk(bool isElevated, PhysicalDiskInfo pDiskInfo) { var newPDiskInfo = Utils.CopyFrom(pDiskInfo); diff --git a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs deleted file mode 100644 index 333ea541e..000000000 --- a/AlphaFS/Device/PhysicalDisk/Local.GetPhysicalDiskInfo.cs +++ /dev/null @@ -1,138 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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.Linq; -using System.Security; -using Alphaleonis.Win32.Filesystem; -using Alphaleonis.Win32.Security; - -namespace Alphaleonis.Win32.Device -{ - public static partial class Local - { - /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . - /// Returns a instance that represents the physical disk on the Computer or null if the device can not be retrieved. - /// - /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every volume/logical drive on the Computer as each call queries all physical disks, associated volumes and logical drives. - /// Instead, use method and property or . - /// - /// - /// - /// - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// - [SecurityCritical] - public static PhysicalDiskInfo GetPhysicalDiskInfo(string devicePath) - { - return GetPhysicalDiskInfoCore(ProcessContext.IsElevatedProcess, -1, devicePath); - } - - - /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . - /// Returns a instance that represents the physical disk on the Computer or null if the device can not be retrieved. - /// - /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every volume/logical drive on the Computer as each call queries all physical disks, associated volumes and logical drives. - /// Instead, use method and property or . - /// - /// - /// - /// - /// true indicates the current process is in an elevated state, allowing to retrieve more data. - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// - [SecurityCritical] - public static PhysicalDiskInfo GetPhysicalDiskInfo(bool isElevated, string devicePath) - { - return GetPhysicalDiskInfoCore(isElevated, -1, devicePath); - } - - - /// [AlphaFS] Retrieves the physical disk that is related to the logical drive name, volume or . - /// Returns a instance that represents the physical disk on the Computer or null if the device can not be retrieved. - /// - /// Most properties of the returned and instances are meaningless unless this method is called from an elevated state. - /// Do not call this method for every volume/logical drive on the Computer as each call queries all physical disks, associated volumes and logical drives. - /// Instead, use method and property or . - /// - /// - /// - /// - /// true indicates the current process is in an elevated state, allowing to retrieve more data. - /// Retrieve a instance by device number. - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// - [SecurityCritical] - internal static PhysicalDiskInfo GetPhysicalDiskInfoCore(bool isElevated, int deviceNumber, string devicePath) - { - var getByDeviceNumber = deviceNumber > -1; - bool isDevice; - var isDrive = false; - var isVolume = false; - - var localDevicePath = getByDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); - - if (isDrive) - localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - - - // The StorageDeviceInfo is always needed as it contains the device- and partition number. - - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, localDevicePath, out localDevicePath); - - if (null == storageDeviceInfo) - return null; - - if (!getByDeviceNumber) - deviceNumber = storageDeviceInfo.DeviceNumber; - - - var physicalDiskInfo = EnumeratePhysicalDisksCore(isElevated, deviceNumber).FirstOrDefault(); - - if (null != physicalDiskInfo) - { - if (isDrive || isVolume) - physicalDiskInfo.StorageDeviceInfo = storageDeviceInfo; - - if (null == physicalDiskInfo.StoragePartitionInfo) - physicalDiskInfo.StoragePartitionInfo = GetStoragePartitionInfoCore(isElevated, localDevicePath); - } - - - return physicalDiskInfo; - } - } -} diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index 3b8eadb0e..bb4d112a7 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -20,6 +20,8 @@ */ using System; +using System.Globalization; +using System.Linq; using System.Security; using Alphaleonis.Win32.Filesystem; @@ -34,6 +36,7 @@ public sealed partial class PhysicalDiskInfo private int _deviceNumber = -1; private string _localDevicePath; + private bool _isElevated; private bool _isDrive; private bool _isVolume; private bool _isDevice; @@ -56,24 +59,14 @@ public PhysicalDiskInfo(int deviceNumber) if (deviceNumber < 0) throw new ArgumentOutOfRangeException("deviceNumber"); - _deviceNumber = deviceNumber; - - - var pDiskInfo = Local.GetPhysicalDiskInfoCore(Security.ProcessContext.IsElevatedProcess, _deviceNumber, null); - - if (null != pDiskInfo) - { - SetDevicePath(pDiskInfo.DevicePath); - - Utils.CopyTo(pDiskInfo, this); - } + CreatePhysicalDiskInfoInstance(Security.ProcessContext.IsElevatedProcess, deviceNumber, null); } /// [AlphaFS] Initializes a PhysicalDiskInfo instance from a physical disk number such as: 0, 1, ... /// /// Do not create and instance for every volume/logical drive on the Computer as each call queries all physical disks, associated volumes and logical drives. - /// Instead, use method and property or . + /// Instead, use method and property or . /// /// /// A disk path such as: \\.\PhysicalDrive0 @@ -83,26 +76,109 @@ public PhysicalDiskInfo(int deviceNumber) /// public PhysicalDiskInfo(string devicePath) { - SetDevicePath(devicePath); - - var pDiskInfo = Local.GetPhysicalDiskInfoCore(Security.ProcessContext.IsElevatedProcess, -1, _localDevicePath); - - if (null != pDiskInfo) - Utils.CopyTo(pDiskInfo, this); + CreatePhysicalDiskInfoInstance(Security.ProcessContext.IsElevatedProcess, -1, devicePath); } #endregion // Constructors - private void SetDevicePath(string devicePath) + [SecurityCritical] + private void CreatePhysicalDiskInfoInstance(bool isElevated, int deviceNumber, string devicePath) { - _localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out _isDrive, out _isVolume, out _isDevice); + _isElevated = isElevated; + + var getByDeviceNumber = deviceNumber > -1; + + if (getByDeviceNumber) + _deviceNumber = deviceNumber; + + _localDevicePath = getByDeviceNumber ? Path.PhysicalDrivePrefix + _deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out _isDrive, out _isVolume, out _isDevice); if (_isDrive) _localDevicePath = FileSystemHelper.GetLocalDevicePath(_localDevicePath); + + + // The StorageDeviceInfo is always needed as it contains the device- and partition number. + + var localDevicePathStorageDeviceInfo = Local.GetStorageDeviceInfoNative(_isElevated, _isDevice, _deviceNumber, _localDevicePath, out _localDevicePath); + + if (null == localDevicePathStorageDeviceInfo) + return; + + + DeviceInfo theDeviceInfo = null; + StorageDeviceInfo theDeviceStorageInfo = null; + + var theDeviceNumber = getByDeviceNumber ? _deviceNumber : localDevicePathStorageDeviceInfo.DeviceNumber; + + + foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) + { + string unusedDevicePath; + + theDeviceStorageInfo = Local.GetStorageDeviceInfoNative(_isElevated, true, theDeviceNumber, device.DevicePath, out unusedDevicePath); + + if (null == theDeviceStorageInfo) + continue; + + theDeviceInfo = device; + break; + } + + if (null == theDeviceInfo) + return; + + + // Set instance properties. + + DevicePath = theDeviceInfo.DevicePath; + + DeviceDescription = theDeviceInfo.DeviceDescription; + + Name = theDeviceInfo.FriendlyName; + + PhysicalDeviceObjectName = theDeviceInfo.PhysicalDeviceObjectName; + + + StorageAdapterInfo = Local.GetStorageAdapterInfoCore(_isElevated, theDeviceInfo.DevicePath, theDeviceInfo.BusReportedDeviceDescription); + + StorageDeviceInfo = _isDevice ? theDeviceStorageInfo : localDevicePathStorageDeviceInfo; + + StoragePartitionInfo = Local.GetStoragePartitionInfoCore(_isElevated, theDeviceInfo.DevicePath); + + + var pDiskInfo = Local.PopulatePhysicalDisk(_isElevated, this); + + LogicalDrives = pDiskInfo.LogicalDrives; + + VolumeGuids = pDiskInfo.VolumeGuids; + + PartitionIndexes = pDiskInfo.PartitionIndexes; + + + + + //if (!getByDeviceNumber) + // _deviceNumber = storageDeviceInfo.DeviceNumber; + + //var physicalDiskInfo = Local.EnumeratePhysicalDisksCore(_isElevated, _deviceNumber).FirstOrDefault(); + + //if (null != physicalDiskInfo) + //{ + // physicalDiskInfo.StorageAdapterInfo = Local.GetStorageAdapterInfoCore(isElevated, devicePath, busReportedDeviceDescription); + + // if (_isDrive || _isVolume) + // physicalDiskInfo.StorageDeviceInfo = storageDeviceInfo; + + // physicalDiskInfo.StoragePartitionInfo = Local.GetStoragePartitionInfoCore(isElevated, devicePath); + + // Utils.CopyTo(physicalDiskInfo, this); + //} } + + /// Returns the "FriendlyName" of the physical disk. /// Returns a string that represents this instance. public override string ToString() @@ -121,10 +197,13 @@ public override bool Equals(object obj) var other = obj as PhysicalDiskInfo; - return null != other && null != other.DevicePath && null != other.StorageDeviceInfo && - other.DevicePath.Equals(DevicePath, StringComparison.OrdinalIgnoreCase) && - other.StorageDeviceInfo.Equals(StorageDeviceInfo) && - other.StorageDeviceInfo.DeviceNumber.Equals(StorageDeviceInfo.DeviceNumber) && other.StorageDeviceInfo.PartitionNumber.Equals(StorageDeviceInfo.PartitionNumber); + return null != other && Equals(DevicePath, other.DevicePath) && + + Equals(StorageAdapterInfo, other.StorageAdapterInfo) && + + Equals(StorageDeviceInfo, other.StorageDeviceInfo) && + + Equals(StoragePartitionInfo, other.StoragePartitionInfo); } diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index e4ab20c8e..a9f72f9d0 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -62,7 +62,7 @@ public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) /// /// The bus reported bus reported device description of the instance. [SecurityCritical] - private static StorageAdapterInfo GetStorageAdapterInfoCore(bool isElevated, string devicePath, string busReportedDeviceDescription) + internal static StorageAdapterInfo GetStorageAdapterInfoCore(bool isElevated, string devicePath, string busReportedDeviceDescription) { var localDevicePath = devicePath; diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index c9892f76b..3e5f4e147 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -90,9 +90,8 @@ public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string dev /// /// The resolved local device path such as \\.\C: or \\.\PhysicalDrive0 [SecurityCritical] - private static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int deviceNumber, string devicePath, out string localDevicePath) + internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int deviceNumber, string devicePath, out string localDevicePath) { - var getByDeviceNumber = deviceNumber > -1; bool isDrive; bool isVolume; bool isDevice; @@ -102,6 +101,14 @@ private static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int d if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); + return GetStorageDeviceInfoNative(isElevated, isDevice, deviceNumber, localDevicePath, out localDevicePath); + } + + + internal static StorageDeviceInfo GetStorageDeviceInfoNative(bool isElevated, bool isDevice, int deviceNumber, string devicePath, out string localDevicePath) + { + localDevicePath = devicePath; + var getByDeviceNumber = deviceNumber > -1; var retry = false; Retry: diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index e051d8685..c6be26c60 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -84,7 +84,7 @@ public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, stri /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// [SecurityCritical] - private static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, string devicePath) + internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, string devicePath) { var localDevicePath = devicePath; From 5a1dd6f5710b525361f3d1a09277406fd2e41f5a Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 17 Jun 2018 01:35:52 +0200 Subject: [PATCH 114/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 7 - ...tPhysicalDiskInfo_UsingLogicalDrivePath.cs | 103 ----------- ...InstanceUsingDevicePathFromSystemDrive.cs} | 2 +- ...InitializeInstanceUsingLogicalDrivePath.cs | 31 ++++ ...InstanceUsingVolumePathFromSystemDrive.cs} | 2 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 5 +- AlphaFS/Device/Local.EnumerateDevices.cs | 2 +- AlphaFS/Device/Native Other/IoControlCode.cs | 1 - .../Local.EnumeratePhysicalDisks.cs | 129 ++------------ .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 166 +++++++++++------- .../PhysicalDiskInfo_Properties.cs | 27 ++- .../Storage/Local.GetStorageAdapterInfo.cs | 18 +- .../Storage/Local.GetStoragePartitionInfo.cs | 27 ++- 13 files changed, 193 insertions(+), 327 deletions(-) delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs => AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs} (97%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs => AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs} (97%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index 8e5e3fbf8..3149ffb96 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -64,13 +64,6 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - //Assert.AreEqual(driveCount, pDiskInfo.StorageAdapterInfo.DeviceNumber); - - //Assert.AreEqual(driveCount, pDiskInfo.StorageDeviceInfo.DeviceNumber); - - //Assert.AreEqual(driveCount, pDiskInfo.StoragePartitionInfo.DeviceNumber); - - driveCount++; Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs deleted file mode 100644 index 38e02204f..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingLogicalDrivePath.cs +++ /dev/null @@ -1,103 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_PhysicalDiskInfoTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Device_GetPhysicalDiskInfo_UsingLogicalDrivePath_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var driveCount = 0; - - foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) - { - // Works with System.IO.DriveType.CDRom. - - // System.UnauthorizedAccessException: (5) Access is denied. - if (driveInfo.DriveType == System.IO.DriveType.Network) - { - Console.WriteLine("#{0:000}\tSkipped Network drive: [{1}]\n", ++driveCount, driveInfo.Name); - continue; - } - - if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) - { - Console.WriteLine("#{0:000}\tSkipped NoRootDirectory drive: [{1}]\n", ++driveCount, driveInfo.Name); - continue; - } - - - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); - - - var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(driveInfo.Name); - - - UnitTestConstants.Dump(pDiskInfo); - - UnitTestConstants.Dump(pDiskInfo.StorageAdapterInfo, true); - - UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); - - UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - - - Assert.IsNotNull(pDiskInfo); - - Assert.IsNotNull(pDiskInfo.LogicalDrives); - - Assert.IsNotNull(pDiskInfo.VolumeGuids); - - - if (pDiskInfo.StorageDeviceInfo.PartitionNumber > 0) - Assert.IsNotNull(pDiskInfo.StoragePartitionInfo); - - - // For CDRom, the PartitionNumber is always -1. - - if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) - { - Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.CDRom, pDiskInfo.StorageDeviceInfo.DeviceType); - } - - else - Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); - - - Assert.AreEqual(pDiskInfo.LogicalDrives.Contains(driveInfo.Name.TrimEnd('\\'), StringComparer.OrdinalIgnoreCase), pDiskInfo.ContainsVolume(driveInfo.Name)); - - - Console.WriteLine(); - } - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs similarity index 97% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs index 8b2c8ded6..c4d521f85 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs @@ -31,7 +31,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetPhysicalDiskInfo_UsingDevicePathFromSystemDrive_Success() + public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingDevicePathFromSystemDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs index 5ef80a2a4..cde1fad19 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs @@ -39,6 +39,8 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Loc foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { + // Works with System.IO.DriveType.CDRom. + // System.UnauthorizedAccessException: (5) Access is denied. if (driveInfo.DriveType == System.IO.DriveType.Network) { @@ -46,6 +48,12 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Loc continue; } + if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) + { + Console.WriteLine("#{0:000}\tSkipped NoRootDirectory drive: [{1}]\n", ++driveCount, driveInfo.Name); + continue; + } + Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); @@ -66,6 +74,29 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Loc UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); + Assert.IsNotNull(pDiskInfo); + + Assert.IsNotNull(pDiskInfo.LogicalDrives); + + Assert.IsNotNull(pDiskInfo.VolumeGuids); + + + if (pDiskInfo.StorageDeviceInfo.PartitionNumber > 0) + Assert.IsNotNull(pDiskInfo.StoragePartitionInfo); + + + // For CDRom, the PartitionNumber is always -1. + + if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) + { + Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.CDRom, pDiskInfo.StorageDeviceInfo.DeviceType); + } + + else + Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + + var physicalDiskNumber = pDiskInfo.StorageDeviceInfo.DeviceNumber; Assert.AreEqual(physicalDiskNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs similarity index 97% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs index 4c11be04a..09af368bc 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs @@ -31,7 +31,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_Device_GetPhysicalDiskInfo_UsingVolumePathFromSystemDrive_Success() + public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingVolumePathFromSystemDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 14a073e64..2fea10b94 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -144,9 +144,8 @@ AssemblyVersionInfo.cs - - - + + diff --git a/AlphaFS/Device/Local.EnumerateDevices.cs b/AlphaFS/Device/Local.EnumerateDevices.cs index 7f36170ac..016fa00ee 100644 --- a/AlphaFS/Device/Local.EnumerateDevices.cs +++ b/AlphaFS/Device/Local.EnumerateDevices.cs @@ -127,7 +127,7 @@ internal static IEnumerable EnumerateDevicesCore(string hostName, De /// One of the devices. /// true to retrieve all device properties. [SecurityCritical] - private static IEnumerable EnumerateDevicesNative(SafeCmConnectMachineHandle safeMachineHandle, string hostName, DeviceGuid deviceGuid, bool getAllProperties) + internal static IEnumerable EnumerateDevicesNative(SafeCmConnectMachineHandle safeMachineHandle, string hostName, DeviceGuid deviceGuid, bool getAllProperties) { var nonNullHostName = !Utils.IsNullOrWhiteSpace(hostName) ? hostName : Environment.MachineName; diff --git a/AlphaFS/Device/Native Other/IoControlCode.cs b/AlphaFS/Device/Native Other/IoControlCode.cs index 8a21ae51e..79b9a0ac3 100644 --- a/AlphaFS/Device/Native Other/IoControlCode.cs +++ b/AlphaFS/Device/Native Other/IoControlCode.cs @@ -19,7 +19,6 @@ * THE SOFTWARE. */ -using System; using System.IO; namespace Alphaleonis.Win32.Device diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 448180492..acaa91f3a 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -20,17 +20,14 @@ */ using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Security; -using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Security; -using Path = Alphaleonis.Win32.Filesystem.Path; namespace Alphaleonis.Win32.Device { public static partial class Local { - /// [AlphaFS] Enumerates the physical disks (including CD/DVD devices) on the Computer, populated with volume-/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CD/DVD devices) on the Computer, populated with volume/logical drive information. /// Returns an collection that represents the physical disks on the Computer. [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() @@ -39,136 +36,38 @@ public static IEnumerable EnumeratePhysicalDisks() } - /// [AlphaFS] Enumerates the physical disks (including CD/DVD devices) on the Computer, populated with volume-/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CD/DVD devices) on the Computer, populated with volume/logical drive information. + /// Returns an collection that represents the physical disks on the Computer. + /// Retrieve instances by device number. + [SecurityCritical] + public static IEnumerable EnumeratePhysicalDisks(int deviceNumber) + { + return EnumeratePhysicalDisksCore(ProcessContext.IsElevatedProcess, deviceNumber); + } + + + /// [AlphaFS] Enumerates the physical disks (including CD/DVD devices) on the Computer, populated with volume/logical drive information. /// Returns an collection that represents the physical disks on the Computer. /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// Retrieve a instance by device number. [SecurityCritical] internal static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, int deviceNumber) { - var getByDeviceNumber = deviceNumber > -1; - foreach (var deviceInfo in EnumerateDevicesCore(null, new []{DeviceGuid.Disk, DeviceGuid.CDRom}, false)) { string unusedLocalDevicePath; - // The StorageDeviceInfo is always needed as it contains the device- and partition number. - - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, deviceInfo.DevicePath, out unusedLocalDevicePath); - - if (null == storageDeviceInfo) - continue; - - - var devicePath = deviceInfo.DevicePath; - - var pDiskInfo = new PhysicalDiskInfo - { - DevicePath = devicePath, - - DeviceDescription = deviceInfo.DeviceDescription, - - Name = deviceInfo.FriendlyName, - - PhysicalDeviceObjectName = deviceInfo.PhysicalDeviceObjectName, - - - StorageAdapterInfo = GetStorageAdapterInfoCore(isElevated, devicePath, deviceInfo.BusReportedDeviceDescription), - - StorageDeviceInfo = storageDeviceInfo, - - StoragePartitionInfo = GetStoragePartitionInfoCore(isElevated, devicePath) - }; - - - //if (pDiskInfo.StorageDeviceInfo.TotalSize == 0) - // pDiskInfo.StorageDeviceInfo.TotalSize = new DiskSpaceInfo(devicePath, false, true, true).TotalNumberOfBytes; - - yield return PopulatePhysicalDisk(isElevated, pDiskInfo); - - - // There can only be one. - if (getByDeviceNumber) - break; - } - } - - - /// Retrieves volumes and logical drives that belong to - internal static PhysicalDiskInfo PopulatePhysicalDisk(bool isElevated, PhysicalDiskInfo pDiskInfo) - { - var newPDiskInfo = Utils.CopyFrom(pDiskInfo); - - var deviceNumber = newPDiskInfo.StorageDeviceInfo.DeviceNumber; - - - foreach (var volumeGuid in Volume.EnumerateVolumes()) - { - string unusedLocalDevicePath; // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, deviceNumber, volumeGuid, out unusedLocalDevicePath); + var storageDeviceInfo = GetStorageDeviceInfoNative(isElevated, true, deviceNumber, deviceInfo.DevicePath, out unusedLocalDevicePath); if (null == storageDeviceInfo) continue; - AddToPartitionIndex(newPDiskInfo, storageDeviceInfo.PartitionNumber); - - AddToVolumeGuids(newPDiskInfo, volumeGuid); - - // Resolve logical drive from volume matching DeviceNumber and PartitionNumber. - - var driveName = Volume.GetVolumeDisplayName(volumeGuid); - - if (!Utils.IsNullOrWhiteSpace(driveName)) - AddToLogicalDrives(newPDiskInfo, driveName); + yield return new PhysicalDiskInfo(deviceNumber, deviceInfo.DevicePath, deviceInfo); } - - - return newPDiskInfo; - } - - - private static void AddToPartitionIndex(PhysicalDiskInfo pDiskInfo, int deviceNumber) - { - // Add device partition index numbers. - - if (null == pDiskInfo.PartitionIndexes) - pDiskInfo.PartitionIndexes = new Collection(); - - pDiskInfo.PartitionIndexes.Add(deviceNumber); - } - - - private static void AddToVolumeGuids(PhysicalDiskInfo pDiskInfo, string volumeGuid) - { - //// Add device volume labels. - - //if (null == pDiskInfo.VolumeLabels) - // pDiskInfo.VolumeLabels = new Collection(); - - //pDiskInfo.VolumeLabels.Add(pVolume.Name); - - - // Add device volume GUIDs. - - if (null == pDiskInfo.VolumeGuids) - pDiskInfo.VolumeGuids = new Collection(); - - pDiskInfo.VolumeGuids.Add(volumeGuid); - } - - - private static void AddToLogicalDrives(PhysicalDiskInfo pDiskInfo, string drivePath) - { - // Add device logical drive. - - if (null == pDiskInfo.LogicalDrives) - pDiskInfo.LogicalDrives = new Collection(); - - pDiskInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(drivePath)); } } } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index bb4d112a7..8ac470c79 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -20,8 +20,8 @@ */ using System; +using System.Collections.ObjectModel; using System.Globalization; -using System.Linq; using System.Security; using Alphaleonis.Win32.Filesystem; @@ -32,40 +32,27 @@ namespace Alphaleonis.Win32.Device [SecurityCritical] public sealed partial class PhysicalDiskInfo { - #region Fields - - private int _deviceNumber = -1; - private string _localDevicePath; - private bool _isElevated; - private bool _isDrive; - private bool _isVolume; - private bool _isDevice; - - #endregion // Fields - - #region Constructors - /// [AlphaFS] Initializes an empty PhysicalDiskInfo instance. - public PhysicalDiskInfo() + private PhysicalDiskInfo() { } - /// [AlphaFS] Initializes a PhysicalDiskInfo instance from a physical disk number such as: 0, 1, ... + /// [AlphaFS] Initializes an instance from a physical disk number. /// A number that indicates a physical disk on the Computer. public PhysicalDiskInfo(int deviceNumber) { if (deviceNumber < 0) throw new ArgumentOutOfRangeException("deviceNumber"); - CreatePhysicalDiskInfoInstance(Security.ProcessContext.IsElevatedProcess, deviceNumber, null); + CreatePhysicalDiskInfoInstance(this, Security.ProcessContext.IsElevatedProcess, deviceNumber, null, null); } - /// [AlphaFS] Initializes a PhysicalDiskInfo instance from a physical disk number such as: 0, 1, ... + /// [AlphaFS] Initializes an instance from a physical disk device path. /// - /// Do not create and instance for every volume/logical drive on the Computer as each call queries all physical disks, associated volumes and logical drives. + /// Creating an instance for every volume/logical drive on the Computer is expensive as each call queries all physical disks, associated volumes/logical drives. /// Instead, use method and property or . /// /// @@ -76,104 +63,147 @@ public PhysicalDiskInfo(int deviceNumber) /// public PhysicalDiskInfo(string devicePath) { - CreatePhysicalDiskInfoInstance(Security.ProcessContext.IsElevatedProcess, -1, devicePath); + CreatePhysicalDiskInfoInstance(this, Security.ProcessContext.IsElevatedProcess, -1, devicePath, null); + } + + + internal PhysicalDiskInfo(int deviceNumber, string devicePath, DeviceInfo deviceInfo) + { + CreatePhysicalDiskInfoInstance(this, Security.ProcessContext.IsElevatedProcess, deviceNumber, devicePath, deviceInfo); } #endregion // Constructors [SecurityCritical] - private void CreatePhysicalDiskInfoInstance(bool isElevated, int deviceNumber, string devicePath) + private static void CreatePhysicalDiskInfoInstance(PhysicalDiskInfo physicalDiskInfo, bool isElevated, int deviceNumber, string devicePath, DeviceInfo deviceInfo) { - _isElevated = isElevated; - var getByDeviceNumber = deviceNumber > -1; + var isDrive = false; + bool isVolume; + var isDevice = false; - if (getByDeviceNumber) - _deviceNumber = deviceNumber; - - _localDevicePath = getByDeviceNumber ? Path.PhysicalDrivePrefix + _deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out _isDrive, out _isVolume, out _isDevice); + var localDevicePath = getByDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); - if (_isDrive) - _localDevicePath = FileSystemHelper.GetLocalDevicePath(_localDevicePath); + if (isDrive) + localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var localDevicePathStorageDeviceInfo = Local.GetStorageDeviceInfoNative(_isElevated, _isDevice, _deviceNumber, _localDevicePath, out _localDevicePath); + var storageDeviceInfo = Local.GetStorageDeviceInfoNative(isElevated, isDevice, deviceNumber, localDevicePath, out localDevicePath); - if (null == localDevicePathStorageDeviceInfo) + if (null == storageDeviceInfo) return; - DeviceInfo theDeviceInfo = null; - StorageDeviceInfo theDeviceStorageInfo = null; + deviceNumber = getByDeviceNumber ? deviceNumber : storageDeviceInfo.DeviceNumber; - var theDeviceNumber = getByDeviceNumber ? _deviceNumber : localDevicePathStorageDeviceInfo.DeviceNumber; + if (null == deviceInfo) + foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) + { + string unusedDevicePath; + var deviceStorageInfo = Local.GetStorageDeviceInfoNative(isElevated, true, deviceNumber, device.DevicePath, out unusedDevicePath); - foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) - { - string unusedDevicePath; + if (null == deviceStorageInfo) + continue; - theDeviceStorageInfo = Local.GetStorageDeviceInfoNative(_isElevated, true, theDeviceNumber, device.DevicePath, out unusedDevicePath); + deviceInfo = device; + break; + } - if (null == theDeviceStorageInfo) - continue; + if (null == deviceInfo) + return; - theDeviceInfo = device; - break; - } - if (null == theDeviceInfo) - return; + physicalDiskInfo.DeviceInfo = deviceInfo; + + physicalDiskInfo.StorageAdapterInfo = Local.GetStorageAdapterInfoNative(deviceNumber, localDevicePath, deviceInfo.BusReportedDeviceDescription); + + physicalDiskInfo.StoragePartitionInfo = Local.GetStoragePartitionInfoNative(isElevated, deviceNumber, localDevicePath); + + physicalDiskInfo.StorageDeviceInfo = storageDeviceInfo; + + PopulatePhysicalDisk(isElevated, physicalDiskInfo); + } - // Set instance properties. - DevicePath = theDeviceInfo.DevicePath; + /// Retrieves volumes/logical drives that belong to the instance. + [SecurityCritical] + private static void PopulatePhysicalDisk(bool isElevated, PhysicalDiskInfo physicalDiskInfo) + { + var deviceNumber = physicalDiskInfo.StorageDeviceInfo.DeviceNumber; - DeviceDescription = theDeviceInfo.DeviceDescription; - Name = theDeviceInfo.FriendlyName; + foreach (var volumeGuid in Volume.EnumerateVolumes()) + { + string unusedLocalDevicePath; - PhysicalDeviceObjectName = theDeviceInfo.PhysicalDeviceObjectName; + // The StorageDeviceInfo is always needed as it contains the device- and partition number. + var storageDeviceInfo = Local.GetStorageDeviceInfoCore(isElevated, deviceNumber, volumeGuid, out unusedLocalDevicePath); - StorageAdapterInfo = Local.GetStorageAdapterInfoCore(_isElevated, theDeviceInfo.DevicePath, theDeviceInfo.BusReportedDeviceDescription); + if (null == storageDeviceInfo) + continue; - StorageDeviceInfo = _isDevice ? theDeviceStorageInfo : localDevicePathStorageDeviceInfo; - StoragePartitionInfo = Local.GetStoragePartitionInfoCore(_isElevated, theDeviceInfo.DevicePath); + AddToPartitionIndex(physicalDiskInfo, storageDeviceInfo.PartitionNumber); + + AddToVolumeGuids(physicalDiskInfo, volumeGuid); + + // Resolve logical drive from volume matching DeviceNumber and PartitionNumber. - var pDiskInfo = Local.PopulatePhysicalDisk(_isElevated, this); + var driveName = Volume.GetVolumeDisplayName(volumeGuid); - LogicalDrives = pDiskInfo.LogicalDrives; - VolumeGuids = pDiskInfo.VolumeGuids; + if (!Utils.IsNullOrWhiteSpace(driveName)) - PartitionIndexes = pDiskInfo.PartitionIndexes; + AddToLogicalDrives(physicalDiskInfo, driveName); + } + } + private static void AddToPartitionIndex(PhysicalDiskInfo pDiskInfo, int deviceNumber) + { + // Add device partition index numbers. + if (null == pDiskInfo.PartitionIndexes) + pDiskInfo.PartitionIndexes = new Collection(); - //if (!getByDeviceNumber) - // _deviceNumber = storageDeviceInfo.DeviceNumber; + pDiskInfo.PartitionIndexes.Add(deviceNumber); + } - //var physicalDiskInfo = Local.EnumeratePhysicalDisksCore(_isElevated, _deviceNumber).FirstOrDefault(); - //if (null != physicalDiskInfo) - //{ - // physicalDiskInfo.StorageAdapterInfo = Local.GetStorageAdapterInfoCore(isElevated, devicePath, busReportedDeviceDescription); + private static void AddToVolumeGuids(PhysicalDiskInfo pDiskInfo, string volumeGuid) + { + //// Add device volume labels. - // if (_isDrive || _isVolume) - // physicalDiskInfo.StorageDeviceInfo = storageDeviceInfo; + //if (null == pDiskInfo.VolumeLabels) + // pDiskInfo.VolumeLabels = new Collection(); + + //pDiskInfo.VolumeLabels.Add(pVolume.Name); + + + // Add device volume GUIDs. + + if (null == pDiskInfo.VolumeGuids) + pDiskInfo.VolumeGuids = new Collection(); + + pDiskInfo.VolumeGuids.Add(volumeGuid); + } + + + private static void AddToLogicalDrives(PhysicalDiskInfo pDiskInfo, string drivePath) + { + // Add device logical drive. - // physicalDiskInfo.StoragePartitionInfo = Local.GetStoragePartitionInfoCore(isElevated, devicePath); + if (null == pDiskInfo.LogicalDrives) + pDiskInfo.LogicalDrives = new Collection(); - // Utils.CopyTo(physicalDiskInfo, this); - //} + pDiskInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(drivePath)); } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs index e9ca2048a..ec9a57f1c 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs @@ -27,17 +27,26 @@ namespace Alphaleonis.Win32.Device { public sealed partial class PhysicalDiskInfo { - /// The device description. - public string DeviceDescription { get; internal set; } + private DeviceInfo DeviceInfo { get; set; } + + /// The device description. + public string DeviceDescription + { + get { return null != DeviceInfo ? DeviceInfo.DeviceDescription : null; } + } + /// The path to the device. /// Returns a string that represents the path to the device. /// A drive path such as: C:, D:\, /// a volume path such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// or a string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string. + /// or a string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string. /// - public string DevicePath { get; internal set; } + public string DevicePath + { + get { return null != DeviceInfo ? DeviceInfo.DevicePath : null; } + } /// An of logical drives that are located on the physical disk. @@ -45,7 +54,10 @@ public sealed partial class PhysicalDiskInfo /// The "FriendlyName" of the physical disk. - public string Name { get; internal set; } + public string Name + { + get { return null != DeviceInfo ? DeviceInfo.FriendlyName : null; } + } /// An of partition index numbers that are located on the physical disk. @@ -53,7 +65,10 @@ public sealed partial class PhysicalDiskInfo /// Encapsulates the physical device location (PDO) information provided by a device's firmware to Windows. - public string PhysicalDeviceObjectName { get; internal set; } + public string PhysicalDeviceObjectName + { + get { return null != DeviceInfo ? DeviceInfo.PhysicalDeviceObjectName : null; } + } /// The storage device adapter information. Retrieving this information requires an elevated state. diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index a9f72f9d0..e404efdcf 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -22,7 +22,6 @@ using System; using System.Security; using Alphaleonis.Win32.Filesystem; -using Alphaleonis.Win32.Security; namespace Alphaleonis.Win32.Device { @@ -43,7 +42,7 @@ public static partial class Local [SecurityCritical] public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) { - return GetStorageAdapterInfoCore(ProcessContext.IsElevatedProcess, devicePath, null); + return GetStorageAdapterInfoCore(devicePath, null); } @@ -53,7 +52,6 @@ public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) /// /// /// - /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ @@ -62,18 +60,26 @@ public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) /// /// The bus reported bus reported device description of the instance. [SecurityCritical] - internal static StorageAdapterInfo GetStorageAdapterInfoCore(bool isElevated, string devicePath, string busReportedDeviceDescription) + internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath, string busReportedDeviceDescription) { var localDevicePath = devicePath; + // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath, out localDevicePath); + var storageDeviceInfo = GetStorageDeviceInfoCore(false, -1, localDevicePath, out localDevicePath); if (null == storageDeviceInfo) return null; + return GetStorageAdapterInfoNative(storageDeviceInfo.DeviceNumber, localDevicePath, busReportedDeviceDescription); + } + + + [SecurityCritical] + internal static StorageAdapterInfo GetStorageAdapterInfoNative(int deviceNumber, string localDevicePath, string busReportedDeviceDescription) + { using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, NativeMethods.FILE_ANY_ACCESS)) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY @@ -87,7 +93,7 @@ internal static StorageAdapterInfo GetStorageAdapterInfoCore(bool isElevated, st { if (null != safeBuffer) { - var storageAdapterInfo = new StorageAdapterInfo(storageDeviceInfo.DeviceNumber, safeBuffer.PtrToStructure()); + var storageAdapterInfo = new StorageAdapterInfo(deviceNumber, safeBuffer.PtrToStructure()); if (!Utils.IsNullOrWhiteSpace(busReportedDeviceDescription)) storageAdapterInfo.BusReportedDeviceDescription = busReportedDeviceDescription; diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index c6be26c60..6697a3fae 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -70,34 +70,31 @@ public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, stri } - /// [AlphaFS] Retrieves information about the partitions on a disk and the features of each partition. - /// Returns a instance that represent the partition info that is related to . - /// - /// - /// - /// - /// true indicates the current process is in an elevated state, allowing to retrieve more data. - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// [SecurityCritical] internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, string devicePath) { var localDevicePath = devicePath; + // The StorageDeviceInfo is always needed as it contains the device- and partition number. var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath, out localDevicePath); if (null == storageDeviceInfo) return null; - + + return GetStoragePartitionInfoNative(isElevated, storageDeviceInfo.DeviceNumber, localDevicePath); + } + + + [SecurityCritical] + internal static StoragePartitionInfo GetStoragePartitionInfoNative(bool isElevated, int deviceNumber, string localDevicePath) + { using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) + if (null != safeBuffer) { var layout = safeBuffer.PtrToStructure(); @@ -119,7 +116,7 @@ internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated var disk = GetDiskGeometryExNative(safeHandle, localDevicePath); - return new StoragePartitionInfo(storageDeviceInfo.DeviceNumber, disk, layout, partitions); + return new StoragePartitionInfo(deviceNumber, disk, layout, partitions); } } From a7b5a4e0ae6c8a3138b5173d5e377a6f9ff078da Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 17 Jun 2018 11:17:23 +0200 Subject: [PATCH 115/133] -Code improvement, work in progress; -Changed some XxxCore/XxxNative methods from private to internal; --- .../UnitTest Utility/TemporaryDirectory.cs | 6 +- AlphaFS/Device/Native Other/IoControlCode.cs | 11 +- .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 103 +++++++++++------- .../PhysicalDiskInfo_Properties.cs | 26 ++--- .../Storage/Device.StorageDeviceInfo.cs | 6 +- .../Storage/Local.GetStorageAdapterInfo.cs | 37 ++++--- .../Storage/Local.GetStoragePartitionInfo.cs | 14 +-- .../Directory Class/Directory.Copy.cs | 2 +- .../Directory Class/Directory.Delete.cs | 2 +- .../DirectoryInfo.CopyTo.cs | 2 +- .../DirectoryInfo.CreateSubdirectory.cs | 2 +- AlphaFS/Filesystem/File Class/File.Copy.cs | 6 +- .../FileInfo Class/FileInfo.CopyToMoveTo.cs | 2 +- .../Path Class/Path.GetShort83Path.cs | 2 +- .../Path.GetSuffixedDirectoryName.cs | 2 +- ...ath.GetSuffixedDirectoryNameWithoutRoot.cs | 2 +- AlphaFS/Filesystem/Shell32.cs | 2 +- 17 files changed, 119 insertions(+), 108 deletions(-) diff --git a/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs index 302d80126..ff000bbb4 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs @@ -212,7 +212,7 @@ public System.IO.DirectoryInfo CreateRecursiveRandomizedAttributesTree(int level /// Creates an, optional recursive, directory structure of levels deep, populated with subdirectories and files of random size and possibly with read-only and/or hidden attributes set. - private System.IO.DirectoryInfo CreateTreeCore(string rootFullPath, int level = 1, bool recurse = false, bool readOnly = false, bool hidden = false) + internal System.IO.DirectoryInfo CreateTreeCore(string rootFullPath, int level = 1, bool recurse = false, bool readOnly = false, bool hidden = false) { var dirInfo = CreateDirectoryCore(rootFullPath, readOnly, hidden); @@ -298,7 +298,7 @@ public override string ToString() /// Returns a instance to an existing directory, possibly with read-only and/or hidden attributes set. - private System.IO.DirectoryInfo CreateDirectoryCore(string folderFullPath, bool readOnly = false, bool hidden = false) + internal System.IO.DirectoryInfo CreateDirectoryCore(string folderFullPath, bool readOnly = false, bool hidden = false) { var dirInfo = System.IO.Directory.CreateDirectory(!Alphaleonis.Utils.IsNullOrWhiteSpace(folderFullPath) ? folderFullPath : RandomDirectoryFullPath); @@ -309,7 +309,7 @@ private System.IO.DirectoryInfo CreateDirectoryCore(string folderFullPath, bool /// Returns a instance to an existing file, possibly with read-only and/or hidden attributes set. - private System.IO.FileInfo CreateFileCore(string fileFullPath, bool readOnly = false, bool hidden = false) + internal System.IO.FileInfo CreateFileCore(string fileFullPath, bool readOnly = false, bool hidden = false) { var fileInfo = new System.IO.FileInfo(!Alphaleonis.Utils.IsNullOrWhiteSpace(fileFullPath) ? fileFullPath : RandomTxtFileFullPath); diff --git a/AlphaFS/Device/Native Other/IoControlCode.cs b/AlphaFS/Device/Native Other/IoControlCode.cs index 79b9a0ac3..0d9bfb364 100644 --- a/AlphaFS/Device/Native Other/IoControlCode.cs +++ b/AlphaFS/Device/Native Other/IoControlCode.cs @@ -182,7 +182,7 @@ internal enum IoControlCode : uint ///// - //DiskLogging = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x000a << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_LOGGING = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x000a << 2) | IoMethod.Buffered | (0 << 14), ///// Is similar to IOCTL_DISK_FORMAT_TRACKS, except that it allows the caller to specify several more parameters. The additional extended parameters are the format gap length, the number of sectors per track, and an array whose element size is equal to the number of sectors per track. This array represents the track layout. @@ -675,15 +675,6 @@ internal enum IoControlCode : uint //FSCTL_GET_BOOT_AREA_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (140 << 2) | IoMethod.Buffered | (0 << 14), #endregion // FILE_DEVICE_FILE_SYSTEM - - - #region VIDEO - - //VideoQuerySupportedBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0125 << 2) | IoMethod.Buffered | (0 << 14), - //VideoQueryDisplayBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0126 << 2) | IoMethod.Buffered | (0 << 14), - //VideoSetDisplayBrightness = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO << 16) | (0x0127 << 2) | IoMethod.Buffered | (0 << 14), - - #endregion // VIDEO } } } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index 8ac470c79..3d0e98ea9 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -20,9 +20,13 @@ */ using System; +using System.Collections; +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; +using System.Linq; using System.Security; +using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Device @@ -32,6 +36,15 @@ namespace Alphaleonis.Win32.Device [SecurityCritical] public sealed partial class PhysicalDiskInfo { + #region Fields + + private Collection partitionIndexCollection; + private Collection volumeGuidCollection; + private Collection logicalDriveCollection; + + #endregion // Fields + + #region Constructors private PhysicalDiskInfo() @@ -59,7 +72,7 @@ public PhysicalDiskInfo(int deviceNumber) /// A disk path such as: \\.\PhysicalDrive0 /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// public PhysicalDiskInfo(string devicePath) { @@ -91,13 +104,14 @@ private static void CreatePhysicalDiskInfoInstance(PhysicalDiskInfo physicalDisk // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var storageDeviceInfo = Local.GetStorageDeviceInfoNative(isElevated, isDevice, deviceNumber, localDevicePath, out localDevicePath); + physicalDiskInfo.StorageDeviceInfo = Local.GetStorageDeviceInfoNative(isElevated, isDevice, deviceNumber, localDevicePath, out localDevicePath); - if (null == storageDeviceInfo) + if (null == physicalDiskInfo.StorageDeviceInfo) return; - deviceNumber = getByDeviceNumber ? deviceNumber : storageDeviceInfo.DeviceNumber; + deviceNumber = getByDeviceNumber ? deviceNumber : physicalDiskInfo.StorageDeviceInfo.DeviceNumber; + if (null == deviceInfo) foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) @@ -118,25 +132,26 @@ private static void CreatePhysicalDiskInfoInstance(PhysicalDiskInfo physicalDisk physicalDiskInfo.DeviceInfo = deviceInfo; - - physicalDiskInfo.StorageAdapterInfo = Local.GetStorageAdapterInfoNative(deviceNumber, localDevicePath, deviceInfo.BusReportedDeviceDescription); - physicalDiskInfo.StoragePartitionInfo = Local.GetStoragePartitionInfoNative(isElevated, deviceNumber, localDevicePath); - physicalDiskInfo.StorageDeviceInfo = storageDeviceInfo; + using (var safeFileHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + { + physicalDiskInfo.StorageAdapterInfo = Local.GetStorageAdapterInfoNative(safeFileHandle, deviceNumber, localDevicePath, deviceInfo.BusReportedDeviceDescription); + physicalDiskInfo.StoragePartitionInfo = Local.GetStoragePartitionInfoNative(safeFileHandle, deviceNumber, localDevicePath); + } + - PopulatePhysicalDisk(isElevated, physicalDiskInfo); + physicalDiskInfo.PopulatePhysicalDisk(isElevated, physicalDiskInfo); } /// Retrieves volumes/logical drives that belong to the instance. [SecurityCritical] - private static void PopulatePhysicalDisk(bool isElevated, PhysicalDiskInfo physicalDiskInfo) + private void PopulatePhysicalDisk(bool isElevated, PhysicalDiskInfo physicalDiskInfo) { var deviceNumber = physicalDiskInfo.StorageDeviceInfo.DeviceNumber; - - + foreach (var volumeGuid in Volume.EnumerateVolumes()) { string unusedLocalDevicePath; @@ -149,35 +164,45 @@ private static void PopulatePhysicalDisk(bool isElevated, PhysicalDiskInfo physi continue; - AddToPartitionIndex(physicalDiskInfo, storageDeviceInfo.PartitionNumber); + AddToPartitionIndex(storageDeviceInfo.PartitionNumber); - AddToVolumeGuids(physicalDiskInfo, volumeGuid); + AddToVolumeGuids(volumeGuid); // Resolve logical drive from volume matching DeviceNumber and PartitionNumber. var driveName = Volume.GetVolumeDisplayName(volumeGuid); - + if (!Utils.IsNullOrWhiteSpace(driveName)) - AddToLogicalDrives(physicalDiskInfo, driveName); + AddToLogicalDrives(driveName); } - } - private static void AddToPartitionIndex(PhysicalDiskInfo pDiskInfo, int deviceNumber) - { - // Add device partition index numbers. + if (null != partitionIndexCollection) + physicalDiskInfo.PartitionIndexes = partitionIndexCollection.ToArray(); - if (null == pDiskInfo.PartitionIndexes) - pDiskInfo.PartitionIndexes = new Collection(); + if (null != volumeGuidCollection) + physicalDiskInfo.VolumeGuids = volumeGuidCollection.ToArray(); - pDiskInfo.PartitionIndexes.Add(deviceNumber); + if (null != logicalDriveCollection) + physicalDiskInfo.LogicalDrives = logicalDriveCollection.ToArray(); } - private static void AddToVolumeGuids(PhysicalDiskInfo pDiskInfo, string volumeGuid) + /// Adds device partition index numbers. + private void AddToPartitionIndex(int deviceNumber) + { + if (null == partitionIndexCollection) + partitionIndexCollection = new Collection(); + + partitionIndexCollection.Add(deviceNumber); + } + + + /// Adds device volume GUIDs. + private void AddToVolumeGuids(string volumeGuid) { //// Add device volume labels. @@ -187,23 +212,20 @@ private static void AddToVolumeGuids(PhysicalDiskInfo pDiskInfo, string volumeGu //pDiskInfo.VolumeLabels.Add(pVolume.Name); - // Add device volume GUIDs. - - if (null == pDiskInfo.VolumeGuids) - pDiskInfo.VolumeGuids = new Collection(); + if (null == volumeGuidCollection) + volumeGuidCollection = new Collection(); - pDiskInfo.VolumeGuids.Add(volumeGuid); + volumeGuidCollection.Add(volumeGuid); } - private static void AddToLogicalDrives(PhysicalDiskInfo pDiskInfo, string drivePath) + /// Adds device logical drive. + private void AddToLogicalDrives(string drivePath) { - // Add device logical drive. - - if (null == pDiskInfo.LogicalDrives) - pDiskInfo.LogicalDrives = new Collection(); + if (null == logicalDriveCollection) + logicalDriveCollection = new Collection(); - pDiskInfo.LogicalDrives.Add(Path.RemoveTrailingDirectorySeparator(drivePath)); + logicalDriveCollection.Add(Path.RemoveTrailingDirectorySeparator(drivePath)); } @@ -227,13 +249,10 @@ public override bool Equals(object obj) var other = obj as PhysicalDiskInfo; - return null != other && Equals(DevicePath, other.DevicePath) && - - Equals(StorageAdapterInfo, other.StorageAdapterInfo) && - - Equals(StorageDeviceInfo, other.StorageDeviceInfo) && - - Equals(StoragePartitionInfo, other.StoragePartitionInfo); + return null != other && other.DevicePath == DevicePath && + other.StorageAdapterInfo == StorageAdapterInfo && + other.StorageDeviceInfo == StorageDeviceInfo && + other.StoragePartitionInfo == StoragePartitionInfo; } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs index ec9a57f1c..30c7c1f3c 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs @@ -20,17 +20,17 @@ */ using System; -using System.Collections.Generic; using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Device { public sealed partial class PhysicalDiskInfo { + /// An initialized instance. private DeviceInfo DeviceInfo { get; set; } - /// The device description. + /// The . public string DeviceDescription { get { return null != DeviceInfo ? DeviceInfo.DeviceDescription : null; } @@ -49,22 +49,22 @@ public string DevicePath } - /// An of logical drives that are located on the physical disk. - public ICollection LogicalDrives { get; internal set; } + /// An of logical drives that are located on the physical disk or null when no entries found. + public string[] LogicalDrives { get; private set; } - /// The "FriendlyName" of the physical disk. + /// The . public string Name { get { return null != DeviceInfo ? DeviceInfo.FriendlyName : null; } } - /// An of partition index numbers that are located on the physical disk. - public ICollection PartitionIndexes { get; internal set; } + /// An of partition index numbers that are located on the physical disk or null when no entries found. + public int[] PartitionIndexes { get; private set; } - /// Encapsulates the physical device location (PDO) information provided by a device's firmware to Windows. + /// The (PDO) information provided by a device's firmware to Windows. public string PhysicalDeviceObjectName { get { return null != DeviceInfo ? DeviceInfo.PhysicalDeviceObjectName : null; } @@ -72,18 +72,18 @@ public string PhysicalDeviceObjectName /// The storage device adapter information. Retrieving this information requires an elevated state. - public StorageAdapterInfo StorageAdapterInfo { get; internal set; } + public StorageAdapterInfo StorageAdapterInfo { get; private set; } /// The storage device information. - public StorageDeviceInfo StorageDeviceInfo { get; internal set; } + public StorageDeviceInfo StorageDeviceInfo { get; private set; } /// The storage device partition information. - public StoragePartitionInfo StoragePartitionInfo { get; internal set; } + public StoragePartitionInfo StoragePartitionInfo { get; private set; } - /// An of volume strings of volumes that are located on the physical disk. - public ICollection VolumeGuids { get; internal set; } + /// An of volume strings of volumes that are located on the physical disk or null when no entries found. + public string[] VolumeGuids { get; private set; } } } diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 50b7a7492..b09af3eca 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -77,11 +77,11 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() /// The storage device type. - public StorageDeviceType DeviceType { get; internal set; } + public StorageDeviceType DeviceType { get; private set; } /// The device number of the storage device, starting at 0. - public int DeviceNumber { get; internal set; } + public int DeviceNumber { get; private set; } /// @@ -89,7 +89,7 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() /// -1 is also returned if the device is accessed by its path: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// instead of a logical drive- or volume path. /// - public int PartitionNumber { get; internal set; } + public int PartitionNumber { get; private set; } /// The product ID of the physical disk. diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index e404efdcf..409433963 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -22,6 +22,7 @@ using System; using System.Security; using Alphaleonis.Win32.Filesystem; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { @@ -73,37 +74,37 @@ internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath, return null; - return GetStorageAdapterInfoNative(storageDeviceInfo.DeviceNumber, localDevicePath, busReportedDeviceDescription); + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, NativeMethods.FILE_ANY_ACCESS)) + + return GetStorageAdapterInfoNative(safeHandle, storageDeviceInfo.DeviceNumber, localDevicePath, busReportedDeviceDescription); } [SecurityCritical] - internal static StorageAdapterInfo GetStorageAdapterInfoNative(int deviceNumber, string localDevicePath, string busReportedDeviceDescription) + internal static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle safeFileHandle, int deviceNumber, string localDevicePath, string busReportedDeviceDescription) { - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, NativeMethods.FILE_ANY_ACCESS)) + var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { - var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY - { - PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, - QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery - }; + PropertyId = NativeMethods.STORAGE_PROPERTY_ID.StorageAdapterProperty, + QueryType = NativeMethods.STORAGE_QUERY_TYPE.PropertyStandardQuery + }; - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) + using (var safeBuffer = InvokeDeviceIoData(safeFileHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) + if (null != safeBuffer) { - if (null != safeBuffer) - { - var storageAdapterInfo = new StorageAdapterInfo(deviceNumber, safeBuffer.PtrToStructure()); + var storageAdapterInfo = new StorageAdapterInfo(deviceNumber, safeBuffer.PtrToStructure()); - if (!Utils.IsNullOrWhiteSpace(busReportedDeviceDescription)) - storageAdapterInfo.BusReportedDeviceDescription = busReportedDeviceDescription; - return storageAdapterInfo; - } + if (!Utils.IsNullOrWhiteSpace(busReportedDeviceDescription)) - return null; + storageAdapterInfo.BusReportedDeviceDescription = busReportedDeviceDescription; + + + return storageAdapterInfo; } - } + + return null; } } } diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 6697a3fae..30aec9743 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -84,16 +84,16 @@ internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated return null; - return GetStoragePartitionInfoNative(isElevated, storageDeviceInfo.DeviceNumber, localDevicePath); + using (var safeFileHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + + return GetStoragePartitionInfoNative(safeFileHandle, storageDeviceInfo.DeviceNumber, localDevicePath); } [SecurityCritical] - internal static StoragePartitionInfo GetStoragePartitionInfoNative(bool isElevated, int deviceNumber, string localDevicePath) + internal static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeFileHandle, int deviceNumber, string localDevicePath) { - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) + using (var safeBuffer = InvokeDeviceIoData(safeFileHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) if (null != safeBuffer) { @@ -114,7 +114,7 @@ internal static StoragePartitionInfo GetStoragePartitionInfoNative(bool isElevat partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); - var disk = GetDiskGeometryExNative(safeHandle, localDevicePath); + var disk = GetDiskGeometryExNative(safeFileHandle, localDevicePath); return new StoragePartitionInfo(deviceNumber, disk, layout, partitions); } @@ -126,7 +126,7 @@ internal static StoragePartitionInfo GetStoragePartitionInfoNative(bool isElevat /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). [SecurityCritical] - private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeHandle, string pathForException) + internal static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeHandle, string pathForException) { var bufferSize = 128; diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs index 35eec6679..c0a6ec20a 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Copy.cs @@ -767,7 +767,7 @@ internal static CopyMoveResult CopyMoveCore(KernelTransaction transaction, strin } - private static CopyMoveResult CopyDeleteDirectoryCore(KernelTransaction transaction, string sourcePathLp, string destinationPathLp, bool preserveDates, bool emulateMove, CopyOptions? copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, CopyMoveResult copyMoveResult) + internal static CopyMoveResult CopyDeleteDirectoryCore(KernelTransaction transaction, string sourcePathLp, string destinationPathLp, bool preserveDates, bool emulateMove, CopyOptions? copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, CopyMoveResult copyMoveResult) { var cmr = copyMoveResult ?? new CopyMoveResult(sourcePathLp, destinationPathLp, true, true, preserveDates, emulateMove); diff --git a/AlphaFS/Filesystem/Directory Class/Directory.Delete.cs b/AlphaFS/Filesystem/Directory Class/Directory.Delete.cs index 8650e13dc..5c71d725e 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory.Delete.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory.Delete.cs @@ -334,7 +334,7 @@ internal static void DeleteDirectoryCore(KernelTransaction transaction, FileSyst [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - private static void DeleteDirectoryCore(KernelTransaction transaction, string pathLp, bool ignoreReadOnly, bool continueOnNotFound) + internal static void DeleteDirectoryCore(KernelTransaction transaction, string pathLp, bool ignoreReadOnly, bool continueOnNotFound) { startRemoveDirectory: diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs index 06126dfb8..c2c14ed5f 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CopyTo.cs @@ -399,7 +399,7 @@ public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bo /// Returns the retrieved long full path. /// Indicates the format of the path parameter(s). [SecurityCritical] - private CopyMoveResult CopyToMoveToCore(string destinationPath, bool preserveDates, CopyOptions? copyOptions, MoveOptions? moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, out string longFullPath, PathFormat pathFormat) + internal CopyMoveResult CopyToMoveToCore(string destinationPath, bool preserveDates, CopyOptions? copyOptions, MoveOptions? moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, out string longFullPath, PathFormat pathFormat) { longFullPath = Path.GetExtendedLengthPathCore(Transaction, destinationPath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); diff --git a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CreateSubdirectory.cs b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CreateSubdirectory.cs index 5dee9b6ac..b3c2186d2 100644 --- a/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CreateSubdirectory.cs +++ b/AlphaFS/Filesystem/DirectoryInfo Class/DirectoryInfo.CreateSubdirectory.cs @@ -152,7 +152,7 @@ public DirectoryInfo CreateSubdirectory(string path, string templatePath, Direct /// The security to apply. /// When true compresses the directory. [SecurityCritical] - private DirectoryInfo CreateSubdirectoryCore(string path, string templatePath, ObjectSecurity directorySecurity, bool compress) + internal DirectoryInfo CreateSubdirectoryCore(string path, string templatePath, ObjectSecurity directorySecurity, bool compress) { string pathLp = Path.CombineCore(false, LongFullName, path); string templatePathLp = templatePath == null ? null : diff --git a/AlphaFS/Filesystem/File Class/File.Copy.cs b/AlphaFS/Filesystem/File Class/File.Copy.cs index b27b0de6b..7446d08fb 100644 --- a/AlphaFS/Filesystem/File Class/File.Copy.cs +++ b/AlphaFS/Filesystem/File Class/File.Copy.cs @@ -853,9 +853,9 @@ internal static CopyMoveResult CopyMoveCore(KernelTransaction transaction, bool return cmr; } - - - private static bool CopyMoveNative(KernelTransaction transaction, bool isMove, string sourcePathLp, string destinationPathLp, NativeMethods.NativeCopyMoveProgressRoutine routine, CopyOptions? copyOptions, MoveOptions? moveOptions, out bool cancel, out int lastError) + + + internal static bool CopyMoveNative(KernelTransaction transaction, bool isMove, string sourcePathLp, string destinationPathLp, NativeMethods.NativeCopyMoveProgressRoutine routine, CopyOptions? copyOptions, MoveOptions? moveOptions, out bool cancel, out int lastError) { cancel = false; diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.CopyToMoveTo.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.CopyToMoveTo.cs index abb45b7b9..337cf9ba9 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.CopyToMoveTo.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.CopyToMoveTo.cs @@ -596,7 +596,7 @@ public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, Co /// /// [SecurityCritical] - private CopyMoveResult CopyToMoveToCore(string destinationPath, CopyOptions? copyOptions, MoveOptions? moveOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, out string longFullPath, PathFormat pathFormat) + internal 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); diff --git a/AlphaFS/Filesystem/Path Class/Path.GetShort83Path.cs b/AlphaFS/Filesystem/Path Class/Path.GetShort83Path.cs index 054238fed..cac6ee85b 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetShort83Path.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetShort83Path.cs @@ -70,7 +70,7 @@ public static string GetShort83PathTransacted(KernelTransaction transaction, str /// An existing path to a folder or file. /// true to retrieve the short path form, false to retrieve the regular long form from the 8.3 . [SecurityCritical] - private static string GetLongShort83PathCore(KernelTransaction transaction, string path, bool getShort) + internal static string GetLongShort83PathCore(KernelTransaction transaction, string path, bool getShort) { var pathLp = GetFullPathCore(transaction, path, GetFullPathOptions.AsLongPath | GetFullPathOptions.FullCheck); diff --git a/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryName.cs b/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryName.cs index 5cc190796..607cf0842 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryName.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryName.cs @@ -65,7 +65,7 @@ public static string GetSuffixedDirectoryNameTransacted(KernelTransaction transa /// The transaction. /// The path. [SecurityCritical] - private static string GetSuffixedDirectoryNameCore(KernelTransaction transaction, string path) + internal static string GetSuffixedDirectoryNameCore(KernelTransaction transaction, string path) { var dirInfo = Directory.GetParentCore(transaction, path, PathFormat.RelativePath); diff --git a/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryNameWithoutRoot.cs b/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryNameWithoutRoot.cs index b2934d130..ff4cdc34d 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryNameWithoutRoot.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetSuffixedDirectoryNameWithoutRoot.cs @@ -62,7 +62,7 @@ public static string GetSuffixedDirectoryNameWithoutRootTransacted(KernelTransac /// The transaction. /// The path. [SecurityCritical] - private static string GetSuffixedDirectoryNameWithoutRootCore(KernelTransaction transaction, string path) + internal static string GetSuffixedDirectoryNameWithoutRootCore(KernelTransaction transaction, string path) { var dirInfo = Directory.GetParentCore(transaction, path, PathFormat.RelativePath); diff --git a/AlphaFS/Filesystem/Shell32.cs b/AlphaFS/Filesystem/Shell32.cs index 19dd86a06..e7c6cb0ae 100644 --- a/AlphaFS/Filesystem/Shell32.cs +++ b/AlphaFS/Filesystem/Shell32.cs @@ -747,7 +747,7 @@ internal static bool UrlIsOpaque(string url) /// The associated file- or protocol-related string from the registry or string.Empty if no association can be found. /// [SecurityCritical] - private static string GetFileAssociationCore(string path, AssociationAttributes attributes, AssociationString associationType) + internal static string GetFileAssociationCore(string path, AssociationAttributes attributes, AssociationString associationType) { if (Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); From a9bd9e4a86a7fce9f3efa6ba383332f48ce2f1a9 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 17 Jun 2018 11:49:17 +0200 Subject: [PATCH 116/133] Renamed argument safeHandle to safeFileHandle for consistency. --- .../FilesystemHelper.CreateDirectoryJunction.cs | 4 ++-- .../FilesystemHelper.DeleteDirectoryJunction.cs | 4 ++-- .../FilesystemHelper.GetLinkTarget.cs | 10 +++++----- AlphaFS/Device/Local.GetDeviceIoData.cs | 6 +++--- AlphaFS/Device/Local.GetVolumeDiskExtents.cs | 4 ++-- AlphaFS/Device/Local.InvokeDeviceIoData.cs | 6 +++--- .../Device/Storage/Local.GetStorageAdapterInfo.cs | 1 + .../Device/Storage/Local.GetStoragePartitionInfo.cs | 4 ++-- .../Storage/Local.SetStorageDeviceInfoData.cs | 6 +++--- AlphaFS/Filesystem/File Class/File.Create.cs | 13 +++++-------- AlphaFS/Filesystem/File Class/File.Open.cs | 9 ++++----- 11 files changed, 32 insertions(+), 35 deletions(-) diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs index 0732bf2a7..1729e98fb 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs @@ -32,7 +32,7 @@ namespace Alphaleonis.Win32.Device internal static partial class FileSystemHelper { /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). - internal static void CreateDirectoryJunction(SafeFileHandle safeHandle, string directoryPath) + internal static void CreateDirectoryJunction(SafeFileHandle safeFileHandle, string directoryPath) { var targetDirBytes = Encoding.Unicode.GetBytes(Path.NonInterpretedPathPrefix + Path.GetRegularPathCore(directoryPath, GetFullPathOptions.AddTrailingDirectorySeparator, false)); @@ -75,7 +75,7 @@ internal static void CreateDirectoryJunction(SafeFileHandle safeHandle, string d { safeBuffer.StructureToPtr(reparseDataBuffer, false); - var success = NativeMethods.DeviceIoJunctions(safeHandle, NativeMethods.IoControlCode.FSCTL_SET_REPARSE_POINT, safeBuffer, (uint) (targetDirBytes.Length + 20), IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoJunctions(safeFileHandle, NativeMethods.IoControlCode.FSCTL_SET_REPARSE_POINT, safeBuffer, (uint) (targetDirBytes.Length + 20), IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs index 3093fbb68..f75e38b64 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Device internal static partial class FileSystemHelper { /// [AlphaFS] Deletes an NTFS directory junction. - internal static void DeleteDirectoryJunction(SafeFileHandle safeHandle) + internal static void DeleteDirectoryJunction(SafeFileHandle safeFileHandle) { var reparseDataBuffer = new Filesystem.NativeMethods.REPARSE_DATA_BUFFER { @@ -43,7 +43,7 @@ internal static void DeleteDirectoryJunction(SafeFileHandle safeHandle) { safeBuffer.StructureToPtr(reparseDataBuffer, false); - var success = NativeMethods.DeviceIoJunctions(safeHandle, NativeMethods.IoControlCode.FSCTL_DELETE_REPARSE_POINT, safeBuffer, REPARSE_DATA_BUFFER_HEADER_SIZE, IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoJunctions(safeFileHandle, NativeMethods.IoControlCode.FSCTL_DELETE_REPARSE_POINT, safeBuffer, REPARSE_DATA_BUFFER_HEADER_SIZE, IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs index f20980292..d52fb359d 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs @@ -35,9 +35,9 @@ internal static partial class FileSystemHelper /// /// [SecurityCritical] - internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, string reparsePath) + internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeFileHandle, string reparsePath) { - using (var safeBuffer = GetLinkTargetData(safeHandle, reparsePath)) + using (var safeBuffer = GetLinkTargetData(safeFileHandle, reparsePath)) { var header = safeBuffer.PtrToStructure(); @@ -87,9 +87,9 @@ internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, stri [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) + private static SafeGlobalMemoryBufferHandle GetLinkTargetData(SafeFileHandle safeFileHandle, string reparsePath) { - Utils.IsValidHandle(safeHandle); + Utils.IsValidHandle(safeFileHandle); var bufferSize = MAXIMUM_REPARSE_DATA_BUFFER_SIZE; @@ -97,7 +97,7 @@ private static SafeGlobalMemoryBufferHandle GetLinkTargetData(SafeFileHandle saf { var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeFileHandle, NativeMethods.IoControlCode.FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Local.GetDeviceIoData.cs b/AlphaFS/Device/Local.GetDeviceIoData.cs index 4198a31d0..de3ce3547 100644 --- a/AlphaFS/Device/Local.GetDeviceIoData.cs +++ b/AlphaFS/Device/Local.GetDeviceIoData.cs @@ -31,9 +31,9 @@ public static partial class Local { [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] - private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, string pathForException, out int lastError, int size = -1) + private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle safeFileHandle, NativeMethods.IoControlCode controlCode, string pathForException, out int lastError, int size = -1) { - Utils.IsValidHandle(safeHandle); + Utils.IsValidHandle(safeFileHandle); var bufferSize = size > -1 ? size : Marshal.SizeOf(typeof(T)); @@ -41,7 +41,7 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa { var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - var success = NativeMethods.DeviceIoControl(safeHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeFileHandle, controlCode, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Local.GetVolumeDiskExtents.cs b/AlphaFS/Device/Local.GetVolumeDiskExtents.cs index 9ba3e5644..ae466f083 100644 --- a/AlphaFS/Device/Local.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Local.GetVolumeDiskExtents.cs @@ -30,7 +30,7 @@ public static partial class Local { /// Retrieves the physical location and disk number of a specified volume on one or more disks. [SecurityCritical] - private static NativeMethods.VOLUME_DISK_EXTENTS? GetVolumeDiskExtents(SafeFileHandle safeHandle, string pathForException) + private static NativeMethods.VOLUME_DISK_EXTENTS? GetVolumeDiskExtents(SafeFileHandle safeFileHandle, string pathForException) { var structSize = Marshal.SizeOf(typeof(NativeMethods.DISK_EXTENT_SINGLE)); var bufferSize = structSize; @@ -39,7 +39,7 @@ public static partial class Local while(true) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) { - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeFileHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Local.InvokeDeviceIoData.cs b/AlphaFS/Device/Local.InvokeDeviceIoData.cs index 21c7e7ef7..60ffb0f90 100644 --- a/AlphaFS/Device/Local.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Local.InvokeDeviceIoData.cs @@ -32,9 +32,9 @@ public static partial class Local /// Invokes InvokeIoControl with the specified input and specified size. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] - internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeHandle, NativeMethods.IoControlCode controlCode, T anyObject, string pathForException, int size = -1) + internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandle safeFileHandle, NativeMethods.IoControlCode controlCode, T anyObject, string pathForException, int size = -1) { - Utils.IsValidHandle(safeHandle); + Utils.IsValidHandle(safeFileHandle); var bufferSize = size > -1 ? size : Marshal.SizeOf(anyObject); @@ -42,7 +42,7 @@ internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandl { var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize); - var success = NativeMethods.DeviceIoControlAnyObjectGetSet(safeHandle, controlCode, anyObject, (uint) bufferSize, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoControlAnyObjectGetSet(safeFileHandle, controlCode, anyObject, (uint) bufferSize, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs index 409433963..0626d5dfb 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs @@ -91,6 +91,7 @@ internal static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle sa using (var safeBuffer = InvokeDeviceIoData(safeFileHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 8)) + if (null != safeBuffer) { var storageAdapterInfo = new StorageAdapterInfo(deviceNumber, safeBuffer.PtrToStructure()); diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs index 30aec9743..5e21aae99 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs @@ -126,14 +126,14 @@ internal static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandl /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). [SecurityCritical] - internal static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeHandle, string pathForException) + internal static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeFileHandle, string pathForException) { var bufferSize = 128; while (true) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) { - var success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + var success = NativeMethods.DeviceIoControl(safeFileHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs b/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs index bd3380f4b..65a2da258 100644 --- a/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs +++ b/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs @@ -28,7 +28,7 @@ namespace Alphaleonis.Win32.Device public static partial class Local { [SecurityCritical] - private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, SafeFileHandle safeHandle, string localDevicePath, StorageDeviceInfo storageDeviceInfo) + private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, SafeFileHandle safeFileHandle, string localDevicePath, StorageDeviceInfo storageDeviceInfo) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { @@ -37,7 +37,7 @@ private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, Saf }; - using (var safeBuffer = InvokeDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) + using (var safeBuffer = InvokeDeviceIoData(safeFileHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) { var deviceDescriptor = safeBuffer.PtrToStructure(); @@ -74,7 +74,7 @@ private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, Saf if (isElevated) { - using (var safeBuffer = GetDeviceIoData(safeHandle,NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, localDevicePath, out lastError)) + using (var safeBuffer = GetDeviceIoData(safeFileHandle,NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, localDevicePath, out lastError)) storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; } diff --git a/AlphaFS/Filesystem/File Class/File.Create.cs b/AlphaFS/Filesystem/File Class/File.Create.cs index c12c7847e..a89c20db0 100644 --- a/AlphaFS/Filesystem/File Class/File.Create.cs +++ b/AlphaFS/Filesystem/File Class/File.Create.cs @@ -258,22 +258,19 @@ public static FileStream CreateTransacted(KernelTransaction transaction, string [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) + 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; + SafeFileHandle safeFileHandle = null; try { - safeHandle = CreateFileCore(transaction, path, attributes, fileSecurity, mode, (FileSystemRights) access, share, true, false, pathFormat); + safeFileHandle = CreateFileCore(transaction, path, attributes, fileSecurity, mode, (FileSystemRights) access, share, true, false, pathFormat); - return new FileStream(safeHandle, access, bufferSize, (attributes & ExtendedFileAttributes.Overlapped) != 0); + return new FileStream(safeFileHandle, access, bufferSize, (attributes & ExtendedFileAttributes.Overlapped) != 0); } catch { - if (null != safeHandle && !safeHandle.IsClosed) - safeHandle.Close(); + Utils.IsValidHandle(safeFileHandle, false); throw; } diff --git a/AlphaFS/Filesystem/File Class/File.Open.cs b/AlphaFS/Filesystem/File Class/File.Open.cs index d96f615b8..3e7be9252 100644 --- a/AlphaFS/Filesystem/File Class/File.Open.cs +++ b/AlphaFS/Filesystem/File Class/File.Open.cs @@ -993,18 +993,17 @@ internal static FileStream OpenCore(KernelTransaction transaction, string path, : 0); - SafeFileHandle safeHandle = null; + SafeFileHandle safeFileHandle = null; try { - safeHandle = CreateFileCore(transaction, path, attributes, security, mode, rights, share, true, false, pathFormat); + safeFileHandle = CreateFileCore(transaction, path, attributes, security, mode, rights, share, true, false, pathFormat); - return new FileStream(safeHandle, access, bufferSize ?? NativeMethods.DefaultFileBufferSize, (attributes & ExtendedFileAttributes.Overlapped) != 0); + return new FileStream(safeFileHandle, access, bufferSize ?? NativeMethods.DefaultFileBufferSize, (attributes & ExtendedFileAttributes.Overlapped) != 0); } catch { - if (null != safeHandle && !safeHandle.IsClosed) - safeHandle.Close(); + Utils.IsValidHandle(safeFileHandle, false); throw; } From ae290d8623f506b4b029715656734a90210d7640 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 17 Jun 2018 14:52:04 +0200 Subject: [PATCH 117/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 3 + ...tionInfo_UsingVolumePathFromSystemDrive.cs | 3 + ...eInstanceUsingDevicePathFromSystemDrive.cs | 2 + ...InitializeInstanceUsingLogicalDrivePath.cs | 2 + ...eInstanceUsingVolumePathFromSystemDrive.cs | 2 + .../UnitTest Utility/TemporaryDirectory.cs | 4 +- AlphaFS/AlphaFS.csproj | 4 +- AlphaFS/Device/Device.DeviceInfo.cs | 2 +- AlphaFS/Device/DriveInfo/DriveInfo.cs | 7 +- AlphaFS/Device/Local.EnumerateDevices.cs | 4 +- AlphaFS/Device/Native Other/IoControlCode.cs | 166 +++++++++--------- .../{IoMethod.cs => IoCtlMethod.cs} | 18 +- .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 14 +- .../PhysicalDiskInfo_Properties.cs | 11 +- .../Storage/Device.StorageDeviceInfo.cs | 2 +- .../Storage/Device.StorageGptPartitionInfo.cs | 2 +- .../Storage/Device.StorageMbrPartitionInfo.cs | 2 +- .../Storage/Device.StoragePartitionInfo.cs | 2 +- .../Volume.EnumerateVolumeMountPoints.cs | 5 +- .../Volume/Volume.EnumerateVolumePathNames.cs | 4 +- .../Volume/Volume.SetVolumeMountPoint.cs | 13 +- AlphaFS/Device/Volume/VolumeInfo.cs | 7 +- AlphaFS/Filesystem/CopyMoveResult.cs | 2 +- AlphaFS/Filesystem/DiskSpaceInfo.cs | 7 +- .../Link Stream/AlternateDataStreamInfo.cs | 4 +- .../Path Class/Path.GetRegularPath.cs | 22 ++- AlphaFS/Network/NetworkConnectionInfo.cs | 2 +- AlphaFS/Network/NetworkInfo.cs | 2 +- AlphaFS/Network/OpenConnectionInfo.cs | 2 +- AlphaFS/Network/SessionInfo.cs | 2 +- AlphaFS/OperatingSystem/OperatingSystem.cs | 2 +- 31 files changed, 178 insertions(+), 146 deletions(-) rename AlphaFS/Device/Native Other/{IoMethod.cs => IoCtlMethod.cs} (78%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index 3149ffb96..0023e75c2 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -64,6 +64,9 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); + Assert.IsNull(pDiskInfo.DosDevice); + + driveCount++; Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs index e2f10cfc7..a30fb7ece 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs @@ -54,12 +54,15 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingVolumePathFromSystemDriv Assert.AreEqual(0, storagePartitionInfo.DeviceNumber); + Assert.IsNotNull(pDiskInfo); Assert.AreEqual(pDiskInfo.StorageDeviceInfo.DeviceNumber, storagePartitionInfo.DeviceNumber); Assert.AreEqual(pDiskInfo.StoragePartitionInfo, storagePartitionInfo); + Assert.IsNotNull(pDiskInfo.DosDevice); + // Show all partition information. diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs index c4d521f85..04b7aeba9 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs @@ -65,6 +65,8 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingDevicePathFromSystem Assert.IsNotNull(pDiskInfo.VolumeGuids); + Assert.IsNotNull(pDiskInfo.DosDevice); + Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs index cde1fad19..581ba6d1e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs @@ -80,6 +80,8 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Loc Assert.IsNotNull(pDiskInfo.VolumeGuids); + Assert.IsNotNull(pDiskInfo.DosDevice); + if (pDiskInfo.StorageDeviceInfo.PartitionNumber > 0) Assert.IsNotNull(pDiskInfo.StoragePartitionInfo); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs index 09af368bc..550e6a312 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs @@ -63,6 +63,8 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingVolumePathFromSystem Assert.IsNotNull(pDiskInfo.VolumeGuids); + Assert.IsNotNull(pDiskInfo.DosDevice); + Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); diff --git a/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs index ff000bbb4..62b7d9343 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/TemporaryDirectory.cs @@ -291,7 +291,7 @@ public override string ToString() #endregion // Methods - #region Private Members + #region Fields Members /// The path to the temporary folder, ending with a backslash. private static readonly string TempPath = System.IO.Path.GetTempPath(); @@ -331,7 +331,7 @@ private static void SetAttributes(System.IO.FileSystemInfo fsi, bool readOnly = fsi.Attributes |= System.IO.FileAttributes.Hidden; } - #endregion Private Members + #endregion Fields Members #region Disposable Members diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 1bbf1d2a2..b907a74dc 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -356,7 +356,7 @@ - + @@ -743,7 +743,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.DeviceInfo.cs b/AlphaFS/Device/Device.DeviceInfo.cs index a0df154a2..3b5b25d76 100644 --- a/AlphaFS/Device/Device.DeviceInfo.cs +++ b/AlphaFS/Device/Device.DeviceInfo.cs @@ -87,7 +87,7 @@ public DeviceInfo(string host) /// Represents the registry entry name of the driver key for a device instance. public string DeviceDriver { get; internal set; } - + /// Represents the name of the enumerator for a device instance. public string EnumeratorName { get; internal set; } diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.cs index 3c9d5ddf2..9b9fd1fe0 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.cs @@ -37,7 +37,7 @@ namespace Alphaleonis.Win32.Filesystem [SecurityCritical] public sealed partial class DriveInfo { - #region Private Fields + #region Fields [NonSerialized] private readonly VolumeInfo _volumeInfo; [NonSerialized] private readonly DiskSpaceInfo _dsi; @@ -65,9 +65,12 @@ public sealed partial class DriveInfo [SecurityCritical] public DriveInfo(string driveName) { - if (Utils.IsNullOrWhiteSpace(driveName)) + if (null == driveName) throw new ArgumentNullException("driveName"); + if (driveName.Trim().Length == 0) + throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "driveName"); + driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); diff --git a/AlphaFS/Device/Local.EnumerateDevices.cs b/AlphaFS/Device/Local.EnumerateDevices.cs index 016fa00ee..c453725f7 100644 --- a/AlphaFS/Device/Local.EnumerateDevices.cs +++ b/AlphaFS/Device/Local.EnumerateDevices.cs @@ -136,7 +136,7 @@ internal static IEnumerable EnumerateDevicesNative(SafeCmConnectMach // Start at the "Root" of the device tree. - using (var safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref classGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_PRESENT | NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_DEVICEINTERFACE, IntPtr.Zero, hostName, IntPtr.Zero)) + using (var safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref classGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_ALLCLASSES | NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_PRESENT | NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_DEVICEINTERFACE, IntPtr.Zero, hostName, IntPtr.Zero)) { var lastError = Marshal.GetLastWin32Error(); @@ -335,7 +335,7 @@ private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.Class); deviceInfo.DeviceDescription = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.DeviceDescription); - + deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.FriendlyName); deviceInfo.PhysicalDeviceObjectName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.PhysicalDeviceObjectName); diff --git a/AlphaFS/Device/Native Other/IoControlCode.cs b/AlphaFS/Device/Native Other/IoControlCode.cs index 0d9bfb364..26fc581f5 100644 --- a/AlphaFS/Device/Native Other/IoControlCode.cs +++ b/AlphaFS/Device/Native Other/IoControlCode.cs @@ -30,11 +30,11 @@ internal static partial class NativeMethods internal enum IoControlCode : uint { /// Retrieves the physical location of a specified volume on one or more disks. - IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), + IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// Return properties of a storage device or adapter. The request indicates the kind of information to retrieve, such as inquiry data for a device or capabilities and limitations of an adapter. - IOCTL_STORAGE_QUERY_PROPERTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x500 << 2) | IoMethod.Buffered | (0 << 14), + IOCTL_STORAGE_QUERY_PROPERTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x500 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), #region FILE_DEVICE_MASS_STORAGE @@ -44,7 +44,7 @@ internal enum IoControlCode : uint ///// Determines whether the media has changed on a removable-media device - the caller has opened with FILE_READ_ATTRIBUTES. Because no file system is mounted when a device is opened in this way, this request can be processed much more quickly than an IOCTL_STORAGE_CHECK_VERIFY request. - //IOCTL_STORAGE_CHECK_VERIFY2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0200 << 2) | IoMethod.Buffered | (0 << 14), // FileAccess.Any + //IOCTL_STORAGE_CHECK_VERIFY2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0200 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), // FileAccess.Any ///// Locks the device to prevent removal of the media. If the driver can prevent the media from being removed while the drive is in use, it disables or enables the mechanism that ejects media on a device - the caller has opened for read or write access. @@ -60,7 +60,7 @@ internal enum IoControlCode : uint ///// Causes media to be loaded in a device that the caller has opened with FILE_READ_ATTRIBUTES. Because no file system is mounted when a device is opened in this way, this request can be processed much more quickly than an IOCTL_STORAGE_LOAD_MEDIA request. - //IOCTL_STORAGE_LOAD_MEDIA2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0203 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_STORAGE_LOAD_MEDIA2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0203 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Claims a device for the exclusive use of the caller on a bus that supports multiple initiators and the concept of reserving a device, such as a SCSI bus. @@ -91,7 +91,7 @@ internal enum IoControlCode : uint ///// Unlike IOCTL_STORAGE_MEDIA_REMOVAL, the driver tracks IOCTL_STORAGE_EJECTION_CONTROL requests by caller and ignores unlock requests for ///// which it has not received a lock request from the same caller, thereby preventing other callers from unlocking the drive. ///// - //IOCTL_STORAGE_EJECTION_CONTROL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0250 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_STORAGE_EJECTION_CONTROL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0250 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -100,15 +100,15 @@ internal enum IoControlCode : uint ///// FILE_READ_ATTRIBUTES access and if the device has AutoPlay enabled in the registry. The caller must not open the device for read or write ///// access or the IOCTL operation will fail. This IOCTL has no effect on the AutoPlay setting in the registry. ///// - //IOCTL_STORAGE_MCN_CONTROL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0251 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_STORAGE_MCN_CONTROL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0251 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Returns information about the geometry of floppy drives. - //IOCTL_STORAGE_GET_MEDIA_TYPES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0300 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_STORAGE_GET_MEDIA_TYPES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0300 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Returns information about the types of media supported by a device. A storage class driver must handle this IOCTL to control devices to be accessed by the removable storage manager (RSM) either as stand-alone devices or as data transfer elements (drives) in a media library or changer device. - //IOCTL_STORAGE_GET_MEDIA_TYPES_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0301 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_STORAGE_GET_MEDIA_TYPES_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0301 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Resets an I/O bus and, indirectly, each device on the bus. Resetting the bus clears all device reservations and transfer speed settings, which must then be renegotiated, making it a time-consuming operation that should be used very rarely. The caller requires only read access to issue a bus reset. @@ -124,7 +124,7 @@ internal enum IoControlCode : uint /// Returns a STORAGE_DEVICE_NUMBER structure that contains the FILE_DEVICE_XXX type, device number, and, for a partitionable device, /// the partition number assigned to a device by the driver when the device is started. This request is usually issued by a fault-tolerant disk driver. /// - IOCTL_STORAGE_GET_DEVICE_NUMBER = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0420 << 2) | IoMethod.Buffered | (0 << 14), + IOCTL_STORAGE_GET_DEVICE_NUMBER = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0420 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -132,7 +132,7 @@ internal enum IoControlCode : uint ///// If the device supports prediction failure, the disk class driver queries the device for failure prediction status and reports the results. If the disk class driver assigns a nonzero value to the PredictFailure member of STORAGE_PREDICT_FAILURE in the output buffer at Irp->AssociatedIrp.SystemBuffer, the disk has bad sectors and is predicting a failure. The storage stack returns 512 bytes of vendor-specific information about the failure prediction in the VendorSpecific member of STORAGE_PREDICT_FAILURE. ///// If the PredictFailure member contains a value of zero, the disk is not predicting a failure. ///// - //IOCTL_STORAGE_PREDICT_FAILURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0440 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_STORAGE_PREDICT_FAILURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0440 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), #endregion // FILE_DEVICE_MASS_STORAGE @@ -142,7 +142,7 @@ internal enum IoControlCode : uint /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). /// IOCTL_DISK_GET_DRIVE_GEOMETRY_EX can retrieve information from both Master Boot Record (MBR) and GUID Partition Table (GPT)-type partitioned media. /// - IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0028 << 2) | IoMethod.Buffered | (0 << 14), + IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0028 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///////// Returns information about the type, size, and nature of a disk partition. (Floppy drivers need not handle this request.) @@ -154,7 +154,7 @@ internal enum IoControlCode : uint /// Contains extended information about a drive's partitions. - IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0014 << 2) | IoMethod.Buffered | (0 << 14), + IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0014 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Repartitions a disk as specified. (Floppy drivers need not handle this request.) @@ -162,7 +162,7 @@ internal enum IoControlCode : uint ///// Performs a logical format of a specified extent on a disk. - //IOCTL_DISK_VERIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0005 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_VERIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0005 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Formats the specified set of contiguous tracks on the disk. @@ -174,15 +174,15 @@ internal enum IoControlCode : uint ///// Increments a reference counter that enables the collection of disk performance statistics, such as the numbers of bytes read and written since the driver last processed this request, for a corresponding disk monitoring application. In Microsoft Windows 2000 this IOCTL is handled by the filter driver diskperf. In Windows XP and later operating systems, the partition manager handles this request for disks and ftdisk.sys and dmio.sys handle this request for volumes. - //IOCTL_DISK_PERFORMANCE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0008 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_PERFORMANCE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0008 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Determines whether a disk is writable. - //IOCTL_DISK_IS_WRITABLE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0009 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_IS_WRITABLE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0009 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// - //IOCTL_DISK_LOGGING = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x000a << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_LOGGING = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x000a << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Is similar to IOCTL_DISK_FORMAT_TRACKS, except that it allows the caller to specify several more parameters. The additional extended parameters are the format gap length, the number of sectors per track, and an array whose element size is equal to the number of sectors per track. This array represents the track layout. @@ -191,35 +191,35 @@ internal enum IoControlCode : uint ///// Do not use //[Obsolete] - //IOCTL_DISK_HISTOGRAM_STRUCTURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000c << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_HISTOGRAM_STRUCTURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000c << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Do not use //[Obsolete] - //IOCTL_DISK_HISTOGRAM_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000d << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_HISTOGRAM_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000d << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Do not use //[Obsolete] - //IOCTL_DISK_HISTOGRAM_RESET = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000e << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_HISTOGRAM_RESET = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000e << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Do not use //[Obsolete] - //IOCTL_DISK_REQUEST_STRUCTURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000f << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_REQUEST_STRUCTURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000f << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Do not use //[Obsolete] - //IOCTL_DISK_REQUEST_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x0010 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_REQUEST_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x0010 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Do not use //[Obsolete] - //IOCTL_DISK_CONTROLLER_NUMBER = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x0011 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_CONTROLLER_NUMBER = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x0011 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), /// Retrieves the length of the specified disk, volume, or partition. - IOCTL_DISK_GET_LENGTH_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0017 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + IOCTL_DISK_GET_LENGTH_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0017 << 2) | IoCtlMethod.Buffered | (FileAccess.Read << 14), ///// Returns version information, a capabilities mask, and a bitmask for the device. This IOCTL must be handled by drivers that support Self-Monitoring Analysis and Reporting Technology (SMART). @@ -264,7 +264,7 @@ internal enum IoControlCode : uint ///// - //DiskSenseDevice = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x00f8 << 2) | IoMethod.Buffered | (0 << 14), + //DiskSenseDevice = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x00f8 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// In Microsoft Windows 2000 and later operating systems, this IOCTL is replaced by IOCTL_STORAGE_CHECK_VERIFY. The only difference between the two IOCTLs is the base value. @@ -276,7 +276,7 @@ internal enum IoControlCode : uint ///// In Microsoft Windows 2000 and later operating systems, this IOCTL is replaced by IOCTL_STORAGE_GET_MEDIA_TYPES. The only difference between the two IOCTLs is the base value. - //IOCTL_DISK_GET_MEDIA_TYPES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0300 << 2) | IoMethod.Buffered | (0 << 14), + //IOCTL_DISK_GET_MEDIA_TYPES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0300 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), #endregion // FILE_DEVICE_DISK @@ -332,45 +332,45 @@ internal enum IoControlCode : uint #region FILE_DEVICE_FILE_SYSTEM ///// Requests a level 1 opportunistic lock on a file. - //FSCTL_REQUEST_OPLOCK_LEVEL_1 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (0 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_REQUEST_OPLOCK_LEVEL_1 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (0 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Requests a level 2 opportunistic lock on a file. - //FSCTL_REQUEST_OPLOCK_LEVEL_2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (1 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_REQUEST_OPLOCK_LEVEL_2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (1 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Requests a batch opportunistic lock on a file. - //FSCTL_REQUEST_BATCH_OPLOCK = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (2 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_REQUEST_BATCH_OPLOCK = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (2 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Responds to notification that an exclusive opportunistic lock on a file is about to be broken. Use this operation to indicate that the file should receive a level 2 opportunistic lock. - //FSCTL_OPLOCK_BREAK_ACKNOWLEDGE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (3 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_OPLOCK_BREAK_ACKNOWLEDGE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (3 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Notifies a server that a client application is ready to close a file. Use this operation after notification that an opportunistic lock on a file is ready to be broken. - //FSCTL_OPBATCH_ACK_CLOSE_PENDING = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (4 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_OPBATCH_ACK_CLOSE_PENDING = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (4 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// ///// Enables the calling application to wait for completion of an opportunistic lock break. ///// This operation is not useful to application developers and is documented here only for completeness. CreateFile handles the problem that this operation was designed to handle. ///// - //FSCTL_OPLOCK_BREAK_NOTIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (5 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_OPLOCK_BREAK_NOTIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (5 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Locks a volume if it is not in use. A locked volume can be accessed only through handles to the file object (*hDevice) that locks the volume. For more information, see the Remarks section. - //FSCTL_LOCK_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (6 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_LOCK_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (6 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Unlocks a volume. - //FSCTL_UNLOCK_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (7 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_UNLOCK_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (7 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Dismounts a volume regardless of whether or not the volume is currently in use. For more information, see the Remarks section. - //FSCTL_DISMOUNT_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (8 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_DISMOUNT_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (8 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Determines whether the specified volume is mounted, or if the specified file or directory is on a mounted volume. - //FSCTL_IS_VOLUME_MOUNTED = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (10 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_IS_VOLUME_MOUNTED = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (10 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -381,11 +381,11 @@ internal enum IoControlCode : uint ///// This control code is not supported with fast FAT file systems, and it is not a meaningful operation in NTFS or UDFS. NTFS and UDFS support ///// such a wide variety of codesets that any string is potentially a valid pathname. ///// - //FSCTL_IS_PATHNAME_VALID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (11 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_IS_PATHNAME_VALID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (11 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// The FSCTL_MARK_VOLUME_DIRTY control code marks a specified volume as dirty, which triggers Autochk.exe to run on the volume during the next system restart. - //FSCTL_MARK_VOLUME_DIRTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (12 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_MARK_VOLUME_DIRTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (12 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -397,15 +397,15 @@ internal enum IoControlCode : uint ///// LCN that refer more directly to the underlying physical storage. You must not use FSCTL_QUERY_RETRIEVAL_POINTERS with files other than ///// the page file, because they might reside on volumes, such as mirrored volumes, that have one-to-many mappings of VCNs to LCNs. ///// - //FSCTL_QUERY_RETRIEVAL_POINTERS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (14 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_QUERY_RETRIEVAL_POINTERS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (14 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Retrieves the current compression state of a file or directory on a volume whose file system supports per-stream compression. - //FSCTL_GET_COMPRESSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (15 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_GET_COMPRESSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (15 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), /// Sets the compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. You can use FSCTL_SET_COMPRESSION to compress or uncompress a file or directory on such a volume. - FSCTL_SET_COMPRESSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (16 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + FSCTL_SET_COMPRESSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (16 << 2) | IoCtlMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// @@ -415,7 +415,7 @@ internal enum IoControlCode : uint ///// directory or volume handle. File system redirectors that access files on remote machines treat this control code as a no-op. ///// Only kernel-level components can use this filesystem control code. ///// - //FSCTL_MARK_AS_SYSTEM_HIVE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (19 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_MARK_AS_SYSTEM_HIVE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (19 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// @@ -428,7 +428,7 @@ internal enum IoControlCode : uint ///// For more information about opportunistic locking and about the FSCTL_OPLOCK_BREAK_ACK_NO_2 control code, see the Microsoft Windows SDK ///// documentation. ///// - //FSCTL_OPLOCK_BREAK_ACK_NO_2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (20 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_OPLOCK_BREAK_ACK_NO_2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (20 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -437,11 +437,11 @@ internal enum IoControlCode : uint ///// To perform this operation, minifilter drivers call FltFsControlFile, and file systems, redirectors, and legacy file system filter drivers ///// call ZwFsControlFile, using the following parameters. ///// - //FSCTL_INVALIDATE_VOLUMES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (21 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_INVALIDATE_VOLUMES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (21 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// - //FSCTL_QUERY_FAT_BPB = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (22 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_QUERY_FAT_BPB = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (22 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -451,31 +451,31 @@ internal enum IoControlCode : uint ///// For more information about opportunistic locking and about the FSCTL_REQUEST_FILTER_OPLOCK control code, see the Microsoft Windows SDK ///// documentation. ///// - //FSCTL_REQUEST_FILTER_OPLOCK = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (23 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_REQUEST_FILTER_OPLOCK = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (23 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves the information from various file system performance counters. - //FSCTL_FILESYSTEM_GET_STATISTICS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (24 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_FILESYSTEM_GET_STATISTICS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (24 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves information about the specified NTFS file system volume. - //FSCTL_GET_NTFS_VOLUME_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (25 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_GET_NTFS_VOLUME_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (25 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves the first file record that is in use and is of a lesser than or equal ordinal value to the requested file reference number. - //FSCTL_GET_NTFS_FILE_RECORD = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (26 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_GET_NTFS_FILE_RECORD = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (26 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves a bitmap of occupied and available clusters on a volume. - //FSCTL_GET_VOLUME_BITMAP = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (27 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_GET_VOLUME_BITMAP = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (27 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Given a file handle, retrieves a data structure that describes the allocation and location on disk of a specific file, or, given a volume handle, the locations of bad clusters on a volume. - //FSCTL_GET_RETRIEVAL_POINTERS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (28 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_GET_RETRIEVAL_POINTERS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (28 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Relocates one or more virtual clusters of a file from one logical cluster to another within the same volume. This operation is used during defragmentation. - //FSCTL_MOVE_FILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (29 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_MOVE_FILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (29 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -484,43 +484,43 @@ internal enum IoControlCode : uint ///// To perform this operation, minifilter drivers call FltFsControlFile with the following parameters, and file systems, redirectors, and ///// legacy file system filter drivers call ZwFsControlFile with the following parameters. ///// - //FSCTL_IS_VOLUME_DIRTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (30 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_IS_VOLUME_DIRTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (30 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// - //FsctlGetHfsInformation = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (31 << 2) | IoMethod.Buffered | (0 << 14), + //FsctlGetHfsInformation = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (31 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Signals the file system driver not to perform any I/O boundary checks on partition read or write calls. Instead, boundary checks are performed by the device driver. - //FSCTL_ALLOW_EXTENDED_DASD_IO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (32 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_ALLOW_EXTENDED_DASD_IO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (32 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlReadPropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (33 << 2) | IoMethod.Neither | (0 << 14), + //FsctlReadPropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (33 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlWritePropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (34 << 2) | IoMethod.Neither | (0 << 14), + //FsctlWritePropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (34 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlDumpPropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (37 << 2) | IoMethod.Neither | (0 << 14), + //FsctlDumpPropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (37 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Searches a directory for a file whose creator owner matches the specified SID. - //FSCTL_FIND_FILES_BY_SID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (35 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_FIND_FILES_BY_SID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (35 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Sets the object identifier for the specified file or directory. - //FSCTL_SET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (38 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_SET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (38 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves the object identifier for the specified file or directory. - //FSCTL_GET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (39 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_GET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (39 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Removes the object identifier from a specified file or directory. The underlying object is not deleted. - //FSCTL_DELETE_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (40 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_DELETE_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (40 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), /// @@ -529,7 +529,7 @@ internal enum IoControlCode : uint /// Minifilters should use FltTagFile instead of FSCTL_SET_REPARSE_POINT to set a reparse point. /// For more information about reparse points and the FSCTL_SET_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_SET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (41 << 2) | IoMethod.Buffered | (0 << 14), + FSCTL_SET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (41 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// @@ -537,7 +537,7 @@ internal enum IoControlCode : uint /// To perform this operation, call FltFsControlFile or ZwFsControlFile with the following parameters. /// For more information about reparse points and the FSCTL_GET_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_GET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (42 << 2) | IoMethod.Buffered | (0 << 14), + FSCTL_GET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (42 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// @@ -547,13 +547,13 @@ internal enum IoControlCode : uint /// Minifilters should use FltUntagFile instead of FSCTL_DELETE_REPARSE_POINT to delete a reparse point. /// For more information about reparse points and the FSCTL_DELETE_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_DELETE_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (43 << 2) | IoMethod.Buffered | (0 << 14), + FSCTL_DELETE_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (43 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// ///// Enumerates the update sequence number (USN) data between two specified boundaries to obtain master file table (MFT) records. ///// - //FSCTL_ENUM_USN_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (44 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_ENUM_USN_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (44 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// The FSCTL_SECURITY_ID_CHECK control code performs a bulk security check of the security identifiers exposed through USN records. @@ -561,19 +561,19 @@ internal enum IoControlCode : uint ///// Retrieves the set of update sequence number (USN) change journal records between two specified USN values. - //FSCTL_READ_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (46 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_READ_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (46 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Modifies user data associated with the object identifier for the specified file or directory. - //FSCTL_SET_OBJECT_ID_EXTENDED = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (47 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_SET_OBJECT_ID_EXTENDED = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (47 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves the object identifier for the specified file or directory. If no object identifier exists, using FSCTL_CREATE_OR_GET_OBJECT_ID creates one. - //FSCTL_CREATE_OR_GET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (48 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_CREATE_OR_GET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (48 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Marks the indicated file as sparse or not sparse. In a sparse file, large ranges of zeros may not require disk allocation. Space for nonzero data will be allocated as needed as the file is written. - //FSCTL_SET_SPARSE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (49 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_SET_SPARSE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (49 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Fills a specified range of a file with zeros (0). If the file is sparse or compressed, the NTFS file system may deallocate disk space in the file. This sets the range of bytes to zeros (0) without extending the file size. @@ -592,47 +592,47 @@ internal enum IoControlCode : uint ///// The FSCTL_SET_ENCRYPTION request sets the encryption for the file or directory associated with the given handle. ///// The message contains an ENCRYPTION_BUFFER structure that indicates whether to encrypt/decrypt a file or an individual stream. ///// - //FSCTL_SET_ENCRYPTION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (53 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_SET_ENCRYPTION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (53 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlEncryptionFsctlIo = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (54 << 2) | IoMethod.Neither | (0 << 14), + //FsctlEncryptionFsctlIo = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (54 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlWriteRawEncrypted = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (55 << 2) | IoMethod.Neither | (0 << 14), + //FsctlWriteRawEncrypted = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (55 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlReadRawEncrypted = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (56 << 2) | IoMethod.Neither | (0 << 14), + //FsctlReadRawEncrypted = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (56 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Creates an update sequence number (USN) change journal stream on a target volume, or modifies an existing change journal stream. - //FSCTL_CREATE_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (57 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_CREATE_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (57 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Retrieves the update sequence number (USN) change-journal information for the specified file or directory. - //FSCTL_READ_FILE_USN_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (58 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_READ_FILE_USN_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (58 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Generates a record in the update sequence number (USN) change journal stream for the input file. This record will have the USN_REASON_CLOSE flag. - //FSCTL_WRITE_USN_CLOSE_RECORD = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (59 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_WRITE_USN_CLOSE_RECORD = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (59 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Increases the size of a mounted volume. - //FSCTL_EXTEND_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (60 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_EXTEND_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (60 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Queries for information on the current update sequence number (USN) change journal, its records, and its capacity. - //FSCTL_QUERY_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (61 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_QUERY_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (61 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Deletes the update sequence number (USN) change journal on a volume, or waits for notification of change journal deletion. - //FSCTL_DELETE_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (62 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_DELETE_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (62 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Marks a specified file or directory and its change journal record with information about changes to that file or directory. - //FSCTL_MARK_HANDLE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (63 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_MARK_HANDLE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (63 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -644,7 +644,7 @@ internal enum IoControlCode : uint ///// This FSCTL can be issued against either a file or directory handle. The source and destination files MUST reside on the volume ///// associated with the given handle. ///// - //FSCTL_SIS_COPYFILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (64 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_SIS_COPYFILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (64 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -668,11 +668,11 @@ internal enum IoControlCode : uint ///// Recalls a file from storage media that Remote Storage manages, which is the hierarchical storage management software. - //FSCTL_RECALL_FILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (69 << 2) | IoMethod.Neither | (0 << 14), + //FSCTL_RECALL_FILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (69 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// The FSCTL_GET_BOOT_AREA_INFO control code retrieves the locations of boot sectors for a volume. - //FSCTL_GET_BOOT_AREA_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (140 << 2) | IoMethod.Buffered | (0 << 14), + //FSCTL_GET_BOOT_AREA_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (140 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), #endregion // FILE_DEVICE_FILE_SYSTEM } diff --git a/AlphaFS/Device/Native Other/IoMethod.cs b/AlphaFS/Device/Native Other/IoCtlMethod.cs similarity index 78% rename from AlphaFS/Device/Native Other/IoMethod.cs rename to AlphaFS/Device/Native Other/IoCtlMethod.cs index 247517e3c..0a0998dc0 100644 --- a/AlphaFS/Device/Native Other/IoMethod.cs +++ b/AlphaFS/Device/Native Other/IoCtlMethod.cs @@ -24,28 +24,12 @@ namespace Alphaleonis.Win32.Device internal static partial class NativeMethods { /// Define values for DeviceIoControl. - internal enum IoMethod : uint + private enum IoCtlMethod : uint { - /// Buffered Buffered = 0, - - /// InDirect InDirect = 1, - - /// OutDirect OutDirect = 2, - - /// Neither Neither = 3 } - - - ///// Define values for DeviceIoControl access - //internal enum IoctlAccess : uint - //{ - // Any = 0, - // Read = 1, - // Write = 2 - //} } } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index 3d0e98ea9..1475e6591 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -93,7 +93,7 @@ private static void CreatePhysicalDiskInfoInstance(PhysicalDiskInfo physicalDisk { var getByDeviceNumber = deviceNumber > -1; var isDrive = false; - bool isVolume; + var isVolume = false; var isDevice = false; var localDevicePath = getByDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); @@ -132,7 +132,11 @@ private static void CreatePhysicalDiskInfoInstance(PhysicalDiskInfo physicalDisk physicalDiskInfo.DeviceInfo = deviceInfo; - + + + if (isDrive || isVolume) + physicalDiskInfo.DosDevice = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); + using (var safeFileHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) { @@ -181,13 +185,13 @@ private void PopulatePhysicalDisk(bool isElevated, PhysicalDiskInfo physicalDisk if (null != partitionIndexCollection) - physicalDiskInfo.PartitionIndexes = partitionIndexCollection.ToArray(); + physicalDiskInfo.PartitionIndexes = partitionIndexCollection; if (null != volumeGuidCollection) - physicalDiskInfo.VolumeGuids = volumeGuidCollection.ToArray(); + physicalDiskInfo.VolumeGuids = volumeGuidCollection; if (null != logicalDriveCollection) - physicalDiskInfo.LogicalDrives = logicalDriveCollection.ToArray(); + physicalDiskInfo.LogicalDrives = logicalDriveCollection; } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs index 30c7c1f3c..44b77e9f4 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs @@ -20,6 +20,7 @@ */ using System; +using System.Collections.Generic; using Alphaleonis.Win32.Filesystem; namespace Alphaleonis.Win32.Device @@ -49,8 +50,12 @@ public string DevicePath } + /// The DOS device name. + public string DosDevice { get; private set; } + + /// An of logical drives that are located on the physical disk or null when no entries found. - public string[] LogicalDrives { get; private set; } + public IEnumerable LogicalDrives { get; private set; } /// The . @@ -61,7 +66,7 @@ public string Name /// An of partition index numbers that are located on the physical disk or null when no entries found. - public int[] PartitionIndexes { get; private set; } + public IEnumerable PartitionIndexes { get; private set; } /// The (PDO) information provided by a device's firmware to Windows. @@ -84,6 +89,6 @@ public string PhysicalDeviceObjectName /// An of volume strings of volumes that are located on the physical disk or null when no entries found. - public string[] VolumeGuids { get; private set; } + public IEnumerable VolumeGuids { get; private set; } } } diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index b09af3eca..80fc0d4a0 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -31,7 +31,7 @@ namespace Alphaleonis.Win32.Device [SecurityCritical] public sealed class StorageDeviceInfo { - #region Private Fields + #region Fields #endregion // Private Fields diff --git a/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs b/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs index 39a13620a..64993cdd5 100644 --- a/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageGptPartitionInfo.cs @@ -31,7 +31,7 @@ namespace Alphaleonis.Win32.Device [SecurityCritical] public sealed class StorageGptPartitionInfo { - #region Private Fields + #region Fields private readonly int _partitionNumber; private ulong _partitionLength; diff --git a/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs b/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs index 50fe82ff9..dd225ab5d 100644 --- a/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageMbrPartitionInfo.cs @@ -31,7 +31,7 @@ namespace Alphaleonis.Win32.Device [SecurityCritical] public sealed class StorageMbrPartitionInfo { - #region Private Fields + #region Fields private readonly int _partitionNumber; private ulong _partitionLength; diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index 199cb81b8..00b9db9ab 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -34,7 +34,7 @@ namespace Alphaleonis.Win32.Device [SecurityCritical] public sealed class StoragePartitionInfo { - #region Private Fields + #region Fields private ulong _gptStartingUsableOffset; private ulong _gptUsableLength; diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs index b5109fe4a..bdc31cdb4 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs @@ -37,9 +37,12 @@ public static partial class Volume [SecurityCritical] public static IEnumerable EnumerateVolumeMountPoints(string volumeGuid) { - if (Utils.IsNullOrWhiteSpace(volumeGuid)) + if (null == volumeGuid) throw new ArgumentNullException("volumeGuid"); + if (volumeGuid.Trim().Length == 0) + throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "volumeGuid"); + if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid"); diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs index 360bce7d6..022297106 100644 --- a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs +++ b/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs @@ -37,9 +37,11 @@ public static partial class Volume [SecurityCritical] public static IEnumerable EnumerateVolumePathNames(string volumeGuid) { - if (Utils.IsNullOrWhiteSpace(volumeGuid)) + if (null == volumeGuid) throw new ArgumentNullException("volumeGuid"); + if (volumeGuid.Trim().Length == 0) + throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "volumeGuid"); if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid"); diff --git a/AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs b/AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs index bd9f751df..549768b47 100644 --- a/AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs +++ b/AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs @@ -40,12 +40,21 @@ public static partial class Volume [SecurityCritical] public static void SetVolumeMountPoint(string volumeMountPoint, string volumeGuid) { - if (Utils.IsNullOrWhiteSpace(volumeMountPoint)) + if (null == volumeMountPoint) throw new ArgumentNullException("volumeMountPoint"); - if (Utils.IsNullOrWhiteSpace(volumeGuid)) + if (volumeMountPoint.Trim().Length == 0) + throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "volumeMountPoint"); + + if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid"); + + if (null == volumeGuid) throw new ArgumentNullException("volumeGuid"); + if (volumeGuid.Trim().Length == 0) + throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "volumeGuid"); + if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid"); diff --git a/AlphaFS/Device/Volume/VolumeInfo.cs b/AlphaFS/Device/Volume/VolumeInfo.cs index 6091b2500..76775c868 100644 --- a/AlphaFS/Device/Volume/VolumeInfo.cs +++ b/AlphaFS/Device/Volume/VolumeInfo.cs @@ -34,7 +34,7 @@ namespace Alphaleonis.Win32.Filesystem [SecurityCritical] public sealed class VolumeInfo { - #region Private Fields + #region Fields [NonSerialized] private readonly bool _continueOnAccessError; [NonSerialized] private readonly SafeFileHandle _volumeHandle; @@ -54,9 +54,12 @@ public sealed class VolumeInfo [SecurityCritical] public VolumeInfo(string driveName) { - if (Utils.IsNullOrWhiteSpace(driveName)) + if (null == driveName) throw new ArgumentNullException("driveName"); + if (driveName.Trim().Length == 0) + throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "driveName"); + if (!driveName.StartsWith(Path.LongPathPrefix, StringComparison.Ordinal)) driveName = Path.IsUncPathCore(driveName, false, false) ? Path.GetLongPathCore(driveName, GetFullPathOptions.None) : Path.LongPathPrefix + driveName; diff --git a/AlphaFS/Filesystem/CopyMoveResult.cs b/AlphaFS/Filesystem/CopyMoveResult.cs index 6ee1e425b..424aadc22 100644 --- a/AlphaFS/Filesystem/CopyMoveResult.cs +++ b/AlphaFS/Filesystem/CopyMoveResult.cs @@ -31,7 +31,7 @@ namespace Alphaleonis.Win32.Filesystem [Serializable] public sealed class CopyMoveResult { - #region Private Fields + #region Fields [NonSerialized] internal readonly Stopwatch _stopwatch; diff --git a/AlphaFS/Filesystem/DiskSpaceInfo.cs b/AlphaFS/Filesystem/DiskSpaceInfo.cs index f1a1025b7..41155a8af 100644 --- a/AlphaFS/Filesystem/DiskSpaceInfo.cs +++ b/AlphaFS/Filesystem/DiskSpaceInfo.cs @@ -35,7 +35,7 @@ namespace Alphaleonis.Win32.Filesystem [SecurityCritical] public sealed class DiskSpaceInfo { - #region Private Fields + #region Fields [NonSerialized] private CultureInfo _cultureInfo; [NonSerialized] private readonly bool _initGetClusterInfo = true; @@ -54,9 +54,12 @@ public sealed class DiskSpaceInfo [SecurityCritical] public DiskSpaceInfo(string driveName) { - if (Utils.IsNullOrWhiteSpace(driveName)) + if (null == driveName) throw new ArgumentNullException("driveName"); + if (driveName.Trim().Length == 0) + throw new ArgumentException(Resources.Path_Is_Zero_Length_Or_Only_White_Space, "driveName"); + driveName = driveName.Length == 1 ? driveName + Path.VolumeSeparatorChar : Path.GetPathRoot(driveName, false); diff --git a/AlphaFS/Filesystem/Link Stream/AlternateDataStreamInfo.cs b/AlphaFS/Filesystem/Link Stream/AlternateDataStreamInfo.cs index 154033238..4d89bda97 100644 --- a/AlphaFS/Filesystem/Link Stream/AlternateDataStreamInfo.cs +++ b/AlphaFS/Filesystem/Link Stream/AlternateDataStreamInfo.cs @@ -28,7 +28,7 @@ namespace Alphaleonis.Win32.Filesystem /// public struct AlternateDataStreamInfo { - #region Private Fields + #region Fields private readonly string _streamName; private readonly string _fullPath; @@ -128,7 +128,7 @@ public override bool Equals(object obj) #endregion // Public Methods - #region Private Methods + #region Fields Methods private static string ParseStreamName(string streamName) { diff --git a/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs b/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs index 5d05f3b9d..be4f8acd8 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs @@ -59,24 +59,28 @@ internal static string GetRegularPathCore(string path, GetFullPathOptions option if (path == null) throw new ArgumentNullException("path"); - if (!allowEmpty && (path.Length == 0 || Utils.IsNullOrWhiteSpace(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); - return path.StartsWith(DosDeviceUncPrefix, StringComparison.OrdinalIgnoreCase) + if (path.StartsWith(DosDeviceUncPrefix, StringComparison.OrdinalIgnoreCase)) + return UncPrefix + path.Substring(DosDeviceUncPrefix.Length); + - ? UncPrefix + path.Substring(DosDeviceUncPrefix.Length) - : (path.StartsWith(NonInterpretedPathPrefix, StringComparison.Ordinal) + if (path.StartsWith(LogicalDrivePrefix, StringComparison.Ordinal)) + return path.Substring(LogicalDrivePrefix.Length); - ? path.Substring(NonInterpretedPathPrefix.Length) - : (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)))); + 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)); } } } diff --git a/AlphaFS/Network/NetworkConnectionInfo.cs b/AlphaFS/Network/NetworkConnectionInfo.cs index 8bef1e4d8..f349f031d 100644 --- a/AlphaFS/Network/NetworkConnectionInfo.cs +++ b/AlphaFS/Network/NetworkConnectionInfo.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Network /// Represents a connection to a network. public class NetworkConnectionInfo { - #region Private Fields + #region Fields private readonly INetworkConnection _networkConnection; diff --git a/AlphaFS/Network/NetworkInfo.cs b/AlphaFS/Network/NetworkInfo.cs index 27353fd18..8b385ad0c 100644 --- a/AlphaFS/Network/NetworkInfo.cs +++ b/AlphaFS/Network/NetworkInfo.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Network /// Represents a network on the local machine. It can also represent a collection of network connections with a similar network signature. public class NetworkInfo { - #region Private Fields + #region Fields private readonly INetwork _network; diff --git a/AlphaFS/Network/OpenConnectionInfo.cs b/AlphaFS/Network/OpenConnectionInfo.cs index 8347fcff0..5a589c8ba 100644 --- a/AlphaFS/Network/OpenConnectionInfo.cs +++ b/AlphaFS/Network/OpenConnectionInfo.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Network [Serializable] public sealed class OpenConnectionInfo { - #region Private Fields + #region Fields private string _netName; diff --git a/AlphaFS/Network/SessionInfo.cs b/AlphaFS/Network/SessionInfo.cs index b15795ee1..f6122052c 100644 --- a/AlphaFS/Network/SessionInfo.cs +++ b/AlphaFS/Network/SessionInfo.cs @@ -28,7 +28,7 @@ namespace Alphaleonis.Win32.Network [Serializable] public sealed class SessionInfo { - #region Private Fields + #region Fields private string _netName; diff --git a/AlphaFS/OperatingSystem/OperatingSystem.cs b/AlphaFS/OperatingSystem/OperatingSystem.cs index d4e6470a1..9786c7302 100644 --- a/AlphaFS/OperatingSystem/OperatingSystem.cs +++ b/AlphaFS/OperatingSystem/OperatingSystem.cs @@ -30,7 +30,7 @@ namespace Alphaleonis.Win32 /// [AlphaFS] Static class providing access to information about the operating system under which the assembly is executing. public static partial class OperatingSystem { - #region Private Fields + #region Fields private static bool _isServer; private static bool? _isWow64Process; From a4c52b7382dcfab7829965e96114bec44a5b4991 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 17 Jun 2018 16:28:45 +0200 Subject: [PATCH 118/133] Code improvement, work in progress. --- .../AlphaFS_Device.EnumeratePhysicalDisks.cs | 2 +- ...tionInfo_UsingVolumePathFromSystemDrive.cs | 2 +- ...eInstanceUsingDevicePathFromSystemDrive.cs | 2 +- ...InitializeInstanceUsingLogicalDrivePath.cs | 2 +- ...eInstanceUsingVolumePathFromSystemDrive.cs | 2 +- ...haFS_Volume.GetDriveNameForNtDeviceName.cs | 2 +- .../AlphaFS_Volume.GetXxx.cs | 2 +- .../DriveInfo/DriveInfo.GetDeviceInfo.cs | 2 +- AlphaFS/Device/DriveInfo/DriveInfo.cs | 2 +- ...icalDiskInfo.InitializePhysicalDiskInfo.cs | 78 ------------------- .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 2 +- .../PhysicalDiskInfo_Properties.cs | 4 +- .../Volume/Volume.GetVolumeDeviceName.cs | 1 + 13 files changed, 13 insertions(+), 90 deletions(-) delete mode 100644 AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs index 0023e75c2..94ff091b9 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs @@ -64,7 +64,7 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - Assert.IsNull(pDiskInfo.DosDevice); + Assert.IsNull(pDiskInfo.DosDeviceName); driveCount++; diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs index a30fb7ece..8ed1013f1 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs @@ -61,7 +61,7 @@ public void AlphaFS_Device_GetStoragePartitionInfo_UsingVolumePathFromSystemDriv Assert.AreEqual(pDiskInfo.StoragePartitionInfo, storagePartitionInfo); - Assert.IsNotNull(pDiskInfo.DosDevice); + Assert.IsNotNull(pDiskInfo.DosDeviceName); // Show all partition information. diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs index 04b7aeba9..dae10061c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs @@ -65,7 +65,7 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingDevicePathFromSystem Assert.IsNotNull(pDiskInfo.VolumeGuids); - Assert.IsNotNull(pDiskInfo.DosDevice); + Assert.IsNotNull(pDiskInfo.DosDeviceName); Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs index 581ba6d1e..8cb24327b 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs @@ -80,7 +80,7 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Loc Assert.IsNotNull(pDiskInfo.VolumeGuids); - Assert.IsNotNull(pDiskInfo.DosDevice); + Assert.IsNotNull(pDiskInfo.DosDeviceName); if (pDiskInfo.StorageDeviceInfo.PartitionNumber > 0) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs index 550e6a312..bde206762 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs @@ -63,7 +63,7 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingVolumePathFromSystem Assert.IsNotNull(pDiskInfo.VolumeGuids); - Assert.IsNotNull(pDiskInfo.DosDevice); + Assert.IsNotNull(pDiskInfo.DosDeviceName); Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs index 819516bb9..97b7d4570 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs @@ -47,7 +47,7 @@ public void AlphaFS_Volume_GetDriveNameForNtDeviceName_And_GetVolumeGuidForNtDev var driveName = driveInfo.Name; - var dosDeviceName = Alphaleonis.Win32.Filesystem.Volume.GetVolumeDeviceName(driveName); + var dosDeviceName = Alphaleonis.Win32.Filesystem.Volume.QueryDosDevice(driveName); var deviceGuid = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(driveName); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs index 8f2b91f25..0320302fd 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs @@ -56,7 +56,7 @@ public void AlphaFS_Volume_GetXxx_Local_Success() // GetVolumeDeviceName: "C:\" --> "\Device\HarddiskVolume4" - var deviceNameFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.GetVolumeDeviceName(driveInfo.Name); + var deviceNameFromLogicalDrive = Alphaleonis.Win32.Filesystem.Volume.QueryDosDevice(driveInfo.Name); Console.WriteLine("\tGetVolumeDeviceName\t\t\t: [{0}]", deviceNameFromLogicalDrive); diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs index a2eaa9ed2..5ebcea29c 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs @@ -74,7 +74,7 @@ private object GetDeviceInfo(int type, int mode) if (mode == 0) { // DosDeviceName - return _dosDeviceName ?? (_dosDeviceName = Volume.GetVolumeDeviceName(_name)); + return _dosDeviceName ?? (_dosDeviceName = Volume.QueryDosDevice(_name)); } break; diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.cs b/AlphaFS/Device/DriveInfo/DriveInfo.cs index 9b9fd1fe0..50f80edea 100644 --- a/AlphaFS/Device/DriveInfo/DriveInfo.cs +++ b/AlphaFS/Device/DriveInfo/DriveInfo.cs @@ -222,7 +222,7 @@ public DiskSpaceInfo DiskSpaceInfo } - /// [AlphaFS] The MS-DOS device name. + /// [AlphaFS] The Win32 Device name. public string DosDeviceName { get { return (string) GetDeviceInfo(1, 0); } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs deleted file mode 100644 index c03abb9fe..000000000 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.InitializePhysicalDiskInfo.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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; -using Alphaleonis.Win32.Filesystem; - -namespace Alphaleonis.Win32.Device -{ - public sealed partial class PhysicalDiskInfo - { - /// [AlphaFS] Initializes a instance that is related to the logical drive name, volume or . - /// Returns a instance that represents the physical disk on the Computer or null if the device can not be retrieved. - /// Use either or , not both. - /// - /// - /// - /// - /// true indicates the current process is in an elevated state, allowing to retrieve more data. - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// - /// An initialized instance. - /// An initialized instance. - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed.")] - [SecurityCritical] - internal static PhysicalDiskInfo InitializePhysicalDiskInfo(bool isElevated, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) - { - if (null == devicePath && null == deviceInfo) - return null; - - var isDevice = null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); - - if (isDevice) - devicePath = deviceInfo.DevicePath; - - return new PhysicalDiskInfo - { - DevicePath = devicePath, - - DeviceDescription = isDevice ? deviceInfo.DeviceDescription : null, - - Name = isDevice ? deviceInfo.FriendlyName : null, - - PhysicalDeviceObjectName = isDevice ? deviceInfo.PhysicalDeviceObjectName : null, - - - StorageAdapterInfo = Local.GetStorageAdapterInfoCore(devicePath, deviceInfo), - - StorageDeviceInfo = null != storageDeviceInfo ? storageDeviceInfo : Local.GetStorageDeviceInfoCore(isElevated, -1, devicePath), - - StoragePartitionInfo = Local.GetStoragePartitionInfoCore(isElevated, devicePath) - }; - } - } -} diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index 1475e6591..b3f1a2bde 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -135,7 +135,7 @@ private static void CreatePhysicalDiskInfoInstance(PhysicalDiskInfo physicalDisk if (isDrive || isVolume) - physicalDiskInfo.DosDevice = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); + physicalDiskInfo.DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); using (var safeFileHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs index 44b77e9f4..a9c784bb6 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs @@ -50,8 +50,8 @@ public string DevicePath } - /// The DOS device name. - public string DosDevice { get; private set; } + /// The Win32 Device name. + public string DosDeviceName { get; private set; } /// An of logical drives that are located on the physical disk or null when no entries found. diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs index 8a63ff6f7..2a72f3574 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs @@ -34,6 +34,7 @@ public static partial class Volume /// /// Name of the Volume. [SecurityCritical] + [Obsolete("Use Volume.QueryDosDevice")] public static string GetVolumeDeviceName(string volumeName) { return QueryDosDevice(volumeName); From e1e5b0a8cab16475e747eabf553b4d59a5078c6c Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Sun, 17 Jun 2018 21:39:04 +0200 Subject: [PATCH 119/133] Code improvement, renamed some unit tests. --- ...lphaFS_BackupFileStream_CreateInstance.cs} | 8 +-- ...viceInfo_UsingDevicePathFromSystemDrive.cs | 36 +++++++++- ...StorageDeviceInfo_UsingLogicalDrivePath.cs | 3 +- ...viceInfo_UsingVolumePathFromSystemDrive.cs | 34 ++++++++-- ...nstance_UsingDevicePathFromSystemDrive.cs} | 6 +- ...o.CreateInstance_UsingLogicalDrivePath.cs} | 2 +- ...reateInstance_UsingPhysicalDriveNumber.cs} | 5 +- ...nstance_UsingVolumePathFromSystemDrive.cs} | 4 +- ...e_UsingLogicalDrivePathFromSystemDrive.cs} | 8 +-- ... => AlphaFS_Shell32Info.CreateInstance.cs} | 8 +-- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 30 ++++----- ...eInstance_AnalyzeDirectoryInfoSecurity.cs} | 8 +-- ...yInfo.CreateInstance_ExistingDirectory.cs} | 8 +-- ...ectoryName_PropertyExistsShouldBeFalse.cs} | 8 +-- ...5Characters_ThrowsPathTooLongException.cs} | 8 +-- ...fo.CreateInstance_NonExistingDirectory.cs} | 8 +-- ...AsFileName_PropertyExistsShouldBeFalse.cs} | 8 +-- .../FileInfo.CreateInstance_ExistingFile.cs} | 8 +-- ...ileInfo.CreateInstance_NonExistingFile.cs} | 8 +-- .../FilesystemHelper.OpenPhysicalDrive.cs | 19 ++++++ .../Local.EnumeratePhysicalDisks.cs | 4 +- .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 25 ++++--- .../Storage/Local.GetStorageDeviceInfo.cs | 7 ++ .../Storage/Local.SetStorageDeviceInfoData.cs | 6 +- AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs | 4 ++ AlphaFS/Filesystem/File Class/File.Create.cs | 66 +++++++++++++++++++ .../NativeMethods.FileManagement.cs | 6 ++ .../Path Class/Path.GetRegularPath.cs | 6 +- .../NativeMethods.OperatingSystem.cs | 3 +- 29 files changed, 264 insertions(+), 90 deletions(-) rename AlphaFS.UnitTest/AlphaFS BackupFileStream Class/{AlphaFS_BackupFileStream_InitializeInstance.cs => AlphaFS_BackupFileStream_CreateInstance.cs} (87%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs => AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive.cs} (93%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs => AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath.cs} (97%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs => AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber.cs} (93%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs => AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive.cs} (94%) rename AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/{DriveInfo.InitializeInstance.cs => DriveInfo.CreateInstance_UsingLogicalDrivePathFromSystemDrive.cs} (91%) rename AlphaFS.UnitTest/AlphaFS Shell32 Class/{AlphaFS_Shell32Info.InitializeInstance.cs => AlphaFS_Shell32Info.CreateInstance.cs} (87%) rename AlphaFS.UnitTest/DirectoryInfo Class/{DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_AnalyzeDirectoryInfoSecurity.cs => DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_AnalyzeDirectoryInfoSecurity.cs} (93%) rename AlphaFS.UnitTest/DirectoryInfo Class/{DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingDirectory.cs => DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_ExistingDirectory.cs} (94%) rename AlphaFS.UnitTest/DirectoryInfo Class/{DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldbeFalse.cs => DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse.cs} (81%) rename AlphaFS.UnitTest/DirectoryInfo Class/{DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException.cs => DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException.cs} (84%) rename AlphaFS.UnitTest/DirectoryInfo Class/{DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_NonExistingDirectory.cs => DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_NonExistingDirectory.cs} (84%) rename AlphaFS.UnitTest/FileInfo Class/{FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse.cs => FileInfo.CreateInstance/FileInfo.CreateInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse.cs} (82%) rename AlphaFS.UnitTest/FileInfo Class/{FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingFile.cs => FileInfo.CreateInstance/FileInfo.CreateInstance_ExistingFile.cs} (95%) rename AlphaFS.UnitTest/FileInfo Class/{FileInfo.InitializeInstance/FileInfo.InitializeInstance_NonExistingFile.cs => FileInfo.CreateInstance/FileInfo.CreateInstance_NonExistingFile.cs} (86%) diff --git a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_CreateInstance.cs similarity index 87% rename from AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs rename to AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_CreateInstance.cs index 695215841..911cca85b 100644 --- a/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_InitializeInstance.cs +++ b/AlphaFS.UnitTest/AlphaFS BackupFileStream Class/AlphaFS_BackupFileStream_CreateInstance.cs @@ -30,14 +30,14 @@ public partial class AlphaFS_BackupFileStreamTest [TestMethod] - public void AlphaFS_BackupFileStream_InitializeInstance_LocalAndNetwork_Success() + public void AlphaFS_BackupFileStream_CreateInstance_LocalAndNetwork_Success() { - AlphaFS_BackupFileStream_InitializeInstance(false); - AlphaFS_BackupFileStream_InitializeInstance(true); + AlphaFS_BackupFileStream_CreateInstance_(false); + AlphaFS_BackupFileStream_CreateInstance_(true); } - private void AlphaFS_BackupFileStream_InitializeInstance(bool isNetwork) + private void AlphaFS_BackupFileStream_CreateInstance_(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs index 8fc3760c3..3f214a553 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs @@ -20,6 +20,7 @@ */ using System; +using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -38,6 +39,8 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingDevicePathFromSystemDrive_S var sourceDrive = UnitTestConstants.SysDrive; + var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); + var devicePath = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceDrive).DevicePath; Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); @@ -48,15 +51,42 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingDevicePathFromSystemDrive_S var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(devicePath); - UnitTestConstants.Dump(storageDeviceInfo); + UnitTestConstants.Dump(pDiskInfo); + + UnitTestConstants.Dump(pDiskInfo.StorageAdapterInfo, true); + + UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); + + UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); + Console.WriteLine(); - Assert.IsNotNull(storageDeviceInfo); - Assert.AreEqual(0, storageDeviceInfo.DeviceNumber); + Assert.IsNotNull(storageDeviceInfo); Assert.IsNotNull(pDiskInfo); + Assert.AreEqual(pDiskInfo.StorageDeviceInfo, storageDeviceInfo); + + + Assert.IsNotNull(pDiskInfo.LogicalDrives); + + Assert.IsNotNull(pDiskInfo.VolumeGuids); + + Assert.IsNotNull(pDiskInfo.DosDeviceName); + + + Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); + + Assert.IsTrue(pDiskInfo.ContainsVolume(sourceDrive)); + + + Assert.IsTrue(pDiskInfo.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase)); + + Assert.IsTrue(pDiskInfo.ContainsVolume(sourceVolume)); + + + Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs index 8f74f3778..0d0d847ab 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs @@ -63,9 +63,10 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingLogicalDrivePath_Success() UnitTestConstants.Dump(storageDeviceInfo); - Assert.IsNotNull(storageDeviceInfo); + Assert.AreNotEqual(0, storageDeviceInfo.PartitionNumber); + if (driveInfo.DriveType == System.IO.DriveType.Fixed) { diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs index 7136d733e..ae1c527a0 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs @@ -20,6 +20,7 @@ */ using System; +using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlphaFS.UnitTest @@ -48,17 +49,42 @@ public void AlphaFS_Device_GetStorageDeviceInfo_UsingVolumePathFromSystemDrive_S var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(sourceVolume); - UnitTestConstants.Dump(storageDeviceInfo); + UnitTestConstants.Dump(pDiskInfo); - Assert.IsNotNull(storageDeviceInfo); + UnitTestConstants.Dump(pDiskInfo.StorageAdapterInfo, true); + + UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); + + UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); + Console.WriteLine(); - Assert.AreEqual(0, storageDeviceInfo.DeviceNumber); + + Assert.IsNotNull(storageDeviceInfo); Assert.IsNotNull(pDiskInfo); - Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); Assert.AreEqual(pDiskInfo.StorageDeviceInfo, storageDeviceInfo); + + + Assert.IsNotNull(pDiskInfo.LogicalDrives); + + Assert.IsNotNull(pDiskInfo.VolumeGuids); + + Assert.IsNotNull(pDiskInfo.DosDeviceName); + + + Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); + + Assert.IsTrue(pDiskInfo.ContainsVolume(sourceDrive)); + + + Assert.IsTrue(pDiskInfo.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase)); + + Assert.IsTrue(pDiskInfo.ContainsVolume(sourceVolume)); + + + Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive.cs similarity index 93% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive.cs index dae10061c..f9536cf6d 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive.cs @@ -31,7 +31,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingDevicePathFromSystemDrive_Success() + public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingDevicePathFromSystemDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -65,7 +65,7 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingDevicePathFromSystem Assert.IsNotNull(pDiskInfo.VolumeGuids); - Assert.IsNotNull(pDiskInfo.DosDeviceName); + //Assert.IsNotNull(pDiskInfo.DosDeviceName); Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); @@ -78,7 +78,7 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingDevicePathFromSystem Assert.IsTrue(pDiskInfo.ContainsVolume(sourceVolume)); - Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); // Show all partition information. diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath.cs similarity index 97% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath.cs index 8cb24327b..7a190bcfa 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingLogicalDrivePath_Local_Success() + public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingLogicalDrivePath_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber.cs similarity index 93% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber.cs index e46c6cbeb..7be62fa4c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingPhysicalDriveNumber.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber.cs @@ -31,7 +31,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingPhysicalDriveNumber_Local_Success() + public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingPhysicalDriveNumber_Local_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -61,6 +61,9 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingPhysicalDriveNumber_ Assert.AreEqual(physicalDiskNumber, pDiskInfo.StoragePartitionInfo.DeviceNumber); + Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + + Console.WriteLine(); } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive.cs similarity index 94% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive.cs index bde206762..b6af4c077 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.InitializeInstanceUsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive.cs @@ -31,7 +31,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingVolumePathFromSystemDrive_Success() + public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingVolumePathFromSystemDrive_Success() { UnitTestConstants.PrintUnitTestHeader(false); @@ -76,7 +76,7 @@ public void AlphaFS_PhysicalDiskInfo_InitializeInstanceUsingVolumePathFromSystem Assert.IsTrue(pDiskInfo.ContainsVolume(sourceVolume)); - Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); // Show all partition information. diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/DriveInfo.InitializeInstance.cs b/AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/DriveInfo.CreateInstance_UsingLogicalDrivePathFromSystemDrive.cs similarity index 91% rename from AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/DriveInfo.InitializeInstance.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/DriveInfo.CreateInstance_UsingLogicalDrivePathFromSystemDrive.cs index 9d1d3255b..bef282d12 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/DriveInfo.InitializeInstance.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/DriveInfo Class/DriveInfo.CreateInstance_UsingLogicalDrivePathFromSystemDrive.cs @@ -30,14 +30,14 @@ public partial class DriveInfoTest [TestMethod] - public void DriveInfo_InitializeInstance_LocalAndNetwork_Success() + public void DriveInfo_CreateInstance_UsingLogicalDrivePathFromSystemDrive_LocalAndNetwork_Success() { - DriveInfo_InitializeInstance(false); - DriveInfo_InitializeInstance(true); + DriveInfo_CreateInstance_UsingLogicalDrivePathFromSystemDrive(false); + DriveInfo_CreateInstance_UsingLogicalDrivePathFromSystemDrive(true); } - private void DriveInfo_InitializeInstance(bool isNetwork) + private void DriveInfo_CreateInstance_UsingLogicalDrivePathFromSystemDrive(bool isNetwork) { UnitTestConstants.PrintUnitTestHeader(isNetwork); diff --git a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info.InitializeInstance.cs b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info.CreateInstance.cs similarity index 87% rename from AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info.InitializeInstance.cs rename to AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info.CreateInstance.cs index 7005438a0..b85bddacb 100644 --- a/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info.InitializeInstance.cs +++ b/AlphaFS.UnitTest/AlphaFS Shell32 Class/AlphaFS_Shell32Info.CreateInstance.cs @@ -30,14 +30,14 @@ public partial class AlphaFS_Shell32Test [TestMethod] - public void AlphaFS_Shell32Info_InitializeInstance_LocalAndNetwork_Success() + public void AlphaFS_Shell32Info_CreateInstance_LocalAndNetwork_Success() { - AlphaFS_Shell32Info_InitializeInstance(false); - AlphaFS_Shell32Info_InitializeInstance(true); + AlphaFS_Shell32Info_CreateInstance(false); + AlphaFS_Shell32Info_CreateInstance(true); } - private void AlphaFS_Shell32Info_InitializeInstance(bool isNetwork) + private void AlphaFS_Shell32Info_CreateInstance(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 2fea10b94..91e5caf26 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -144,8 +144,8 @@ AssemblyVersionInfo.cs - - + + @@ -155,9 +155,9 @@ - + - + @@ -168,7 +168,7 @@ - + @@ -182,7 +182,7 @@ - + @@ -232,7 +232,7 @@ - + @@ -393,19 +393,19 @@ - - + + - + - + @@ -462,10 +462,10 @@ - + - + @@ -495,9 +495,9 @@ - + - + diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_AnalyzeDirectoryInfoSecurity.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_AnalyzeDirectoryInfoSecurity.cs similarity index 93% rename from AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_AnalyzeDirectoryInfoSecurity.cs rename to AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_AnalyzeDirectoryInfoSecurity.cs index 8517ed77e..49e4f9938 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_AnalyzeDirectoryInfoSecurity.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_AnalyzeDirectoryInfoSecurity.cs @@ -31,14 +31,14 @@ public partial class DirectoryInfoTest [TestMethod] - public void AnalyzeDirectoryInfoSecurity_ShouldNotExist_LocalAndNetwork() + public void AnalyzeDirectoryInfoSecurity_CreateInstance_ShouldNotExist_LocalAndNetwork() { - AnalyzeDirectoryInfoSecurity_ShouldNotExist(false); - AnalyzeDirectoryInfoSecurity_ShouldNotExist(true); + AnalyzeDirectoryInfoSecurity_CreateInstance_ShouldNotExist(false); + AnalyzeDirectoryInfoSecurity_CreateInstance_ShouldNotExist(true); } - private void AnalyzeDirectoryInfoSecurity_ShouldNotExist(bool isNetwork) + private void AnalyzeDirectoryInfoSecurity_CreateInstance_ShouldNotExist(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingDirectory.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_ExistingDirectory.cs similarity index 94% rename from AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingDirectory.cs rename to AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_ExistingDirectory.cs index 66eaf53cd..57c679d14 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingDirectory.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_ExistingDirectory.cs @@ -30,14 +30,14 @@ public partial class DirectoryInfoTest [TestMethod] - public void DirectoryInfo_InitializeInstance_ExistingDirectory_LocalAndNetwork_Success() + public void DirectoryInfo_CreateInstance_ExistingDirectory_LocalAndNetwork_Success() { - DirectoryInfo_InitializeInstance_ExistingDirectory(false); - DirectoryInfo_InitializeInstance_ExistingDirectory(true); + DirectoryInfo_CreateInstance_ExistingDirectory(false); + DirectoryInfo_CreateInstance_ExistingDirectory(true); } - private void DirectoryInfo_InitializeInstance_ExistingDirectory(bool isNetwork) + private void DirectoryInfo_CreateInstance_ExistingDirectory(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldbeFalse.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse.cs similarity index 81% rename from AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldbeFalse.cs rename to AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse.cs index c4eb7ba15..2711662e6 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldbeFalse.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse.cs @@ -30,14 +30,14 @@ public partial class DirectoryInfoTest [TestMethod] - public void DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse_LocalAndNetwork_Success() + public void DirectoryInfo_CreateInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse_LocalAndNetwork_Success() { - DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse(false); - DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse(true); + DirectoryInfo_CreateInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse(false); + DirectoryInfo_CreateInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse(true); } - private void DirectoryInfo_InitializeInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse(bool isNetwork) + private void DirectoryInfo_CreateInstance_ExistingFileAsDirectoryName_PropertyExistsShouldBeFalse(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException.cs similarity index 84% rename from AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException.cs rename to AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException.cs index 4cecd4fa6..307d393a1 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException.cs @@ -30,14 +30,14 @@ public partial class DirectoryInfoTest [TestMethod] - public void DirectoryInfo_InitializeInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException_LocalAndNetwork_Success() + public void DirectoryInfo_CreateInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException_LocalAndNetwork_Success() { - DirectoryInfo_InitializeInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException(false); - DirectoryInfo_InitializeInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException(true); + DirectoryInfo_CreateInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException(false); + DirectoryInfo_CreateInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException(true); } - private void DirectoryInfo_InitializeInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException(bool isNetwork) + private void DirectoryInfo_CreateInstance_FolderNameGreaterThan255Characters_ThrowsPathTooLongException(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_NonExistingDirectory.cs b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_NonExistingDirectory.cs similarity index 84% rename from AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_NonExistingDirectory.cs rename to AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_NonExistingDirectory.cs index 12a13cd26..efd263313 100644 --- a/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.InitializeInstance/DirectoryInfo.InitializeInstance_NonExistingDirectory.cs +++ b/AlphaFS.UnitTest/DirectoryInfo Class/DirectoryInfo.CreateInstance/DirectoryInfo.CreateInstance_NonExistingDirectory.cs @@ -30,14 +30,14 @@ public partial class DirectoryInfoTest [TestMethod] - public void DirectoryInfo_InitializeInstance_NonExistingDirectory_LocalAndNetwork_Success() + public void DirectoryInfo_CreateInstance_NonExistingDirectory_LocalAndNetwork_Success() { - DirectoryInfo_InitializeInstance_NonExistingDirectory(false); - DirectoryInfo_InitializeInstance_NonExistingDirectory(true); + DirectoryInfo_CreateInstance_NonExistingDirectory(false); + DirectoryInfo_CreateInstance_NonExistingDirectory(true); } - private void DirectoryInfo_InitializeInstance_NonExistingDirectory(bool isNetwork) + private void DirectoryInfo_CreateInstance_NonExistingDirectory(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse.cs b/AlphaFS.UnitTest/FileInfo Class/FileInfo.CreateInstance/FileInfo.CreateInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse.cs similarity index 82% rename from AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse.cs rename to AlphaFS.UnitTest/FileInfo Class/FileInfo.CreateInstance/FileInfo.CreateInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse.cs index 0d2eb9f71..3657ad8c6 100644 --- a/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldbeFalse.cs +++ b/AlphaFS.UnitTest/FileInfo Class/FileInfo.CreateInstance/FileInfo.CreateInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse.cs @@ -30,14 +30,14 @@ public partial class FileInfoTest [TestMethod] - public void FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse_LocalAndNetwork_Success() + public void FileInfo_CreateInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse_LocalAndNetwork_Success() { - FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse(false); - FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse(true); + FileInfo_CreateInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse(false); + FileInfo_CreateInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse(true); } - private void FileInfo_InitializeInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse(bool isNetwork) + private void FileInfo_CreateInstance_ExistingDirectoryAsFileName_PropertyExistsShouldBeFalse(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingFile.cs b/AlphaFS.UnitTest/FileInfo Class/FileInfo.CreateInstance/FileInfo.CreateInstance_ExistingFile.cs similarity index 95% rename from AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingFile.cs rename to AlphaFS.UnitTest/FileInfo Class/FileInfo.CreateInstance/FileInfo.CreateInstance_ExistingFile.cs index 79184c3b2..5922cb948 100644 --- a/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_ExistingFile.cs +++ b/AlphaFS.UnitTest/FileInfo Class/FileInfo.CreateInstance/FileInfo.CreateInstance_ExistingFile.cs @@ -30,14 +30,14 @@ public partial class FileInfoTest [TestMethod] - public void FileInfo_InitializeInstance_ExistingFile_LocalAndNetwork_Success() + public void FileInfo_CreateInstance_ExistingFile_LocalAndNetwork_Success() { - FileInfo_InitializeInstance_ExistingFile(false); - FileInfo_InitializeInstance_ExistingFile(true); + FileInfo_CreateInstance_ExistingFile(false); + FileInfo_CreateInstance_ExistingFile(true); } - private void FileInfo_InitializeInstance_ExistingFile(bool isNetwork) + private void FileInfo_CreateInstance_ExistingFile(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_NonExistingFile.cs b/AlphaFS.UnitTest/FileInfo Class/FileInfo.CreateInstance/FileInfo.CreateInstance_NonExistingFile.cs similarity index 86% rename from AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_NonExistingFile.cs rename to AlphaFS.UnitTest/FileInfo Class/FileInfo.CreateInstance/FileInfo.CreateInstance_NonExistingFile.cs index df7d095cc..8e11c7fb4 100644 --- a/AlphaFS.UnitTest/FileInfo Class/FileInfo.InitializeInstance/FileInfo.InitializeInstance_NonExistingFile.cs +++ b/AlphaFS.UnitTest/FileInfo Class/FileInfo.CreateInstance/FileInfo.CreateInstance_NonExistingFile.cs @@ -30,14 +30,14 @@ public partial class FileInfoTest [TestMethod] - public void FileInfo_InitializeInstance_NonExistingFile_LocalAndNetwork_Success() + public void FileInfo_CreateInstance_NonExistingFile_LocalAndNetwork_Success() { - FileInfo_InitializeInstance_NonExistingFile(false); - FileInfo_InitializeInstance_NonExistingFile(true); + FileInfo_CreateInstance_NonExistingFile(false); + FileInfo_CreateInstance_NonExistingFile(true); } - private void FileInfo_InitializeInstance_NonExistingFile(bool isNetwork) + private void FileInfo_CreateInstance_NonExistingFile(bool isNetwork) { using (var tempRoot = new TemporaryDirectory(isNetwork)) { diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs index 6ff790ae2..e23f62008 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs @@ -60,5 +60,24 @@ public static SafeFileHandle OpenPhysicalDisk(string devicePath, FileSystemRight return File.CreateFileCore(null, devicePath, ExtendedFileAttributes.Normal | ExtendedFileAttributes.NoBuffering, null, FileMode.Open, fileSystemRights, FileShare.ReadWrite, false, false, PathFormat.LongFullPath); } + + + + + internal static SafeFileHandle OpenPhysicalDisk2(string devicePath, FileSystemRights fileSystemRights) + { + // fileSystemRights: If this parameter is 0 (FILE_ANY_ACCESS), the application can query certain metadata such as file, directory, or device attributes + // without accessing that file or device, even if GENERIC_READ access would have been denied. + // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + // + // + // When opening a volume or removable media drive (for example, a floppy disk drive or flash memory thumb drive), the lpFileName string should be the following form: "\\.\X:". + // Do not use a trailing backslash (\), which indicates the root directory of a drive. + // + // When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITE flag. + + + return File.CreateFileCore2(null, devicePath, ExtendedFileAttributes.Normal | ExtendedFileAttributes.NoBuffering, null, FileMode.Open, fileSystemRights, FileShare.ReadWrite, false, false, PathFormat.LongFullPath); + } } } diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index acaa91f3a..dd1f2f3da 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -55,12 +55,12 @@ internal static IEnumerable EnumeratePhysicalDisksCore(bool is { foreach (var deviceInfo in EnumerateDevicesCore(null, new []{DeviceGuid.Disk, DeviceGuid.CDRom}, false)) { - string unusedLocalDevicePath; + string unusedPhysicalDriveNumberPath; // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var storageDeviceInfo = GetStorageDeviceInfoNative(isElevated, true, deviceNumber, deviceInfo.DevicePath, out unusedLocalDevicePath); + var storageDeviceInfo = GetStorageDeviceInfoNative(isElevated, true, deviceNumber, deviceInfo.DevicePath, out unusedPhysicalDriveNumberPath); if (null == storageDeviceInfo) continue; diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index b3f1a2bde..3a69ce682 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -20,11 +20,8 @@ */ using System; -using System.Collections; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; -using System.Linq; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; @@ -103,8 +100,10 @@ private static void CreatePhysicalDiskInfoInstance(PhysicalDiskInfo physicalDisk // The StorageDeviceInfo is always needed as it contains the device- and partition number. + + string physicalDriveNumberPath; - physicalDiskInfo.StorageDeviceInfo = Local.GetStorageDeviceInfoNative(isElevated, isDevice, deviceNumber, localDevicePath, out localDevicePath); + physicalDiskInfo.StorageDeviceInfo = Local.GetStorageDeviceInfoNative(isElevated, isDevice, deviceNumber, localDevicePath, out physicalDriveNumberPath); if (null == physicalDiskInfo.StorageDeviceInfo) return; @@ -130,19 +129,29 @@ private static void CreatePhysicalDiskInfoInstance(PhysicalDiskInfo physicalDisk if (null == deviceInfo) return; - physicalDiskInfo.DeviceInfo = deviceInfo; + // physicalDriveNumberPath != null: The drive is opened using: "\\.\PhysicalDriveX" path format + // which is the device, not the volume/logical drive. + + var updatedDevicPath = physicalDriveNumberPath ?? localDevicePath; + + if (isDrive || isVolume) + { physicalDiskInfo.DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); + updatedDevicPath = localDevicePath; + //updatedDevicPath = Path.GlobalRootPrefix + deviceInfo.PhysicalDeviceObjectName.TrimStart('\\'); + } + - using (var safeFileHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + using (var safeFileHandle = FileSystemHelper.OpenPhysicalDisk(updatedDevicPath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) { - physicalDiskInfo.StorageAdapterInfo = Local.GetStorageAdapterInfoNative(safeFileHandle, deviceNumber, localDevicePath, deviceInfo.BusReportedDeviceDescription); + physicalDiskInfo.StorageAdapterInfo = Local.GetStorageAdapterInfoNative(safeFileHandle, deviceNumber, updatedDevicPath, deviceInfo.BusReportedDeviceDescription); - physicalDiskInfo.StoragePartitionInfo = Local.GetStoragePartitionInfoNative(safeFileHandle, deviceNumber, localDevicePath); + physicalDiskInfo.StoragePartitionInfo = Local.GetStoragePartitionInfoNative(safeFileHandle, deviceNumber, updatedDevicPath); } diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs index 3e5f4e147..03e62b622 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs @@ -113,6 +113,9 @@ internal static StorageDeviceInfo GetStorageDeviceInfoNative(bool isElevated, bo Retry: + // Accessing volume: "\\.\D" on a dynamic disk fails with ERROR_INVALID_FUNCTION. + // On retry, the drive is accessed using the: "\\.\PhysicalDriveX" path format which is the device, not the volume/logical drive. + using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) { int lastError; @@ -128,6 +131,10 @@ internal static StorageDeviceInfo GetStorageDeviceInfoNative(bool isElevated, bo SetStorageDeviceInfoData(isElevated, isDevice, safeHandle, localDevicePath, storageDeviceInfo); + + if (!localDevicePath.StartsWith(Path.PhysicalDrivePrefix, StringComparison.OrdinalIgnoreCase)) + localDevicePath = null; + return storageDeviceInfo; } diff --git a/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs b/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs index 65a2da258..25289a312 100644 --- a/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs +++ b/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs @@ -58,13 +58,13 @@ private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, Saf if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.ProductRevision) || storageDeviceInfo.ProductRevision.Length == 1) - storageDeviceInfo.ProductRevision = null; + storageDeviceInfo.ProductRevision = string.Empty; if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.SerialNumber) || storageDeviceInfo.SerialNumber.Length == 1) - storageDeviceInfo.SerialNumber = null; + storageDeviceInfo.SerialNumber = string.Empty; if (Utils.IsNullOrWhiteSpace(storageDeviceInfo.VendorId) || storageDeviceInfo.VendorId.Length == 1) - storageDeviceInfo.VendorId = null; + storageDeviceInfo.VendorId = string.Empty; } diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs b/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs index 3e0b26c4a..28ce049d2 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs @@ -19,6 +19,7 @@ * THE SOFTWARE. */ +using System; using System.Security; using Microsoft.Win32.SafeHandles; @@ -30,6 +31,7 @@ public static partial class Volume /// A path that contains the root directory. /// Returns a instance describing the volume associatied with the specified root directory. [SecurityCritical] + [Obsolete("Use: new VolumeInfo(volumePath)")] public static VolumeInfo GetVolumeInfo(string volumePath) { return new VolumeInfo(volumePath, true, false); @@ -41,6 +43,7 @@ public static VolumeInfo GetVolumeInfo(string volumePath) /// A path that contains the root directory. /// true suppress any Exception that might be thrown as a result from a failure, such as unavailable resources. [SecurityCritical] + [Obsolete("Use: new VolumeInfo(volumePath, true, continueOnException)")] public static VolumeInfo GetVolumeInfo(string volumePath, bool continueOnException) { return new VolumeInfo(volumePath, true, continueOnException); @@ -51,6 +54,7 @@ public static VolumeInfo GetVolumeInfo(string volumePath, bool continueOnExcepti /// An instance to a handle. /// Returns a instance describing the volume associatied with the specified root directory. [SecurityCritical] + [Obsolete("Use: new VolumeInfo(volumeHandle, true, true)")] public static VolumeInfo GetVolumeInfo(SafeFileHandle volumeHandle) { return new VolumeInfo(volumeHandle, true, true); diff --git a/AlphaFS/Filesystem/File Class/File.Create.cs b/AlphaFS/Filesystem/File Class/File.Create.cs index a89c20db0..67bbfeb71 100644 --- a/AlphaFS/Filesystem/File Class/File.Create.cs +++ b/AlphaFS/Filesystem/File Class/File.Create.cs @@ -366,6 +366,72 @@ internal static SafeFileHandle CreateFileCore(KernelTransaction transaction, str } } + + + internal static SafeFileHandle CreateFileCore2(KernelTransaction transaction, 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.NtCreateFile(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(); + + Utils.IsValidHandle(safeHandle, lastError, pathLp, !continueOnException); + + + if (isAppend) + { + var success = NativeMethods.SetFilePointerEx(safeHandle, 0, IntPtr.Zero, SeekOrigin.End); + + lastError = Marshal.GetLastWin32Error(); + + if (!success) + { + if (!safeHandle.IsClosed) + safeHandle.Close(); + + NativeError.ThrowException(lastError, path); + } + } + + return safeHandle; + } + } + #endregion // CreateFileCore } } diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs index 86646078b..f68cd6f4d 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs @@ -101,6 +101,12 @@ internal static partial class NativeMethods [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW"), SuppressUnmanagedCodeSecurity] internal static extern SafeFileHandle CreateFile([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] FileSystemRights dwDesiredAccess, [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, [MarshalAs(UnmanagedType.LPStruct)] Security.NativeMethods.SecurityAttributes lpSecurityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, [MarshalAs(UnmanagedType.U4)] ExtendedFileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile); + + [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] + internal static extern SafeFileHandle NtCreateFile([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] FileSystemRights dwDesiredAccess, [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, [MarshalAs(UnmanagedType.LPStruct)] Security.NativeMethods.SecurityAttributes lpSecurityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, [MarshalAs(UnmanagedType.U4)] ExtendedFileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile); + + /// /// Creates or opens a file or I/O device. 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. diff --git a/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs b/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs index be4f8acd8..0e204b4f2 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs @@ -64,7 +64,7 @@ internal static string GetRegularPathCore(string path, GetFullPathOptions option if (options != GetFullPathOptions.None) path = ApplyFullPathOptions(path, options); - + if (path.StartsWith(DosDeviceUncPrefix, StringComparison.OrdinalIgnoreCase)) return UncPrefix + path.Substring(DosDeviceUncPrefix.Length); @@ -78,7 +78,9 @@ internal static string GetRegularPathCore(string path, GetFullPathOptions option return path.Substring(NonInterpretedPathPrefix.Length); - return path.StartsWith(GlobalRootPrefix, StringComparison.OrdinalIgnoreCase) || path.StartsWith(VolumePrefix, StringComparison.OrdinalIgnoreCase) || !path.StartsWith(LongPathPrefix, StringComparison.Ordinal) + return path.StartsWith(GlobalRootPrefix, StringComparison.OrdinalIgnoreCase) || path.StartsWith(VolumePrefix, StringComparison.OrdinalIgnoreCase) || + path.StartsWith(PhysicalDrivePrefix, StringComparison.OrdinalIgnoreCase) || !path.StartsWith(LongPathPrefix, StringComparison.Ordinal) + ? path : (path.StartsWith(LongPathUncPrefix, StringComparison.OrdinalIgnoreCase) ? UncPrefix + path.Substring(LongPathUncPrefix.Length) : path.Substring(LongPathPrefix.Length)); } diff --git a/AlphaFS/OperatingSystem/NativeMethods.OperatingSystem.cs b/AlphaFS/OperatingSystem/NativeMethods.OperatingSystem.cs index 04214dc4e..f1d163e69 100644 --- a/AlphaFS/OperatingSystem/NativeMethods.OperatingSystem.cs +++ b/AlphaFS/OperatingSystem/NativeMethods.OperatingSystem.cs @@ -74,7 +74,8 @@ internal struct SYSTEM_INFO /// The RtlGetVersion routine returns version information about the currently running operating system. /// RtlGetVersion returns STATUS_SUCCESS. /// Available starting with Windows 2000. - [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule"), DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] + [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool RtlGetVersion([MarshalAs(UnmanagedType.Struct)] ref RTL_OSVERSIONINFOEXW lpVersionInformation); From c2a3d3c5884902eec7b9c416816a3121d3447263 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 18 Jun 2018 14:07:57 +0200 Subject: [PATCH 120/133] Code improvement, moved some files. --- ...isks_ReturnsStorageDeviceInfoForDevice.cs} | 25 ++- ...pterInfo_UsingDevicePathFromSystemDrive.cs | 59 ------ ...torageAdapterInfo_UsingLogicalDrivePath.cs | 77 -------- ...pterInfo_UsingVolumePathFromSystemDrive.cs | 60 ------ ...viceInfo_UsingDevicePathFromSystemDrive.cs | 92 ---------- ...StorageDeviceInfo_UsingLogicalDrivePath.cs | 98 ---------- ...viceInfo_UsingVolumePathFromSystemDrive.cs | 90 --------- ...tionInfo_UsingDevicePathFromSystemDrive.cs | 68 ------- ...ragePartitionInfo_UsingLogicalDrivePath.cs | 101 ----------- ...tionInfo_UsingVolumePathFromSystemDrive.cs | 83 --------- ...rive_ReturnsStorageDeviceInfoForDevice.cs} | 23 ++- ...Path_ReturnsStorageDeviceInfoForVolume.cs} | 24 +-- ...mber_ReturnsStorageDeviceInfoForDevice.cs} | 27 ++- ...rive_ReturnsStorageDeviceInfoForVolume.cs} | 20 +- AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 19 +- AlphaFS/AlphaFS.csproj | 26 +-- .../Device.FileSystemHelper.cs | 0 AlphaFS/Device/{ => Local}/Device.Local.cs | 0 .../{ => Local}/Local.EnumerateDevices.cs | 26 +-- .../{ => Local}/Local.GetDeviceIoData.cs | 0 .../Local.GetStorageAdapterInfo.cs | 4 +- .../Local.GetStorageDeviceInfo.cs | 4 +- .../Local.GetStoragePartitionInfo.cs | 4 +- .../{ => Local}/Local.GetVolumeDiskExtents.cs | 0 .../{ => Local}/Local.InvokeDeviceIoData.cs | 0 .../Local.OpenDevice.cs} | 6 +- .../Local.SetStorageDeviceInfoData.cs | 0 AlphaFS/Device/Native Other/IoControlCode.cs | 21 ++- .../{IoCtlMethod.cs => IoControlMethod.cs} | 2 +- .../Local.EnumeratePhysicalDisks.cs | 8 +- .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 171 +++++++----------- .../Storage/Device.StorageDeviceInfo.cs | 6 +- 32 files changed, 216 insertions(+), 928 deletions(-) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_Device.EnumeratePhysicalDisks.cs => AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs} (76%) delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs delete mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive.cs => AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive_ReturnsStorageDeviceInfoForDevice.cs} (82%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath.cs => AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs} (79%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber.cs => AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs} (80%) rename AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/{AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive.cs => AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive_ReturnsStorageDeviceInfoForVolume.cs} (90%) rename AlphaFS/Device/{ => FileSystemHelper}/Device.FileSystemHelper.cs (100%) rename AlphaFS/Device/{ => Local}/Device.Local.cs (100%) rename AlphaFS/Device/{ => Local}/Local.EnumerateDevices.cs (99%) rename AlphaFS/Device/{ => Local}/Local.GetDeviceIoData.cs (100%) rename AlphaFS/Device/{Storage => Local}/Local.GetStorageAdapterInfo.cs (97%) rename AlphaFS/Device/{Storage => Local}/Local.GetStorageDeviceInfo.cs (97%) rename AlphaFS/Device/{Storage => Local}/Local.GetStoragePartitionInfo.cs (97%) rename AlphaFS/Device/{ => Local}/Local.GetVolumeDiskExtents.cs (100%) rename AlphaFS/Device/{ => Local}/Local.InvokeDeviceIoData.cs (100%) rename AlphaFS/Device/{FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs => Local/Local.OpenDevice.cs} (94%) rename AlphaFS/Device/{Storage => Local}/Local.SetStorageDeviceInfoData.cs (100%) rename AlphaFS/Device/Native Other/{IoCtlMethod.cs => IoControlMethod.cs} (97%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs similarity index 76% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs index 94ff091b9..338ae54ca 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs @@ -31,7 +31,7 @@ public partial class EnumerationTest [TestMethod] - public void AlphaFS_Device_EnumeratePhysicalDisks_Success() + public void AlphaFS_Device_EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice() { UnitTestConstants.PrintUnitTestHeader(false); @@ -64,7 +64,26 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - Assert.IsNull(pDiskInfo.DosDeviceName); + Assert.IsNotNull(pDiskInfo); + + Assert.IsNotNull(pDiskInfo.LogicalDrives); + + Assert.IsNotNull(pDiskInfo.VolumeGuids); + + + // DosDeviceName should be the same for device. + + Assert.AreEqual(pDiskInfo.DosDeviceName, pDiskInfo.PhysicalDeviceObjectName); + + + // PartitionNumber should be -1 for CDRom. + + if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) + Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + + // PartitionNumber should be 0 for device. + else + Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); driveCount++; @@ -73,7 +92,7 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_Success() } - Assert.IsTrue(pDrives.Length > 0, "No physical disks enumerated, but it is expected."); + Assert.IsTrue(driveCount > 0, "No physical disks enumerated, but it is expected."); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs deleted file mode 100644 index 7937371b2..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingDevicePathFromSystemDrive.cs +++ /dev/null @@ -1,59 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Device_GetStorageAdapterInfo_UsingDevicePathFromSystemDrive_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var deviceCount = 0; - - var sourceDrive = UnitTestConstants.SysDrive; - var devicePath = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceDrive).DevicePath; - - Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); - - - var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(devicePath); - - var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(devicePath); - - - UnitTestConstants.Dump(storageAdapterInfo); - - Assert.IsNotNull(storageAdapterInfo); - - Assert.IsNotNull(pDiskInfo); - - Assert.AreEqual(pDiskInfo.StorageAdapterInfo, storageAdapterInfo); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs deleted file mode 100644 index 194ad978d..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingLogicalDrivePath.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Device_GetStorageAdapterInfo_UsingLogicalDrivePath_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var gotAdapter = false; - var driveCount = 0; - - - foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) - { - // Works with System.IO.DriveType.CDRom. - - // System.UnauthorizedAccessException: (5) Access is denied. - if (driveInfo.DriveType == System.IO.DriveType.Network) - { - Console.WriteLine("#{0:000}\tSkipped Network drive: [{1}]\n", ++driveCount, driveInfo.Name); - continue; - } - - if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) - { - Console.WriteLine("#{0:000}\tSkipped NoRootDirectory drive: [{1}]\n", ++driveCount, driveInfo.Name); - continue; - } - - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); - - - var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(driveInfo.Name); - - - UnitTestConstants.Dump(storageAdapterInfo); - - Assert.IsNotNull(storageAdapterInfo); - - gotAdapter = true; - - Console.WriteLine(); - } - - - Assert.IsTrue(gotAdapter); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs deleted file mode 100644 index 08f4ebf3e..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageAdapterInfo_UsingVolumePathFromSystemDrive.cs +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Device_GetStorageAdapterInfo_UsingVolumePathFromSystemDrive_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var volumeCount = 0; - - var sourceDrive = UnitTestConstants.SysDrive; - - var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - - Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]", ++volumeCount, sourceVolume); - - - var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceVolume); - - var storageAdapterInfo = Alphaleonis.Win32.Device.Local.GetStorageAdapterInfo(sourceVolume); - - - UnitTestConstants.Dump(storageAdapterInfo); - - Assert.IsNotNull(storageAdapterInfo); - - Assert.IsNotNull(pDiskInfo); - - Assert.AreEqual(pDiskInfo.StorageAdapterInfo, storageAdapterInfo); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs deleted file mode 100644 index 3f214a553..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingDevicePathFromSystemDrive.cs +++ /dev/null @@ -1,92 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_PhysicalDiskInfoTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Device_GetStorageDeviceInfo_UsingDevicePathFromSystemDrive_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var deviceCount = 0; - - var sourceDrive = UnitTestConstants.SysDrive; - - var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - - var devicePath = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceDrive).DevicePath; - - Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); - - - var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(devicePath); - - var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(devicePath); - - - UnitTestConstants.Dump(pDiskInfo); - - UnitTestConstants.Dump(pDiskInfo.StorageAdapterInfo, true); - - UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); - - UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - Console.WriteLine(); - - - Assert.IsNotNull(storageDeviceInfo); - - Assert.IsNotNull(pDiskInfo); - - - Assert.AreEqual(pDiskInfo.StorageDeviceInfo, storageDeviceInfo); - - - Assert.IsNotNull(pDiskInfo.LogicalDrives); - - Assert.IsNotNull(pDiskInfo.VolumeGuids); - - Assert.IsNotNull(pDiskInfo.DosDeviceName); - - - Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); - - Assert.IsTrue(pDiskInfo.ContainsVolume(sourceDrive)); - - - Assert.IsTrue(pDiskInfo.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase)); - - Assert.IsTrue(pDiskInfo.ContainsVolume(sourceVolume)); - - - Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs deleted file mode 100644 index 0d0d847ab..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingLogicalDrivePath.cs +++ /dev/null @@ -1,98 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Device_GetStorageDeviceInfo_UsingLogicalDrivePath_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var gotDisk = false; - var driveCount = 0; - - - foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) - { - // Works with System.IO.DriveType.CDRom. - - // System.UnauthorizedAccessException: (5) Access is denied. - if (driveInfo.DriveType == System.IO.DriveType.Network) - { - Console.WriteLine("#{0:000}\tSkipped Network drive: [{1}]\n", ++driveCount, driveInfo.Name); - continue; - } - - if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) - { - Console.WriteLine("#{0:000}\tSkipped NoRootDirectory drive: [{1}]\n", ++driveCount, driveInfo.Name); - continue; - } - - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); - - - var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(driveInfo.Name); - - - UnitTestConstants.Dump(storageDeviceInfo); - - Assert.IsNotNull(storageDeviceInfo); - - Assert.AreNotEqual(0, storageDeviceInfo.PartitionNumber); - - - if (driveInfo.DriveType == System.IO.DriveType.Fixed) - { - gotDisk = true; - Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.Disk, storageDeviceInfo.DeviceType); - } - - - // For CDRom, the PartitionNumber is always - 1. - - if (driveInfo.DriveType == System.IO.DriveType.CDRom) - { - Assert.AreEqual(-1, storageDeviceInfo.PartitionNumber); - - Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.CDRom, storageDeviceInfo.DeviceType); - } - - else - Assert.AreNotEqual(-1, storageDeviceInfo.PartitionNumber); - - - Console.WriteLine(); - } - - - Assert.IsTrue(gotDisk); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs deleted file mode 100644 index ae1c527a0..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStorageDeviceInfo_UsingVolumePathFromSystemDrive.cs +++ /dev/null @@ -1,90 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 AlphaFS_PhysicalDiskInfoTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Device_GetStorageDeviceInfo_UsingVolumePathFromSystemDrive_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var volumeCount = 0; - - var sourceDrive = UnitTestConstants.SysDrive; - - var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - - Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]", ++volumeCount, sourceVolume); - - - var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceVolume); - - var storageDeviceInfo = Alphaleonis.Win32.Device.Local.GetStorageDeviceInfo(sourceVolume); - - - UnitTestConstants.Dump(pDiskInfo); - - UnitTestConstants.Dump(pDiskInfo.StorageAdapterInfo, true); - - UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); - - UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - Console.WriteLine(); - - - Assert.IsNotNull(storageDeviceInfo); - - Assert.IsNotNull(pDiskInfo); - - - Assert.AreEqual(pDiskInfo.StorageDeviceInfo, storageDeviceInfo); - - - Assert.IsNotNull(pDiskInfo.LogicalDrives); - - Assert.IsNotNull(pDiskInfo.VolumeGuids); - - Assert.IsNotNull(pDiskInfo.DosDeviceName); - - - Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); - - Assert.IsTrue(pDiskInfo.ContainsVolume(sourceDrive)); - - - Assert.IsTrue(pDiskInfo.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase)); - - Assert.IsTrue(pDiskInfo.ContainsVolume(sourceVolume)); - - - Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs deleted file mode 100644 index bd6616919..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingDevicePathFromSystemDrive.cs +++ /dev/null @@ -1,68 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Device_GetStoragePartitionInfo_UsingDevicePathFromSystemDrive_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var deviceCount = 0; - - var sourceDrive = UnitTestConstants.SysDrive; - - var devicePath = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceDrive).DevicePath; - - Console.WriteLine("#{0:000}\tInput Device Path: [{1}]", ++deviceCount, devicePath); - - - var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(devicePath); - - - UnitTestConstants.Dump(storagePartitionInfo); - - Assert.IsNotNull(storagePartitionInfo); - - Assert.AreEqual(0, storagePartitionInfo.DeviceNumber); - - - // Show all partition information. - - if (null != storagePartitionInfo.GptPartitionInfo) - foreach (var partition in storagePartitionInfo.GptPartitionInfo) - UnitTestConstants.Dump(partition, true); - - - if (null != storagePartitionInfo.MbrPartitionInfo) - foreach (var partition in storagePartitionInfo.MbrPartitionInfo) - UnitTestConstants.Dump(partition, true); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs deleted file mode 100644 index eb8f83086..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingLogicalDrivePath.cs +++ /dev/null @@ -1,101 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Device_GetStoragePartitionInfo_UsingLogicalDrivePath_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var gotDisk = false; - var driveCount = 0; - - - foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) - { - // Works with System.IO.DriveType.CDRom. - - // System.UnauthorizedAccessException: (5) Access is denied. - if (driveInfo.DriveType == System.IO.DriveType.Network) - { - Console.WriteLine("#{0:000}\tSkipped Network Drive: [{1}]\n", ++driveCount, driveInfo.Name); - continue; - } - - if (driveInfo.DriveType == System.IO.DriveType.NoRootDirectory) - { - Console.WriteLine("#{0:000}\tSkipped NoRootDirectory Drive: [{1}]\n", ++driveCount, driveInfo.Name); - continue; - } - - - var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(driveInfo.Name); - - //if (null == storagePartitionInfo) - //{ - // Console.WriteLine("#{0:000}\tSkipped Logical Drive: [{1}]\n", ++driveCount, driveInfo.Name); - // continue; - //} - - Console.WriteLine("#{0:000}\tInput Logical Drive Path: [{1}]", ++driveCount, driveInfo.Name); - - UnitTestConstants.Dump(storagePartitionInfo); - - - Assert.IsNotNull(storagePartitionInfo); - - // Show all partition information. - - if (null != storagePartitionInfo.GptPartitionInfo) - { - gotDisk = true; - - foreach (var partition in storagePartitionInfo.GptPartitionInfo) - UnitTestConstants.Dump(partition, true); - } - - - if (null != storagePartitionInfo.MbrPartitionInfo) - { - gotDisk = true; - - foreach (var partition in storagePartitionInfo.MbrPartitionInfo) - UnitTestConstants.Dump(partition, true); - } - - - Console.WriteLine(); - } - - - Assert.IsTrue(gotDisk); - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs deleted file mode 100644 index 8ed1013f1..000000000 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.GetStoragePartitionInfo_UsingVolumePathFromSystemDrive.cs +++ /dev/null @@ -1,83 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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_PhysicalDiskInfoTest - { - // Pattern: ___ - - - [TestMethod] - public void AlphaFS_Device_GetStoragePartitionInfo_UsingVolumePathFromSystemDrive_Success() - { - UnitTestConstants.PrintUnitTestHeader(false); - - var volumeCount = 0; - - var sourceDrive = UnitTestConstants.SysDrive; - - var sourceVolume = Alphaleonis.Win32.Filesystem.Volume.GetVolumeGuid(sourceDrive); - - Console.WriteLine("#{0:000}\tInput Volume Path: [{1}]", ++volumeCount, sourceVolume); - - - var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(sourceVolume); - - var storagePartitionInfo = Alphaleonis.Win32.Device.Local.GetStoragePartitionInfo(sourceVolume); - - - UnitTestConstants.Dump(storagePartitionInfo); - - Assert.IsNotNull(storagePartitionInfo); - - Assert.AreEqual(0, storagePartitionInfo.DeviceNumber); - - - Assert.IsNotNull(pDiskInfo); - - Assert.AreEqual(pDiskInfo.StorageDeviceInfo.DeviceNumber, storagePartitionInfo.DeviceNumber); - - Assert.AreEqual(pDiskInfo.StoragePartitionInfo, storagePartitionInfo); - - Assert.IsNotNull(pDiskInfo.DosDeviceName); - - - // Show all partition information. - - if (null != storagePartitionInfo.GptPartitionInfo) - { - foreach (var partition in storagePartitionInfo.GptPartitionInfo) - UnitTestConstants.Dump(partition, true); - } - - - if (null != storagePartitionInfo.MbrPartitionInfo) - { - foreach (var partition in storagePartitionInfo.MbrPartitionInfo) - UnitTestConstants.Dump(partition, true); - } - } - } -} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive_ReturnsStorageDeviceInfoForDevice.cs similarity index 82% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive_ReturnsStorageDeviceInfoForDevice.cs index f9536cf6d..832c52c98 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive_ReturnsStorageDeviceInfoForDevice.cs @@ -31,7 +31,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingDevicePathFromSystemDrive_Success() + public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingDevicePathFromSystemDrive_ReturnsStorageDeviceInfoForDevice() { UnitTestConstants.PrintUnitTestHeader(false); @@ -56,7 +56,6 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingDevicePathFromSystemDri UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - Console.WriteLine(); Assert.IsNotNull(pDiskInfo); @@ -65,8 +64,23 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingDevicePathFromSystemDri Assert.IsNotNull(pDiskInfo.VolumeGuids); - //Assert.IsNotNull(pDiskInfo.DosDeviceName); + // DosDeviceName should be the same for device. + + Assert.AreEqual(pDiskInfo.DosDeviceName, pDiskInfo.PhysicalDeviceObjectName); + + + // PartitionNumber should be -1 for CDRom. + + if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) + Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + + // PartitionNumber should be > 0 for logical drive because it is not the device. + else + Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + + + // ContainsVolume should find volumes/logical drives. Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); @@ -78,9 +92,6 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingDevicePathFromSystemDri Assert.IsTrue(pDiskInfo.ContainsVolume(sourceVolume)); - Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); - - // Show all partition information. if (null != pDiskInfo.StoragePartitionInfo && null != pDiskInfo.StoragePartitionInfo.GptPartitionInfo) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs similarity index 79% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs index 7a190bcfa..86efeb10d 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs @@ -30,7 +30,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingLogicalDrivePath_Local_Success() + public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume() { UnitTestConstants.PrintUnitTestHeader(false); @@ -39,8 +39,6 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingLogicalDrivePath_Local_ foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { - // Works with System.IO.DriveType.CDRom. - // System.UnauthorizedAccessException: (5) Access is denied. if (driveInfo.DriveType == System.IO.DriveType.Network) { @@ -80,30 +78,28 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingLogicalDrivePath_Local_ Assert.IsNotNull(pDiskInfo.VolumeGuids); - Assert.IsNotNull(pDiskInfo.DosDeviceName); + // DosDeviceName should be different for logical drive. - if (pDiskInfo.StorageDeviceInfo.PartitionNumber > 0) - Assert.IsNotNull(pDiskInfo.StoragePartitionInfo); + Assert.AreNotEqual(pDiskInfo.DosDeviceName, pDiskInfo.PhysicalDeviceObjectName); - // For CDRom, the PartitionNumber is always -1. + // PartitionNumber should be -1 for CDRom. if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) - { Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(Alphaleonis.Win32.Device.StorageDeviceType.CDRom, pDiskInfo.StorageDeviceInfo.DeviceType); - } + // PartitionNumber should be > 0 for logical drive because it is not the device. else - Assert.AreNotEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + + - var physicalDiskNumber = pDiskInfo.StorageDeviceInfo.DeviceNumber; + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.DeviceNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); - Assert.AreEqual(physicalDiskNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.DeviceNumber, pDiskInfo.StoragePartitionInfo.DeviceNumber); - Assert.AreEqual(physicalDiskNumber, pDiskInfo.StoragePartitionInfo.DeviceNumber); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs similarity index 80% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs index 7be62fa4c..e79d48c6a 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs @@ -22,6 +22,7 @@ using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Globalization; namespace AlphaFS.UnitTest { @@ -31,7 +32,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingPhysicalDriveNumber_Local_Success() + public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice() { UnitTestConstants.PrintUnitTestHeader(false); @@ -42,7 +43,7 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingPhysicalDriveNumber_Loc for (var physicalDiskNumber = 0; physicalDiskNumber < physicalDisks.Length; physicalDiskNumber++) { - Console.WriteLine("#{0:000}\tInput Physical Disk Number: [{1}]", physicalDiskNumber + 1, physicalDiskNumber); + Console.WriteLine("#{0:000}\tInput Physical Disk Path: [{1}{2}]", physicalDiskNumber + 1, Alphaleonis.Win32.Filesystem.Path.PhysicalDrivePrefix, physicalDiskNumber); var pDiskInfo = new Alphaleonis.Win32.Device.PhysicalDiskInfo(physicalDiskNumber); @@ -55,15 +56,31 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingPhysicalDriveNumber_Loc UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - Assert.AreEqual(physicalDiskNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); + Assert.IsNotNull(pDiskInfo); - Assert.AreEqual(physicalDiskNumber, pDiskInfo.StorageDeviceInfo.DeviceNumber); + Assert.IsNotNull(pDiskInfo.LogicalDrives); - Assert.AreEqual(physicalDiskNumber, pDiskInfo.StoragePartitionInfo.DeviceNumber); + Assert.IsNotNull(pDiskInfo.VolumeGuids); + + + // DosDeviceName should contain "X\DR" for device. + + Assert.IsTrue(pDiskInfo.DosDeviceName.Contains(string.Format(CultureInfo.InvariantCulture, @"{0}\DR", physicalDiskNumber))); + + + // PartitionNumber should be 0 for device. Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + + Assert.AreEqual(physicalDiskNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); + + Assert.AreEqual(physicalDiskNumber, pDiskInfo.StorageDeviceInfo.DeviceNumber); + + Assert.AreEqual(physicalDiskNumber, pDiskInfo.StoragePartitionInfo.DeviceNumber); + + Console.WriteLine(); } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive_ReturnsStorageDeviceInfoForVolume.cs similarity index 90% rename from AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive.cs rename to AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive_ReturnsStorageDeviceInfoForVolume.cs index b6af4c077..94a7fc7ed 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingVolumePathFromSystemDrive_ReturnsStorageDeviceInfoForVolume.cs @@ -31,7 +31,7 @@ public partial class AlphaFS_PhysicalDiskInfoTest [TestMethod] - public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingVolumePathFromSystemDrive_Success() + public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingVolumePathFromSystemDrive_ReturnsStorageDeviceInfoForVolume() { UnitTestConstants.PrintUnitTestHeader(false); @@ -54,8 +54,7 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingVolumePathFromSystemDri UnitTestConstants.Dump(pDiskInfo.StorageDeviceInfo, true); UnitTestConstants.Dump(pDiskInfo.StoragePartitionInfo, true); - Console.WriteLine(); - + Assert.IsNotNull(pDiskInfo); @@ -63,8 +62,18 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingVolumePathFromSystemDri Assert.IsNotNull(pDiskInfo.VolumeGuids); - Assert.IsNotNull(pDiskInfo.DosDeviceName); + // DosDeviceName should be different for volume. + + Assert.AreNotEqual(pDiskInfo.DosDeviceName, pDiskInfo.PhysicalDeviceObjectName); + + + // PartitionNumber should be > 0 for volume because it is not the device. + + Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + + + // ContainsVolume should find volumes/logical drives. Assert.IsTrue(pDiskInfo.LogicalDrives.Contains(sourceDrive, StringComparer.OrdinalIgnoreCase)); @@ -74,9 +83,6 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingVolumePathFromSystemDri Assert.IsTrue(pDiskInfo.VolumeGuids.Contains(sourceVolume, StringComparer.OrdinalIgnoreCase)); Assert.IsTrue(pDiskInfo.ContainsVolume(sourceVolume)); - - - Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); // Show all partition information. diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index 91e5caf26..baf85efff 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -143,21 +143,12 @@ AssemblyVersionInfo.cs - - - - - - - - - - - - - + + + + - + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index b907a74dc..a4c1b7fc1 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -196,27 +196,27 @@ True - + - - + + - - - + + + - + - + - + @@ -253,7 +253,7 @@ - + @@ -356,7 +356,7 @@ - + @@ -441,7 +441,7 @@ - + @@ -743,7 +743,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Device.FileSystemHelper.cs b/AlphaFS/Device/FileSystemHelper/Device.FileSystemHelper.cs similarity index 100% rename from AlphaFS/Device/Device.FileSystemHelper.cs rename to AlphaFS/Device/FileSystemHelper/Device.FileSystemHelper.cs diff --git a/AlphaFS/Device/Device.Local.cs b/AlphaFS/Device/Local/Device.Local.cs similarity index 100% rename from AlphaFS/Device/Device.Local.cs rename to AlphaFS/Device/Local/Device.Local.cs diff --git a/AlphaFS/Device/Local.EnumerateDevices.cs b/AlphaFS/Device/Local/Local.EnumerateDevices.cs similarity index 99% rename from AlphaFS/Device/Local.EnumerateDevices.cs rename to AlphaFS/Device/Local/Local.EnumerateDevices.cs index c453725f7..45467e35c 100644 --- a/AlphaFS/Device/Local.EnumerateDevices.cs +++ b/AlphaFS/Device/Local/Local.EnumerateDevices.cs @@ -240,7 +240,7 @@ private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetDeviceInterfaceD private static string GetDeviceBusReportedDeviceDescription(SafeHandle safeHandle, NativeMethods.SP_DEVINFO_DATA infoData) { if (!OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows7)) - return null; + return string.Empty; const int bufferSize = Filesystem.NativeMethods.DefaultFileBufferSize / 32; // 128 @@ -260,10 +260,10 @@ private static string GetDeviceBusReportedDeviceDescription(SafeHandle safeHandl var result = value.Remove(value.IndexOf((char) 0)); - return !Utils.IsNullOrWhiteSpace(result) ? result.Trim() : null; + return !Utils.IsNullOrWhiteSpace(result) ? result.Trim() : string.Empty; } - return null; + return string.Empty; } @@ -283,7 +283,7 @@ private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMet { var value = safeBuffer.PtrToStringUni(); - return !Utils.IsNullOrWhiteSpace(value) ? value.Trim() : null; + return !Utils.IsNullOrWhiteSpace(value) ? value.Trim() : string.Empty; } @@ -291,7 +291,7 @@ private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMet // 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; + return string.Empty; bufferSize = Utils.GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, property.ToString()); @@ -303,10 +303,16 @@ private static string GetDeviceRegistryProperty(SafeHandle safeHandle, NativeMet private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) { SetMinimalDeviceProperties(safeHandle, deviceInfo, infoData); - + + deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.BaseContainerId)); + + deviceInfo.ClassGuid = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.ClassGuid)); + deviceInfo.CompatibleIds = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.CompatibleIds); + deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.Class); + deviceInfo.DeviceDriver = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.Driver); deviceInfo.EnumeratorName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.EnumeratorName); @@ -326,14 +332,8 @@ private static void SetDeviceProperties(SafeHandle safeHandle, DeviceInfo device [SecurityCritical] private static void SetMinimalDeviceProperties(SafeHandle safeHandle, DeviceInfo deviceInfo, NativeMethods.SP_DEVINFO_DATA infoData) { - deviceInfo.BaseContainerId = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.BaseContainerId)); - deviceInfo.BusReportedDeviceDescription = GetDeviceBusReportedDeviceDescription(safeHandle, infoData); - - deviceInfo.ClassGuid = new Guid(GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.ClassGuid)); - - deviceInfo.DeviceClass = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.Class); - + deviceInfo.DeviceDescription = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.DeviceDescription); deviceInfo.FriendlyName = GetDeviceRegistryProperty(safeHandle, infoData, NativeMethods.SPDRP.FriendlyName); diff --git a/AlphaFS/Device/Local.GetDeviceIoData.cs b/AlphaFS/Device/Local/Local.GetDeviceIoData.cs similarity index 100% rename from AlphaFS/Device/Local.GetDeviceIoData.cs rename to AlphaFS/Device/Local/Local.GetDeviceIoData.cs diff --git a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Local/Local.GetStorageAdapterInfo.cs similarity index 97% rename from AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs rename to AlphaFS/Device/Local/Local.GetStorageAdapterInfo.cs index 0626d5dfb..2160b7230 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStorageAdapterInfo.cs @@ -74,7 +74,9 @@ internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath, return null; - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, NativeMethods.FILE_ANY_ACCESS)) + localDevicePath = localDevicePath ?? devicePath; + + using (var safeHandle = OpenDevice(localDevicePath, NativeMethods.FILE_ANY_ACCESS)) return GetStorageAdapterInfoNative(safeHandle, storageDeviceInfo.DeviceNumber, localDevicePath, busReportedDeviceDescription); } diff --git a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs similarity index 97% rename from AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs rename to AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs index 03e62b622..3a5549398 100644 --- a/AlphaFS/Device/Storage/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs @@ -113,10 +113,10 @@ internal static StorageDeviceInfo GetStorageDeviceInfoNative(bool isElevated, bo Retry: - // Accessing volume: "\\.\D" on a dynamic disk fails with ERROR_INVALID_FUNCTION. + // Accessing a volume like: "\\.\D" on a dynamic disk fails with ERROR_INVALID_FUNCTION. // On retry, the drive is accessed using the: "\\.\PhysicalDriveX" path format which is the device, not the volume/logical drive. - using (var safeHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + using (var safeHandle = OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) { int lastError; diff --git a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Local/Local.GetStoragePartitionInfo.cs similarity index 97% rename from AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs rename to AlphaFS/Device/Local/Local.GetStoragePartitionInfo.cs index 5e21aae99..933b8aee9 100644 --- a/AlphaFS/Device/Storage/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStoragePartitionInfo.cs @@ -84,7 +84,9 @@ internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated return null; - using (var safeFileHandle = FileSystemHelper.OpenPhysicalDisk(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + localDevicePath = localDevicePath ?? devicePath; + + using (var safeFileHandle = OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) return GetStoragePartitionInfoNative(safeFileHandle, storageDeviceInfo.DeviceNumber, localDevicePath); } diff --git a/AlphaFS/Device/Local.GetVolumeDiskExtents.cs b/AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs similarity index 100% rename from AlphaFS/Device/Local.GetVolumeDiskExtents.cs rename to AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs diff --git a/AlphaFS/Device/Local.InvokeDeviceIoData.cs b/AlphaFS/Device/Local/Local.InvokeDeviceIoData.cs similarity index 100% rename from AlphaFS/Device/Local.InvokeDeviceIoData.cs rename to AlphaFS/Device/Local/Local.InvokeDeviceIoData.cs diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs b/AlphaFS/Device/Local/Local.OpenDevice.cs similarity index 94% rename from AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs rename to AlphaFS/Device/Local/Local.OpenDevice.cs index e23f62008..0d40c9ce0 100644 --- a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.OpenPhysicalDrive.cs +++ b/AlphaFS/Device/Local/Local.OpenDevice.cs @@ -29,7 +29,7 @@ namespace Alphaleonis.Win32.Device { - internal static partial class FileSystemHelper + public static partial class Local { /// Opens a physical disk or volume/logical drive for read access. /// Returns a instance. @@ -45,7 +45,7 @@ internal static partial class FileSystemHelper /// /// If no elevated access is needed to access the physical disk or volume/logical drive, specify 0 for this parameter. [SecurityCritical] - public static SafeFileHandle OpenPhysicalDisk(string devicePath, FileSystemRights fileSystemRights) + public static SafeFileHandle OpenDevice(string devicePath, FileSystemRights fileSystemRights) { // fileSystemRights: If this parameter is 0 (FILE_ANY_ACCESS), the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. @@ -64,7 +64,7 @@ public static SafeFileHandle OpenPhysicalDisk(string devicePath, FileSystemRight - internal static SafeFileHandle OpenPhysicalDisk2(string devicePath, FileSystemRights fileSystemRights) + internal static SafeFileHandle OpenDevice2(string devicePath, FileSystemRights fileSystemRights) { // fileSystemRights: If this parameter is 0 (FILE_ANY_ACCESS), the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. diff --git a/AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs b/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs similarity index 100% rename from AlphaFS/Device/Storage/Local.SetStorageDeviceInfoData.cs rename to AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs diff --git a/AlphaFS/Device/Native Other/IoControlCode.cs b/AlphaFS/Device/Native Other/IoControlCode.cs index 26fc581f5..6b9db4f58 100644 --- a/AlphaFS/Device/Native Other/IoControlCode.cs +++ b/AlphaFS/Device/Native Other/IoControlCode.cs @@ -30,11 +30,11 @@ internal static partial class NativeMethods internal enum IoControlCode : uint { /// Retrieves the physical location of a specified volume on one or more disks. - IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// Return properties of a storage device or adapter. The request indicates the kind of information to retrieve, such as inquiry data for a device or capabilities and limitations of an adapter. - IOCTL_STORAGE_QUERY_PROPERTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x500 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_STORAGE_QUERY_PROPERTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x500 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), #region FILE_DEVICE_MASS_STORAGE @@ -124,7 +124,7 @@ internal enum IoControlCode : uint /// Returns a STORAGE_DEVICE_NUMBER structure that contains the FILE_DEVICE_XXX type, device number, and, for a partitionable device, /// the partition number assigned to a device by the driver when the device is started. This request is usually issued by a fault-tolerant disk driver. /// - IOCTL_STORAGE_GET_DEVICE_NUMBER = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0420 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_STORAGE_GET_DEVICE_NUMBER = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0420 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -142,7 +142,7 @@ internal enum IoControlCode : uint /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). /// IOCTL_DISK_GET_DRIVE_GEOMETRY_EX can retrieve information from both Master Boot Record (MBR) and GUID Partition Table (GPT)-type partitioned media. /// - IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0028 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0028 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///////// Returns information about the type, size, and nature of a disk partition. (Floppy drivers need not handle this request.) @@ -154,7 +154,7 @@ internal enum IoControlCode : uint /// Contains extended information about a drive's partitions. - IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0014 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0014 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Repartitions a disk as specified. (Floppy drivers need not handle this request.) @@ -219,7 +219,8 @@ internal enum IoControlCode : uint /// Retrieves the length of the specified disk, volume, or partition. - IOCTL_DISK_GET_LENGTH_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0017 << 2) | IoCtlMethod.Buffered | (FileAccess.Read << 14), + /// This operation should be used instead of IOCTL_DISK_GET_PARTITION_INFO_EX for volumes that do not have partition info, such as partition type or number of hidden sectors. + IOCTL_DISK_GET_LENGTH_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0017 << 2) | IoControlMethod.Buffered | (FileAccess.Read << 14), ///// Returns version information, a capabilities mask, and a bitmask for the device. This IOCTL must be handled by drivers that support Self-Monitoring Analysis and Reporting Technology (SMART). @@ -405,7 +406,7 @@ internal enum IoControlCode : uint /// Sets the compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. You can use FSCTL_SET_COMPRESSION to compress or uncompress a file or directory on such a volume. - FSCTL_SET_COMPRESSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (16 << 2) | IoCtlMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + FSCTL_SET_COMPRESSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (16 << 2) | IoControlMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// @@ -529,7 +530,7 @@ internal enum IoControlCode : uint /// Minifilters should use FltTagFile instead of FSCTL_SET_REPARSE_POINT to set a reparse point. /// For more information about reparse points and the FSCTL_SET_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_SET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (41 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), + FSCTL_SET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (41 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// @@ -537,7 +538,7 @@ internal enum IoControlCode : uint /// To perform this operation, call FltFsControlFile or ZwFsControlFile with the following parameters. /// For more information about reparse points and the FSCTL_GET_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_GET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (42 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), + FSCTL_GET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (42 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// @@ -547,7 +548,7 @@ internal enum IoControlCode : uint /// Minifilters should use FltUntagFile instead of FSCTL_DELETE_REPARSE_POINT to delete a reparse point. /// For more information about reparse points and the FSCTL_DELETE_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_DELETE_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (43 << 2) | IoCtlMethod.Buffered | (FILE_ANY_ACCESS << 14), + FSCTL_DELETE_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (43 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// diff --git a/AlphaFS/Device/Native Other/IoCtlMethod.cs b/AlphaFS/Device/Native Other/IoControlMethod.cs similarity index 97% rename from AlphaFS/Device/Native Other/IoCtlMethod.cs rename to AlphaFS/Device/Native Other/IoControlMethod.cs index 0a0998dc0..54c98f9b0 100644 --- a/AlphaFS/Device/Native Other/IoCtlMethod.cs +++ b/AlphaFS/Device/Native Other/IoControlMethod.cs @@ -24,7 +24,7 @@ namespace Alphaleonis.Win32.Device internal static partial class NativeMethods { /// Define values for DeviceIoControl. - private enum IoCtlMethod : uint + private enum IoControlMethod : uint { Buffered = 0, InDirect = 1, diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index dd1f2f3da..702c1bf7d 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Device { public static partial class Local { - /// [AlphaFS] Enumerates the physical disks (including CD/DVD devices) on the Computer, populated with volume/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CD-ROM/DVD devices) on the Computer, populated with volume/logical drive information. /// Returns an collection that represents the physical disks on the Computer. [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() @@ -36,7 +36,7 @@ public static IEnumerable EnumeratePhysicalDisks() } - /// [AlphaFS] Enumerates the physical disks (including CD/DVD devices) on the Computer, populated with volume/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CD-ROM/DVD devices) on the Computer, populated with volume/logical drive information. /// Returns an collection that represents the physical disks on the Computer. /// Retrieve instances by device number. [SecurityCritical] @@ -46,7 +46,7 @@ public static IEnumerable EnumeratePhysicalDisks(int deviceNum } - /// [AlphaFS] Enumerates the physical disks (including CD/DVD devices) on the Computer, populated with volume/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CD-ROM/DVD devices) on the Computer, populated with volume/logical drive information. /// Returns an collection that represents the physical disks on the Computer. /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// Retrieve a instance by device number. @@ -66,7 +66,7 @@ internal static IEnumerable EnumeratePhysicalDisksCore(bool is continue; - yield return new PhysicalDiskInfo(deviceNumber, deviceInfo.DevicePath, deviceInfo); + yield return new PhysicalDiskInfo(deviceNumber, deviceInfo.DevicePath, storageDeviceInfo, deviceInfo); } } } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index 3a69ce682..44b0423df 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -35,9 +35,9 @@ public sealed partial class PhysicalDiskInfo { #region Fields - private Collection partitionIndexCollection; - private Collection volumeGuidCollection; - private Collection logicalDriveCollection; + private Collection _partitionIndexCollection; + private Collection _volumeGuidCollection; + private Collection _logicalDriveCollection; #endregion // Fields @@ -56,7 +56,7 @@ public PhysicalDiskInfo(int deviceNumber) if (deviceNumber < 0) throw new ArgumentOutOfRangeException("deviceNumber"); - CreatePhysicalDiskInfoInstance(this, Security.ProcessContext.IsElevatedProcess, deviceNumber, null, null); + CreatePhysicalDiskInfoInstance(deviceNumber, null, null, null); } @@ -73,22 +73,25 @@ public PhysicalDiskInfo(int deviceNumber) /// public PhysicalDiskInfo(string devicePath) { - CreatePhysicalDiskInfoInstance(this, Security.ProcessContext.IsElevatedProcess, -1, devicePath, null); + CreatePhysicalDiskInfoInstance(-1, devicePath, null, null); } - internal PhysicalDiskInfo(int deviceNumber, string devicePath, DeviceInfo deviceInfo) + /// Used by + internal PhysicalDiskInfo(int deviceNumber, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) { - CreatePhysicalDiskInfoInstance(this, Security.ProcessContext.IsElevatedProcess, deviceNumber, devicePath, deviceInfo); + CreatePhysicalDiskInfoInstance(deviceNumber, devicePath, storageDeviceInfo, deviceInfo); } #endregion // Constructors [SecurityCritical] - private static void CreatePhysicalDiskInfoInstance(PhysicalDiskInfo physicalDiskInfo, bool isElevated, int deviceNumber, string devicePath, DeviceInfo deviceInfo) + private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) { + var isElevated = Security.ProcessContext.IsElevatedProcess; var getByDeviceNumber = deviceNumber > -1; + var isDrive = false; var isVolume = false; var isDevice = false; @@ -97,152 +100,111 @@ private static void CreatePhysicalDiskInfoInstance(PhysicalDiskInfo physicalDisk if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - - // The StorageDeviceInfo is always needed as it contains the device- and partition number. + string physicalDriveNumberPath = null; - string physicalDriveNumberPath; + // The StorageDeviceInfo is always needed as it contains the device- and partition number. - physicalDiskInfo.StorageDeviceInfo = Local.GetStorageDeviceInfoNative(isElevated, isDevice, deviceNumber, localDevicePath, out physicalDriveNumberPath); + StorageDeviceInfo = storageDeviceInfo ?? Local.GetStorageDeviceInfoNative(isElevated, isDevice, deviceNumber, localDevicePath, out physicalDriveNumberPath); - if (null == physicalDiskInfo.StorageDeviceInfo) + if (null == StorageDeviceInfo) return; - deviceNumber = getByDeviceNumber ? deviceNumber : physicalDiskInfo.StorageDeviceInfo.DeviceNumber; + deviceNumber = getByDeviceNumber ? deviceNumber : StorageDeviceInfo.DeviceNumber; if (null == deviceInfo) - foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) - { - string unusedDevicePath; + SetDeviceInfoData(isElevated, deviceNumber); + else + DeviceInfo = deviceInfo; - var deviceStorageInfo = Local.GetStorageDeviceInfoNative(isElevated, true, deviceNumber, device.DevicePath, out unusedDevicePath); + if (null == DeviceInfo) + return; + + + // If physicalDriveNumberPath != null, the drive is opened using: "\\.\PhysicalDriveX" path format + // which is the device, not the volume/logical drive. - if (null == deviceStorageInfo) - continue; + var updatedDevicPath = physicalDriveNumberPath ?? localDevicePath; - deviceInfo = device; - break; - } + DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(updatedDevicPath, GetFullPathOptions.None, false)); - if (null == deviceInfo) - return; - physicalDiskInfo.DeviceInfo = deviceInfo; + using (var safeFileHandle = Local.OpenDevice(updatedDevicPath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + { + StorageAdapterInfo = Local.GetStorageAdapterInfoNative(safeFileHandle, deviceNumber, updatedDevicPath, DeviceInfo.BusReportedDeviceDescription); + StoragePartitionInfo = Local.GetStoragePartitionInfoNative(safeFileHandle, deviceNumber, updatedDevicPath); + } + - // physicalDriveNumberPath != null: The drive is opened using: "\\.\PhysicalDriveX" path format - // which is the device, not the volume/logical drive. + PopulatePhysicalDisk(isElevated); + } - var updatedDevicPath = physicalDriveNumberPath ?? localDevicePath; - - if (isDrive || isVolume) + private void SetDeviceInfoData(bool isElevated, int deviceNumber) + { + foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) { - physicalDiskInfo.DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); + string unusedDevicePath; - updatedDevicPath = localDevicePath; - //updatedDevicPath = Path.GlobalRootPrefix + deviceInfo.PhysicalDeviceObjectName.TrimStart('\\'); - } + var deviceStorageInfo = Local.GetStorageDeviceInfoNative(isElevated, true, deviceNumber, device.DevicePath, out unusedDevicePath); + if (null == deviceStorageInfo) + continue; - using (var safeFileHandle = FileSystemHelper.OpenPhysicalDisk(updatedDevicPath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - { - physicalDiskInfo.StorageAdapterInfo = Local.GetStorageAdapterInfoNative(safeFileHandle, deviceNumber, updatedDevicPath, deviceInfo.BusReportedDeviceDescription); - physicalDiskInfo.StoragePartitionInfo = Local.GetStoragePartitionInfoNative(safeFileHandle, deviceNumber, updatedDevicPath); + DeviceInfo = device; } - - - physicalDiskInfo.PopulatePhysicalDisk(isElevated, physicalDiskInfo); } - /// Retrieves volumes/logical drives that belong to the instance. + /// Retrieves volumes/logical drives that belong to the PhysicalDiskInfo instance. [SecurityCritical] - private void PopulatePhysicalDisk(bool isElevated, PhysicalDiskInfo physicalDiskInfo) + private void PopulatePhysicalDisk(bool isElevated) { - var deviceNumber = physicalDiskInfo.StorageDeviceInfo.DeviceNumber; - + var deviceNumber = StorageDeviceInfo.DeviceNumber; + + _partitionIndexCollection = new Collection(); + _volumeGuidCollection = new Collection(); + _logicalDriveCollection = new Collection(); + + foreach (var volumeGuid in Volume.EnumerateVolumes()) { string unusedLocalDevicePath; // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var storageDeviceInfo = Local.GetStorageDeviceInfoCore(isElevated, deviceNumber, volumeGuid, out unusedLocalDevicePath); + var storageDeviceInfo = Local.GetStorageDeviceInfoNative(isElevated, false, deviceNumber, volumeGuid, out unusedLocalDevicePath); if (null == storageDeviceInfo) continue; - AddToPartitionIndex(storageDeviceInfo.PartitionNumber); - - AddToVolumeGuids(volumeGuid); - + _partitionIndexCollection.Add(storageDeviceInfo.PartitionNumber); + + _volumeGuidCollection.Add(volumeGuid); + // Resolve logical drive from volume matching DeviceNumber and PartitionNumber. var driveName = Volume.GetVolumeDisplayName(volumeGuid); - if (!Utils.IsNullOrWhiteSpace(driveName)) - AddToLogicalDrives(driveName); + _logicalDriveCollection.Add(Path.RemoveTrailingDirectorySeparator(driveName)); } - if (null != partitionIndexCollection) - physicalDiskInfo.PartitionIndexes = partitionIndexCollection; - - if (null != volumeGuidCollection) - physicalDiskInfo.VolumeGuids = volumeGuidCollection; - - if (null != logicalDriveCollection) - physicalDiskInfo.LogicalDrives = logicalDriveCollection; - } + PartitionIndexes = _partitionIndexCollection; + VolumeGuids = _volumeGuidCollection; - /// Adds device partition index numbers. - private void AddToPartitionIndex(int deviceNumber) - { - if (null == partitionIndexCollection) - partitionIndexCollection = new Collection(); - - partitionIndexCollection.Add(deviceNumber); + LogicalDrives = _logicalDriveCollection; } - - - /// Adds device volume GUIDs. - private void AddToVolumeGuids(string volumeGuid) - { - //// Add device volume labels. - - //if (null == pDiskInfo.VolumeLabels) - // pDiskInfo.VolumeLabels = new Collection(); - - //pDiskInfo.VolumeLabels.Add(pVolume.Name); - - - if (null == volumeGuidCollection) - volumeGuidCollection = new Collection(); - - volumeGuidCollection.Add(volumeGuid); - } - - - /// Adds device logical drive. - private void AddToLogicalDrives(string drivePath) - { - if (null == logicalDriveCollection) - logicalDriveCollection = new Collection(); - - logicalDriveCollection.Add(Path.RemoveTrailingDirectorySeparator(drivePath)); - } - - - + /// Returns the "FriendlyName" of the physical disk. /// Returns a string that represents this instance. @@ -262,7 +224,14 @@ public override bool Equals(object obj) var other = obj as PhysicalDiskInfo; - return null != other && other.DevicePath == DevicePath && + return null != other && + other.Name == Name && + other.DevicePath == DevicePath && + other.DosDeviceName == DosDeviceName && + other.PhysicalDeviceObjectName == PhysicalDeviceObjectName && + other.PartitionIndexes == PartitionIndexes && + other.VolumeGuids == VolumeGuids && + other.LogicalDrives == LogicalDrives && other.StorageAdapterInfo == StorageAdapterInfo && other.StorageDeviceInfo == StorageDeviceInfo && other.StoragePartitionInfo == StoragePartitionInfo; diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 80fc0d4a0..13c2ae155 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -85,9 +85,11 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() /// - /// The partition number of the storage device, starting at 1. If the device cannot be partitioned, like a CDROM, -1 is returned. + /// The partition number of the storage device, starting at 1. + /// Partition number 0 is the device. + /// If the device cannot be partitioned, like a CDROM, -1 is returned. /// -1 is also returned if the device is accessed by its path: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// instead of a logical drive- or volume path. + /// instead of a volume /logical drive path. /// public int PartitionNumber { get; private set; } From adebbdec67404251b84b0b31acb5384c6653f2a4 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 18 Jun 2018 18:10:32 +0200 Subject: [PATCH 121/133] Code improvement. --- ...Disks_ReturnsStorageDeviceInfoForDevice.cs | 7 +- ...Drive_ReturnsStorageDeviceInfoForDevice.cs | 13 +- ...umber_ReturnsStorageDeviceInfoForDevice.cs | 5 + AlphaFS/AlphaFS.csproj | 9 +- ...FileSystemHelper.GetValidatedDevicePath.cs | 2 +- .../Device/Local/Local.GetDiskGeometryEx.cs | 88 ++++++++++++ .../Local/Local.GetStorageAdapterInfo.cs | 55 +------- .../Local/Local.GetStorageDeviceInfo.cs | 81 +---------- .../Local/Local.GetStoragePartitionInfo.cs | 127 +----------------- .../Local/Local.SetStorageDeviceInfoData.cs | 25 +++- .../Local.EnumeratePhysicalDisks.cs | 11 +- .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 82 ++++++----- .../Volume/Volume.GetVolumeDeviceName.cs | 2 +- 13 files changed, 196 insertions(+), 311 deletions(-) create mode 100644 AlphaFS/Device/Local/Local.GetDiskGeometryEx.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs index 338ae54ca..855cea37f 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs @@ -34,7 +34,7 @@ public partial class EnumerationTest public void AlphaFS_Device_EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice() { UnitTestConstants.PrintUnitTestHeader(false); - + var driveCount = 0; var physicalDrives = Alphaleonis.Win32.Filesystem.Volume.QueryAllDosDevices().Where(device => device.StartsWith("PhysicalDrive", StringComparison.OrdinalIgnoreCase)).ToArray(); @@ -86,6 +86,11 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDev Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + // TotalSize should always match for device. + + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.TotalSize, pDiskInfo.StoragePartitionInfo.TotalSize); + + driveCount++; Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive_ReturnsStorageDeviceInfoForDevice.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive_ReturnsStorageDeviceInfoForDevice.cs index 832c52c98..3ad49349b 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive_ReturnsStorageDeviceInfoForDevice.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingDevicePathFromSystemDrive_ReturnsStorageDeviceInfoForDevice.cs @@ -69,15 +69,14 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingDevicePathFromSystemDri Assert.AreEqual(pDiskInfo.DosDeviceName, pDiskInfo.PhysicalDeviceObjectName); - - // PartitionNumber should be -1 for CDRom. + // PartitionNumber should be 0 for device. + + Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + - if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) - Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + // TotalSize should always match for device. - // PartitionNumber should be > 0 for logical drive because it is not the device. - else - Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.TotalSize, pDiskInfo.StoragePartitionInfo.TotalSize); // ContainsVolume should find volumes/logical drives. diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs index e79d48c6a..2f441473e 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs @@ -73,6 +73,11 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingPhysicalDriveNumber_Ret Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + // TotalSize should always match for device. + + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.TotalSize, pDiskInfo.StoragePartitionInfo.TotalSize); + + Assert.AreEqual(physicalDiskNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index a4c1b7fc1..2ec3d16e4 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -197,11 +197,14 @@ True + + + - + @@ -211,10 +214,8 @@ - - @@ -743,7 +744,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs b/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs index f8894a180..4f41b2287 100644 --- a/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs +++ b/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs @@ -41,7 +41,7 @@ internal static string GetValidatedDevicePath(string devicePath, out bool isDriv { isDrive = false; isVolume = false; - isDevice = false; + isDevice = true; return devicePath; } diff --git a/AlphaFS/Device/Local/Local.GetDiskGeometryEx.cs b/AlphaFS/Device/Local/Local.GetDiskGeometryEx.cs new file mode 100644 index 000000000..61305eca8 --- /dev/null +++ b/AlphaFS/Device/Local/Local.GetDiskGeometryEx.cs @@ -0,0 +1,88 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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 Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32.Device +{ + public static partial class Local + { + /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). + [SecurityCritical] + private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryEx(SafeFileHandle safeFileHandle, string pathForException) + { + var bufferSize = 128; + + while (true) + using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) + { + var success = NativeMethods.DeviceIoControl(safeFileHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); + + var lastError = Marshal.GetLastWin32Error(); + + if (success) + { + var typeOf = typeof(NativeMethods.DISK_GEOMETRY); + var sizeOf = Marshal.SizeOf(typeOf); // 24 + + var diskGeometryEx = new NativeMethods.DISK_GEOMETRY_EX + { + Geometry = safeBuffer.PtrToStructure(), + + DiskSize = safeBuffer.ReadInt64(sizeOf) + }; + + + var offset = (uint) sizeOf + sizeof(long); // 32 + + diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure((int) offset); + + + //// Intermittently throws: System.AccessViolationException: Attempted to read or write protected memory. + //// Observed when mounting an .iso file. + + //offset += diskGeometryEx.PartitionInformation.SizeOfPartitionInfo; + + //diskGeometryEx.DiskDetectionInfo = safeBuffer.PtrToStructure((int) offset); + + return diskGeometryEx; + } + + + if (lastError == Win32Errors.ERROR_NOT_READY || + + // A logical drive path like \\.\D: fails on a dynamic disk. + lastError == Win32Errors.ERROR_INVALID_FUNCTION || + + // Request device number from a DeviceGuid.Image device. + lastError == Win32Errors.ERROR_NOT_SUPPORTED) + + return new NativeMethods.DISK_GEOMETRY_EX(); + + + bufferSize = Utils.GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); + } + } + } +} diff --git a/AlphaFS/Device/Local/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Local/Local.GetStorageAdapterInfo.cs index 2160b7230..168f45b64 100644 --- a/AlphaFS/Device/Local/Local.GetStorageAdapterInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStorageAdapterInfo.cs @@ -29,61 +29,10 @@ namespace Alphaleonis.Win32.Device public static partial class Local { /// [AlphaFS] Retrieves the storage adapter of the device that is related to the logical drive name, volume or . - /// Returns a instance that represent the adapter information of the storage device that is related to . - /// - /// - /// + /// Returns a instance that represent the storage device that is related to . /// - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// [SecurityCritical] - public static StorageAdapterInfo GetStorageAdapterInfo(string devicePath) - { - return GetStorageAdapterInfoCore(devicePath, null); - } - - - /// [AlphaFS] Retrieves the storage adapter of the device that is related to the logical drive name, volume or . - /// Returns a instance that represent the storage device that is related to . - /// - /// - /// - /// - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// - /// The bus reported bus reported device description of the instance. - [SecurityCritical] - internal static StorageAdapterInfo GetStorageAdapterInfoCore(string devicePath, string busReportedDeviceDescription) - { - var localDevicePath = devicePath; - - - // The StorageDeviceInfo is always needed as it contains the device- and partition number. - - var storageDeviceInfo = GetStorageDeviceInfoCore(false, -1, localDevicePath, out localDevicePath); - - if (null == storageDeviceInfo) - return null; - - - localDevicePath = localDevicePath ?? devicePath; - - using (var safeHandle = OpenDevice(localDevicePath, NativeMethods.FILE_ANY_ACCESS)) - - return GetStorageAdapterInfoNative(safeHandle, storageDeviceInfo.DeviceNumber, localDevicePath, busReportedDeviceDescription); - } - - - [SecurityCritical] - internal static StorageAdapterInfo GetStorageAdapterInfoNative(SafeFileHandle safeFileHandle, int deviceNumber, string localDevicePath, string busReportedDeviceDescription) + internal static StorageAdapterInfo GetStorageAdapterInfo(SafeFileHandle safeFileHandle, int deviceNumber, string localDevicePath, string busReportedDeviceDescription) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { diff --git a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs index 3a5549398..294256b55 100644 --- a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs @@ -24,88 +24,16 @@ using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; -using Alphaleonis.Win32.Security; namespace Alphaleonis.Win32.Device { public static partial class Local { - /// [AlphaFS] Retrieves the type, device- and partition number for the storage device that is related to the logical drive name, volume or . /// Returns a instance that represent the storage device that is related to . /// When this method is called from a non-elevated state, the property always returns 0. - /// - /// - /// /// - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// [SecurityCritical] - public static StorageDeviceInfo GetStorageDeviceInfo(string devicePath) - { - string unusedLocalDevicePath; - - return GetStorageDeviceInfoCore(ProcessContext.IsElevatedProcess, -1, devicePath, out unusedLocalDevicePath); - } - - - /// Returns a instance that represent the storage device that is related to . - /// When this method is called from a non-elevated state, the property always returns 0. - /// - /// - /// - /// - /// true indicates the current process is in an elevated state, allowing to retrieve more data. - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// - [SecurityCritical] - public static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, string devicePath) - { - string unusedLocalDevicePath; - - return GetStorageDeviceInfoCore(isElevated, -1, devicePath, out unusedLocalDevicePath); - } - - - /// Returns a instance that represent the storage device that is related to . - /// When this method is called from a non-elevated state, the property always returns 0. - /// - /// - /// - /// - /// true indicates the current process is in an elevated state, allowing to retrieve more data. - /// A number that indicates a physical disk on the Computer. - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// - /// The resolved local device path such as \\.\C: or \\.\PhysicalDrive0 - [SecurityCritical] - internal static StorageDeviceInfo GetStorageDeviceInfoCore(bool isElevated, int deviceNumber, string devicePath, out string localDevicePath) - { - bool isDrive; - bool isVolume; - bool isDevice; - - localDevicePath = FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); - - if (isDrive) - localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - - return GetStorageDeviceInfoNative(isElevated, isDevice, deviceNumber, localDevicePath, out localDevicePath); - } - - - internal static StorageDeviceInfo GetStorageDeviceInfoNative(bool isElevated, bool isDevice, int deviceNumber, string devicePath, out string localDevicePath) + internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isDevice, int deviceNumber, string devicePath, out string localDevicePath) { localDevicePath = devicePath; var getByDeviceNumber = deviceNumber > -1; @@ -143,12 +71,17 @@ internal static StorageDeviceInfo GetStorageDeviceInfoNative(bool isElevated, bo if (!retry && !isDevice && lastError == Win32Errors.ERROR_INVALID_FUNCTION) { + + // For dynamic disk? + // localDevicePath = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); + + var volDiskExtents = GetVolumeDiskExtents(safeHandle, localDevicePath); if (volDiskExtents.HasValue) foreach (var extent in volDiskExtents.Value.Extents) { - var newDeviceNumber = (int) extent.DiskNumber; + var newDeviceNumber = (int)extent.DiskNumber; if (getByDeviceNumber && deviceNumber != newDeviceNumber) continue; diff --git a/AlphaFS/Device/Local/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Local/Local.GetStoragePartitionInfo.cs index 933b8aee9..9153ec71c 100644 --- a/AlphaFS/Device/Local/Local.GetStoragePartitionInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStoragePartitionInfo.cs @@ -22,9 +22,6 @@ using System; using System.Runtime.InteropServices; using System.Security; -using System.Security.AccessControl; -using Alphaleonis.Win32.Filesystem; -using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device @@ -32,68 +29,10 @@ namespace Alphaleonis.Win32.Device public static partial class Local { /// [AlphaFS] Retrieves information about the partitions on a disk and the features of each partition. - /// Returns a instance that represent the partition info that is related to . - /// - /// - /// + /// Returns a instance that represent the partition info that is related to . /// - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// [SecurityCritical] - public static StoragePartitionInfo GetStoragePartitionInfo(string devicePath) - { - return GetStoragePartitionInfoCore(ProcessContext.IsElevatedProcess, devicePath); - } - - - /// [AlphaFS] Retrieves information about the partitions on a disk and the features of each partition. - /// Returns a instance that represent the partition info that is related to . - /// - /// - /// - /// - /// true indicates the current process is in an elevated state, allowing to retrieve more data. - /// - /// A disk path such as: \\.\PhysicalDrive0 - /// A drive path such as: C, C: or C:\ - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// - [SecurityCritical] - public static StoragePartitionInfo GetStoragePartitionInfo(bool isElevated, string devicePath) - { - return GetStoragePartitionInfoCore(isElevated, devicePath); - } - - - [SecurityCritical] - internal static StoragePartitionInfo GetStoragePartitionInfoCore(bool isElevated, string devicePath) - { - var localDevicePath = devicePath; - - - // The StorageDeviceInfo is always needed as it contains the device- and partition number. - - var storageDeviceInfo = GetStorageDeviceInfoCore(isElevated, -1, localDevicePath, out localDevicePath); - - if (null == storageDeviceInfo) - return null; - - - localDevicePath = localDevicePath ?? devicePath; - - using (var safeFileHandle = OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - - return GetStoragePartitionInfoNative(safeFileHandle, storageDeviceInfo.DeviceNumber, localDevicePath); - } - - - [SecurityCritical] - internal static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandle safeFileHandle, int deviceNumber, string localDevicePath) + internal static StoragePartitionInfo GetStoragePartitionInfo(SafeFileHandle safeFileHandle, int deviceNumber, string localDevicePath) { using (var safeBuffer = InvokeDeviceIoData(safeFileHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 4)) @@ -116,71 +55,13 @@ internal static StoragePartitionInfo GetStoragePartitionInfoNative(SafeFileHandl partitions[i] = safeBuffer.PtrToStructure(driveStructureSize + i * partitionStructureSize); - var disk = GetDiskGeometryExNative(safeFileHandle, localDevicePath); + var disk = GetDiskGeometryEx(safeFileHandle, localDevicePath); return new StoragePartitionInfo(deviceNumber, disk, layout, partitions); } } - return null; - } - - - /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). - [SecurityCritical] - internal static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryExNative(SafeFileHandle safeFileHandle, string pathForException) - { - var bufferSize = 128; - - while (true) - using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) - { - var success = NativeMethods.DeviceIoControl(safeFileHandle, NativeMethods.IoControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); - - var lastError = Marshal.GetLastWin32Error(); - - if (success) - { - var typeOf = typeof(NativeMethods.DISK_GEOMETRY); - var sizeOf = Marshal.SizeOf(typeOf); // 24 - - var diskGeometryEx = new NativeMethods.DISK_GEOMETRY_EX - { - Geometry = safeBuffer.PtrToStructure(), - - DiskSize = safeBuffer.ReadInt64(sizeOf) - }; - - - var offset = (uint) sizeOf + sizeof(long); // 32 - - diskGeometryEx.PartitionInformation = safeBuffer.PtrToStructure((int) offset); - - - //// Intermittently throws: System.AccessViolationException: Attempted to read or write protected memory. - //// Observed when mounting an .iso file. - - //offset += diskGeometryEx.PartitionInformation.SizeOfPartitionInfo; - - //diskGeometryEx.DiskDetectionInfo = safeBuffer.PtrToStructure((int) offset); - - return diskGeometryEx; - } - - - if (lastError == Win32Errors.ERROR_NOT_READY || - - // A logical drive path like \\.\D: fails on a dynamic disk. - lastError == Win32Errors.ERROR_INVALID_FUNCTION || - - // Request device number from a DeviceGuid.Image device. - lastError == Win32Errors.ERROR_NOT_SUPPORTED) - - return new NativeMethods.DISK_GEOMETRY_EX(); - - - bufferSize = Utils.GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); - } + return null; } } } diff --git a/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs b/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs index 25289a312..47cc62746 100644 --- a/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs +++ b/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs @@ -20,7 +20,6 @@ */ using System.Security; -using Alphaleonis.Win32.Filesystem; using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device @@ -69,22 +68,34 @@ private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, Saf // Get disk total size. - - var lastError = 0; - + if (isElevated) { + int lastError; + using (var safeBuffer = GetDeviceIoData(safeFileHandle,NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, localDevicePath, out lastError)) storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; } - // A logical drive path like \\.\D: fails on a dynamic disk. + //// A logical drive path like \\.\D: fails on a dynamic disk. + + //else + //{ + // if (isDevice) + // { + // //var dosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); - else if (!isDevice || lastError == Win32Errors.ERROR_INVALID_FUNCTION) + // //storageDeviceInfo.TotalSize = new DiskSpaceInfo(dosDeviceName, false, true, true).TotalNumberOfBytes; + // } - storageDeviceInfo.TotalSize = new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; + // else + // { + // //if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) + // storageDeviceInfo.TotalSize = new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; + // } + //} } } } diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 702c1bf7d..445163113 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -53,20 +53,17 @@ public static IEnumerable EnumeratePhysicalDisks(int deviceNum [SecurityCritical] internal static IEnumerable EnumeratePhysicalDisksCore(bool isElevated, int deviceNumber) { - foreach (var deviceInfo in EnumerateDevicesCore(null, new []{DeviceGuid.Disk, DeviceGuid.CDRom}, false)) + foreach (var deviceInfo in EnumerateDevicesCore(null, new []{DeviceGuid.Disk, DeviceGuid.CDRom, DeviceGuid.Wpd, DeviceGuid.WpdPrivate}, false)) { string unusedPhysicalDriveNumberPath; // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var storageDeviceInfo = GetStorageDeviceInfoNative(isElevated, true, deviceNumber, deviceInfo.DevicePath, out unusedPhysicalDriveNumberPath); + var storageDeviceInfo = GetStorageDeviceInfo(isElevated, true, deviceNumber, deviceInfo.DevicePath, out unusedPhysicalDriveNumberPath); - if (null == storageDeviceInfo) - continue; - - - yield return new PhysicalDiskInfo(deviceNumber, deviceInfo.DevicePath, storageDeviceInfo, deviceInfo); + if (null != storageDeviceInfo) + yield return new PhysicalDiskInfo(deviceNumber, storageDeviceInfo, deviceInfo); } } } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index 44b0423df..4eea100f1 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -25,6 +25,7 @@ using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; +using Alphaleonis.Win32.Security; namespace Alphaleonis.Win32.Device { @@ -78,9 +79,9 @@ public PhysicalDiskInfo(string devicePath) /// Used by - internal PhysicalDiskInfo(int deviceNumber, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) + internal PhysicalDiskInfo(int deviceNumber, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) { - CreatePhysicalDiskInfoInstance(deviceNumber, devicePath, storageDeviceInfo, deviceInfo); + CreatePhysicalDiskInfoInstance(deviceNumber, null, storageDeviceInfo, deviceInfo); } #endregion // Constructors @@ -89,14 +90,17 @@ internal PhysicalDiskInfo(int deviceNumber, string devicePath, StorageDeviceInfo [SecurityCritical] private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) { - var isElevated = Security.ProcessContext.IsElevatedProcess; + var isElevated = ProcessContext.IsElevatedProcess; var getByDeviceNumber = deviceNumber > -1; - var isDrive = false; - var isVolume = false; - var isDevice = false; + bool isDrive; + bool isVolume; + bool isDevice; - var localDevicePath = getByDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : FileSystemHelper.GetValidatedDevicePath(devicePath, out isDrive, out isVolume, out isDevice); + if (!getByDeviceNumber && Utils.IsNullOrWhiteSpace(devicePath) && null != deviceInfo) + devicePath = deviceInfo.DevicePath; + + var localDevicePath = FileSystemHelper.GetValidatedDevicePath(getByDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : devicePath, out isDrive, out isVolume, out isDevice); if (isDrive) localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); @@ -105,58 +109,68 @@ private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, // The StorageDeviceInfo is always needed as it contains the device- and partition number. - StorageDeviceInfo = storageDeviceInfo ?? Local.GetStorageDeviceInfoNative(isElevated, isDevice, deviceNumber, localDevicePath, out physicalDriveNumberPath); + StorageDeviceInfo = storageDeviceInfo ?? Local.GetStorageDeviceInfo(isElevated, isDevice, deviceNumber, localDevicePath, out physicalDriveNumberPath); if (null == StorageDeviceInfo) return; - deviceNumber = getByDeviceNumber ? deviceNumber : StorageDeviceInfo.DeviceNumber; + if (!SetDeviceInfoDataFromDeviceNumber(isElevated, deviceNumber, deviceInfo)) + return; - if (null == deviceInfo) - SetDeviceInfoData(isElevated, deviceNumber); - else - DeviceInfo = deviceInfo; - if (null == DeviceInfo) - return; - - // If physicalDriveNumberPath != null, the drive is opened using: "\\.\PhysicalDriveX" path format // which is the device, not the volume/logical drive. - var updatedDevicPath = physicalDriveNumberPath ?? localDevicePath; + localDevicePath = FileSystemHelper.GetValidatedDevicePath(physicalDriveNumberPath ?? localDevicePath, out isDrive, out isVolume, out isDevice); + + DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); - DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(updatedDevicPath, GetFullPathOptions.None, false)); + //localDevicePath = Path.GlobalRootPrefix + DosDeviceName.TrimStart('\\'); + //using (var safeFileHandle = Local.OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - using (var safeFileHandle = Local.OpenDevice(updatedDevicPath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + using (var safeFileHandle = Local.OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) { - StorageAdapterInfo = Local.GetStorageAdapterInfoNative(safeFileHandle, deviceNumber, updatedDevicPath, DeviceInfo.BusReportedDeviceDescription); + StorageAdapterInfo = Local.GetStorageAdapterInfo(safeFileHandle, deviceNumber, localDevicePath, DeviceInfo.BusReportedDeviceDescription); - StoragePartitionInfo = Local.GetStoragePartitionInfoNative(safeFileHandle, deviceNumber, updatedDevicPath); + StoragePartitionInfo = Local.GetStoragePartitionInfo(safeFileHandle, deviceNumber, localDevicePath); } PopulatePhysicalDisk(isElevated); - } - private void SetDeviceInfoData(bool isElevated, int deviceNumber) + // The Win32 API to retrieve the total size of the device requires an elevated process or the TotalSize is 0. + // The Win32 API to retrieve the total size of the device partition does not require elevation, so use that value. + + if (!isElevated && StorageDeviceInfo.TotalSize == 0 && null != StoragePartitionInfo) + + StorageDeviceInfo.TotalSize = isDevice ? StoragePartitionInfo.TotalSize : new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; + } + + + private bool SetDeviceInfoDataFromDeviceNumber(bool isElevated, int deviceNumber, DeviceInfo deviceInfo) { - foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) - { - string unusedDevicePath; + if (null == deviceInfo) + foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) + { + string unusedDevicePath; - var deviceStorageInfo = Local.GetStorageDeviceInfoNative(isElevated, true, deviceNumber, device.DevicePath, out unusedDevicePath); + var storageDeviceInfo = Local.GetStorageDeviceInfo(isElevated, true, deviceNumber, device.DevicePath, out unusedDevicePath); - if (null == deviceStorageInfo) - continue; + if (null != storageDeviceInfo) + { + deviceInfo = device; + break; + } + } - DeviceInfo = device; - } + DeviceInfo = deviceInfo; + + return null != DeviceInfo; } @@ -177,7 +191,7 @@ private void PopulatePhysicalDisk(bool isElevated) // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var storageDeviceInfo = Local.GetStorageDeviceInfoNative(isElevated, false, deviceNumber, volumeGuid, out unusedLocalDevicePath); + var storageDeviceInfo = Local.GetStorageDeviceInfo(isElevated, false, deviceNumber, volumeGuid, out unusedLocalDevicePath); if (null == storageDeviceInfo) continue; @@ -206,6 +220,8 @@ private void PopulatePhysicalDisk(bool isElevated) } + + /// Returns the "FriendlyName" of the physical disk. /// Returns a string that represents this instance. public override string ToString() diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs b/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs index 2a72f3574..3a59998d4 100644 --- a/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs +++ b/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs @@ -34,7 +34,7 @@ public static partial class Volume /// /// Name of the Volume. [SecurityCritical] - [Obsolete("Use Volume.QueryDosDevice")] + [Obsolete("Use Volume.QueryDosDevice(volumeName)")] public static string GetVolumeDeviceName(string volumeName) { return QueryDosDevice(volumeName); From 0f1a1eb5d415f78e7c09a18fb294f22b31c0c473 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 18 Jun 2018 21:21:46 +0200 Subject: [PATCH 122/133] Code improvement, work in progress. --- ...ePath_ReturnsStorageDeviceInfoForVolume.cs | 20 +++++++++++------- .../Local/Local.GetStorageDeviceInfo.cs | 13 ++++++------ .../Local/Local.GetVolumeDiskExtents.cs | 3 +-- .../Local/Local.SetStorageDeviceInfoData.cs | 21 +------------------ .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 3 --- .../Storage/Device.StorageDeviceInfo.cs | 4 +++- .../Filesystem/Path Class/Path.Constants.cs | 4 ++-- 7 files changed, 26 insertions(+), 42 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs index 86efeb10d..be5945875 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs @@ -84,17 +84,23 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingLogicalDrivePath_Return Assert.AreNotEqual(pDiskInfo.DosDeviceName, pDiskInfo.PhysicalDeviceObjectName); - // PartitionNumber should be -1 for CDRom. + //// (It seems that, not 100% sure) PartitionNumber should be 0 for logical drive on dynamic disk. - if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) - Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); - - // PartitionNumber should be > 0 for logical drive because it is not the device. - else - Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + //if (pDiskInfo.StoragePartitionInfo.OnDynamicDisk) + // Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + //else + //{ + // PartitionNumber should be -1 for CDRom. + if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) + Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + // PartitionNumber should be > 0 for logical drive because it is not the device. + else + Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + //} + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.DeviceNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); diff --git a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs index 294256b55..f71c1aab3 100644 --- a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs @@ -29,8 +29,10 @@ namespace Alphaleonis.Win32.Device { public static partial class Local { + // /// When this method is called from a non-elevated state, the property always returns 0. + + /// Returns a instance that represent the storage device that is related to . - /// When this method is called from a non-elevated state, the property always returns 0. /// [SecurityCritical] internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isDevice, int deviceNumber, string devicePath, out string localDevicePath) @@ -57,7 +59,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isD if (getByDeviceNumber && deviceNumber != storageDeviceInfo.DeviceNumber) return null; - SetStorageDeviceInfoData(isElevated, isDevice, safeHandle, localDevicePath, storageDeviceInfo); + SetStorageDeviceInfoData(isElevated, safeHandle, localDevicePath, storageDeviceInfo); if (!localDevicePath.StartsWith(Path.PhysicalDrivePrefix, StringComparison.OrdinalIgnoreCase)) @@ -71,11 +73,6 @@ internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isD if (!retry && !isDevice && lastError == Win32Errors.ERROR_INVALID_FUNCTION) { - - // For dynamic disk? - // localDevicePath = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); - - var volDiskExtents = GetVolumeDiskExtents(safeHandle, localDevicePath); if (volDiskExtents.HasValue) @@ -88,7 +85,9 @@ internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isD localDevicePath = Path.PhysicalDrivePrefix + newDeviceNumber.ToString(CultureInfo.InvariantCulture); + isDevice = true; retry = true; + goto Retry; } } diff --git a/AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs b/AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs index ae466f083..547c92c07 100644 --- a/AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs @@ -66,8 +66,7 @@ public static partial class Local } - // When lastError = ERROR_MORE_DATA the drive is part of a mirror or volume, or the volume is on multiple disks. - + // 2016-06-18 TODO: When lastError = ERROR_MORE_DATA, the drive is part of a mirror or volume, or the volume is on multiple disks. // Encountered a drive such as a CDRom/mounted .iso file. if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) diff --git a/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs b/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs index 47cc62746..723a17908 100644 --- a/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs +++ b/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Device public static partial class Local { [SecurityCritical] - private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, SafeFileHandle safeFileHandle, string localDevicePath, StorageDeviceInfo storageDeviceInfo) + private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle safeFileHandle, string localDevicePath, StorageDeviceInfo storageDeviceInfo) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { @@ -77,25 +77,6 @@ private static void SetStorageDeviceInfoData(bool isElevated, bool isDevice, Saf storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; } - - - //// A logical drive path like \\.\D: fails on a dynamic disk. - - //else - //{ - // if (isDevice) - // { - // //var dosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); - - // //storageDeviceInfo.TotalSize = new DiskSpaceInfo(dosDeviceName, false, true, true).TotalNumberOfBytes; - // } - - // else - // { - // //if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) - // storageDeviceInfo.TotalSize = new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; - // } - //} } } } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index 4eea100f1..774fb3065 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -127,9 +127,6 @@ private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); - //localDevicePath = Path.GlobalRootPrefix + DosDeviceName.TrimStart('\\'); - //using (var safeFileHandle = Local.OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - using (var safeFileHandle = Local.OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) { diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 13c2ae155..7b728b86a 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -113,7 +113,9 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public string SerialNumber { get; internal set; } - /// The total size of the physical disk or 0 if the process is not elevated or the device is a controller. + // /// The total size of the physical disk or 0 if the process is not elevated or the device is a controller. + + /// The total size of the physical disk. public long TotalSize { get; internal set; } diff --git a/AlphaFS/Filesystem/Path Class/Path.Constants.cs b/AlphaFS/Filesystem/Path Class/Path.Constants.cs index a364297ee..d18cc5ac2 100644 --- a/AlphaFS/Filesystem/Path Class/Path.Constants.cs +++ b/AlphaFS/Filesystem/Path Class/Path.Constants.cs @@ -100,10 +100,10 @@ public static partial class Path public static readonly string WildcardQuestion = WildcardQuestionChar.ToString(CultureInfo.InvariantCulture); - /// [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. + /// [AlphaFS] Win32 File Namespace. The "\\?\" (non-normalized) 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. public static readonly string LongPathPrefix = string.Format(CultureInfo.InvariantCulture, "{0}{0}{1}{0}", DirectorySeparatorChar, WildcardQuestion); - /// [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. + /// [AlphaFS] Win32 Device Namespace. The "\\.\" (normalized) prefix is how to access physical disks and volumes, without going through the file system, if the API supports this type of access. public static readonly string LogicalDrivePrefix = string.Format(CultureInfo.InvariantCulture, "{0}{0}.{0}", DirectorySeparatorChar); /// [AlphaFS] PhysicalDrivePrefix = "\\.\PhysicalDrive" Provides standard physical disk prefix. From b251ab617086f0d9f939769755e0da49f7ddd8b2 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 19 Jun 2018 18:06:26 +0200 Subject: [PATCH 123/133] Code improvement, work in progress. --- ...Disks_ReturnsStorageDeviceInfoForDevice.cs | 13 +- ...ePath_ReturnsStorageDeviceInfoForVolume.cs | 16 +- .../AlphaFS_Volume.EnumerateVolumes.cs | 2 +- AlphaFS/AlphaFS.csproj | 8 +- .../Device/Local/Local.EnumerateDevices.cs | 2 +- .../Local/Local.GetStorageDeviceInfo.cs | 2 +- ...{STORAGE_DEVICE_TYPE.cs => DEVICE_TYPE.cs} | 9 +- AlphaFS/Device/Native Other/DISK_EXTENT.cs | 7 + AlphaFS/Device/Native Other/DISK_GEOMETRY.cs | 2 +- AlphaFS/Device/Native Other/IoControlCode.cs | 20 +- .../{STORAGE_MEDIA_TYPE.cs => MEDIA_TYPE.cs} | 11 +- .../NativeMethods.EfiPartitionAttributes.cs | 4 + .../Device/Native Other/PARTITION_STYLE.cs | 9 +- .../STORAGE_ADAPTER_DESCRIPTOR.cs | 9 +- .../Device/Native Other/STORAGE_BUS_TYPE.cs | 9 +- .../Native Other/STORAGE_DEVICE_DESCRIPTOR.cs | 4 + .../Native Other/STORAGE_DEVICE_NUMBER.cs | 13 +- .../Native Other/STORAGE_PROPERTY_ID.cs | 11 +- .../Native Other/STORAGE_PROPERTY_QUERY.cs | 4 + .../Device/Native Other/STORAGE_QUERY_TYPE.cs | 9 +- .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 10 +- .../Storage/Device.StorageDeviceInfo.cs | 4 +- .../Storage/Device.StoragePartitionInfo.cs | 5 + .../{StorageDeviceType.cs => DeviceType.cs} | 150 +++++++-------- .../StorageMediaType.cs | 178 +++++++++--------- 25 files changed, 275 insertions(+), 236 deletions(-) rename AlphaFS/Device/Native Other/{STORAGE_DEVICE_TYPE.cs => DEVICE_TYPE.cs} (95%) rename AlphaFS/Device/Native Other/{STORAGE_MEDIA_TYPE.cs => MEDIA_TYPE.cs} (95%) rename AlphaFS/Device/Structures, Enumerations/{StorageDeviceType.cs => DeviceType.cs} (61%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs index 855cea37f..b0398ea4c 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs @@ -78,7 +78,7 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDev // PartitionNumber should be -1 for CDRom. - if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) + if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.DeviceType.CDRom) Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); // PartitionNumber should be 0 for device. @@ -91,6 +91,17 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDev Assert.AreEqual(pDiskInfo.StorageDeviceInfo.TotalSize, pDiskInfo.StoragePartitionInfo.TotalSize); + // Show all partition information. + + if (null != pDiskInfo.StoragePartitionInfo && null != pDiskInfo.StoragePartitionInfo.GptPartitionInfo) + foreach (var partition in pDiskInfo.StoragePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, true); + + if (null != pDiskInfo.StoragePartitionInfo && null != pDiskInfo.StoragePartitionInfo.MbrPartitionInfo) + foreach (var partition in pDiskInfo.StoragePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, true); + + driveCount++; Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs index be5945875..278e5951d 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs @@ -84,23 +84,23 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingLogicalDrivePath_Return Assert.AreNotEqual(pDiskInfo.DosDeviceName, pDiskInfo.PhysicalDeviceObjectName); - //// (It seems that, not 100% sure) PartitionNumber should be 0 for logical drive on dynamic disk. + // (It seems that, not 100% sure) PartitionNumber should be 0 for logical drive on dynamic disk. - //if (pDiskInfo.StoragePartitionInfo.OnDynamicDisk) - // Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + if (pDiskInfo.StoragePartitionInfo.OnDynamicDisk) + Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); - //else - //{ + else + { // PartitionNumber should be -1 for CDRom. - if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.StorageDeviceType.CDRom) + if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.DeviceType.CDRom) Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); // PartitionNumber should be > 0 for logical drive because it is not the device. else Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); - //} - + } + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.DeviceNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumes.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumes.cs index b0a1b1021..105541645 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumes.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumes.cs @@ -47,7 +47,7 @@ public void AlphaFS_Volume_EnumerateVolumes_Local_Success() foreach (var displayName in Alphaleonis.Win32.Filesystem.Volume.EnumerateVolumePathNames(volume)) { - Console.WriteLine("\t\tVolume points to logcal drive: [{0}]", displayName); + Console.WriteLine("\t\tVolume points to logical drive: [{0}]", displayName); Console.WriteLine(); } diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 2ec3d16e4..682111fa2 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -373,8 +373,8 @@ - - + + @@ -547,7 +547,7 @@ - + @@ -744,7 +744,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Local/Local.EnumerateDevices.cs b/AlphaFS/Device/Local/Local.EnumerateDevices.cs index 45467e35c..53dca6ee0 100644 --- a/AlphaFS/Device/Local/Local.EnumerateDevices.cs +++ b/AlphaFS/Device/Local/Local.EnumerateDevices.cs @@ -136,7 +136,7 @@ internal static IEnumerable EnumerateDevicesNative(SafeCmConnectMach // Start at the "Root" of the device tree. - using (var safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref classGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_ALLCLASSES | NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_PRESENT | NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_DEVICEINTERFACE, IntPtr.Zero, hostName, IntPtr.Zero)) + using (var safeHandle = NativeMethods.SetupDiGetClassDevsEx(ref classGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_PRESENT | NativeMethods.DEVICE_INFORMATION_FLAGS.DIGCF_DEVICEINTERFACE, IntPtr.Zero, hostName, IntPtr.Zero)) { var lastError = Marshal.GetLastWin32Error(); diff --git a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs index f71c1aab3..a14c20097 100644 --- a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs @@ -78,7 +78,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isD if (volDiskExtents.HasValue) foreach (var extent in volDiskExtents.Value.Extents) { - var newDeviceNumber = (int)extent.DiskNumber; + var newDeviceNumber = (int) extent.DiskNumber; if (getByDeviceNumber && deviceNumber != newDeviceNumber) continue; diff --git a/AlphaFS/Device/Native Other/STORAGE_DEVICE_TYPE.cs b/AlphaFS/Device/Native Other/DEVICE_TYPE.cs similarity index 95% rename from AlphaFS/Device/Native Other/STORAGE_DEVICE_TYPE.cs rename to AlphaFS/Device/Native Other/DEVICE_TYPE.cs index 040c1088f..31705ecb6 100644 --- a/AlphaFS/Device/Native Other/STORAGE_DEVICE_TYPE.cs +++ b/AlphaFS/Device/Native Other/DEVICE_TYPE.cs @@ -23,15 +23,8 @@ namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { - // STORAGE_DEVICE_NUMBER structure. - // 2018-01-17: https://msdn.microsoft.com/en-us/library/bb968801(VS.85).aspx - - // The type of device. Values from 0 through 32,767 are reserved for use by Microsoft. - // Values from 32,768 through 65,535 are reserved for use by other vendors. The following values are defined by Microsoft. - - /// The storage device type. - internal enum STORAGE_DEVICE_TYPE + internal enum DEVICE_TYPE { /// FILE_DEVICE_BEEP parameter. FILE_DEVICE_BEEP = 1, diff --git a/AlphaFS/Device/Native Other/DISK_EXTENT.cs b/AlphaFS/Device/Native Other/DISK_EXTENT.cs index ad036d62f..f4886104f 100644 --- a/AlphaFS/Device/Native Other/DISK_EXTENT.cs +++ b/AlphaFS/Device/Native Other/DISK_EXTENT.cs @@ -25,6 +25,13 @@ namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { + // MSDN: Regardless of the disk type, a disk can contain one or more disk extents. + // A disk extent is a contiguous range of logical blocks exposed by the disk. For example, a disk extent can represent an entire volume, + // one portion of a spanned volume, one member of a striped volume, or one plex of a mirrored volume. + + + + /// Represents a disk extent. /// /// Minimum supported client: Windows XP [desktop apps only] diff --git a/AlphaFS/Device/Native Other/DISK_GEOMETRY.cs b/AlphaFS/Device/Native Other/DISK_GEOMETRY.cs index 165b76a1e..d365a3c62 100644 --- a/AlphaFS/Device/Native Other/DISK_GEOMETRY.cs +++ b/AlphaFS/Device/Native Other/DISK_GEOMETRY.cs @@ -36,7 +36,7 @@ internal struct DISK_GEOMETRY [MarshalAs(UnmanagedType.I8)] public readonly long Cylinders; /// The type of media. - [MarshalAs(UnmanagedType.U4)] public readonly STORAGE_MEDIA_TYPE MediaType; + [MarshalAs(UnmanagedType.U4)] public readonly MEDIA_TYPE MediaType; /// The number of tracks per cylinder. [MarshalAs(UnmanagedType.U4)] public readonly uint TracksPerCylinder; diff --git a/AlphaFS/Device/Native Other/IoControlCode.cs b/AlphaFS/Device/Native Other/IoControlCode.cs index 6b9db4f58..27d1516a6 100644 --- a/AlphaFS/Device/Native Other/IoControlCode.cs +++ b/AlphaFS/Device/Native Other/IoControlCode.cs @@ -30,11 +30,11 @@ internal static partial class NativeMethods internal enum IoControlCode : uint { /// Retrieves the physical location of a specified volume on one or more disks. - IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// Return properties of a storage device or adapter. The request indicates the kind of information to retrieve, such as inquiry data for a device or capabilities and limitations of an adapter. - IOCTL_STORAGE_QUERY_PROPERTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x500 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_STORAGE_QUERY_PROPERTY = (DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x500 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), #region FILE_DEVICE_MASS_STORAGE @@ -124,7 +124,7 @@ internal enum IoControlCode : uint /// Returns a STORAGE_DEVICE_NUMBER structure that contains the FILE_DEVICE_XXX type, device number, and, for a partitionable device, /// the partition number assigned to a device by the driver when the device is started. This request is usually issued by a fault-tolerant disk driver. /// - IOCTL_STORAGE_GET_DEVICE_NUMBER = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0420 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_STORAGE_GET_DEVICE_NUMBER = (DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0420 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -142,7 +142,7 @@ internal enum IoControlCode : uint /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). /// IOCTL_DISK_GET_DRIVE_GEOMETRY_EX can retrieve information from both Master Boot Record (MBR) and GUID Partition Table (GPT)-type partitioned media. /// - IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0028 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0028 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///////// Returns information about the type, size, and nature of a disk partition. (Floppy drivers need not handle this request.) @@ -154,7 +154,7 @@ internal enum IoControlCode : uint /// Contains extended information about a drive's partitions. - IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0014 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0014 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Repartitions a disk as specified. (Floppy drivers need not handle this request.) @@ -220,7 +220,7 @@ internal enum IoControlCode : uint /// Retrieves the length of the specified disk, volume, or partition. /// This operation should be used instead of IOCTL_DISK_GET_PARTITION_INFO_EX for volumes that do not have partition info, such as partition type or number of hidden sectors. - IOCTL_DISK_GET_LENGTH_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0017 << 2) | IoControlMethod.Buffered | (FileAccess.Read << 14), + IOCTL_DISK_GET_LENGTH_INFO = (DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0017 << 2) | IoControlMethod.Buffered | (FileAccess.Read << 14), ///// Returns version information, a capabilities mask, and a bitmask for the device. This IOCTL must be handled by drivers that support Self-Monitoring Analysis and Reporting Technology (SMART). @@ -406,7 +406,7 @@ internal enum IoControlCode : uint /// Sets the compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. You can use FSCTL_SET_COMPRESSION to compress or uncompress a file or directory on such a volume. - FSCTL_SET_COMPRESSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (16 << 2) | IoControlMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + FSCTL_SET_COMPRESSION = (DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (16 << 2) | IoControlMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// @@ -530,7 +530,7 @@ internal enum IoControlCode : uint /// Minifilters should use FltTagFile instead of FSCTL_SET_REPARSE_POINT to set a reparse point. /// For more information about reparse points and the FSCTL_SET_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_SET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (41 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + FSCTL_SET_REPARSE_POINT = (DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (41 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// @@ -538,7 +538,7 @@ internal enum IoControlCode : uint /// To perform this operation, call FltFsControlFile or ZwFsControlFile with the following parameters. /// For more information about reparse points and the FSCTL_GET_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_GET_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (42 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + FSCTL_GET_REPARSE_POINT = (DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (42 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// @@ -548,7 +548,7 @@ internal enum IoControlCode : uint /// Minifilters should use FltUntagFile instead of FSCTL_DELETE_REPARSE_POINT to delete a reparse point. /// For more information about reparse points and the FSCTL_DELETE_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_DELETE_REPARSE_POINT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (43 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + FSCTL_DELETE_REPARSE_POINT = (DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (43 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// diff --git a/AlphaFS/Device/Native Other/STORAGE_MEDIA_TYPE.cs b/AlphaFS/Device/Native Other/MEDIA_TYPE.cs similarity index 95% rename from AlphaFS/Device/Native Other/STORAGE_MEDIA_TYPE.cs rename to AlphaFS/Device/Native Other/MEDIA_TYPE.cs index 3ff776e7c..bdb035df0 100644 --- a/AlphaFS/Device/Native Other/STORAGE_MEDIA_TYPE.cs +++ b/AlphaFS/Device/Native Other/MEDIA_TYPE.cs @@ -23,11 +23,12 @@ namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { - /// Specifies various types of storage media. Parameters and members of type STORAGE_MEDIA_TYPE also accept values from the MEDIA_TYPE enumeration type. - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// - public enum STORAGE_MEDIA_TYPE + /// Represents the various forms of device media. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + public enum MEDIA_TYPE { /// Format is unknown. Unknown = 0, diff --git a/AlphaFS/Device/Native Other/NativeMethods.EfiPartitionAttributes.cs b/AlphaFS/Device/Native Other/NativeMethods.EfiPartitionAttributes.cs index 0f5f7e60d..cb42eb9de 100644 --- a/AlphaFS/Device/Native Other/NativeMethods.EfiPartitionAttributes.cs +++ b/AlphaFS/Device/Native Other/NativeMethods.EfiPartitionAttributes.cs @@ -26,6 +26,10 @@ namespace Alphaleonis.Win32.Device internal static partial class NativeMethods { /// The Extensible Firmware Interface (EFI) partition attributes. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// [Flags] internal enum EfiPartitionAttributes : ulong { diff --git a/AlphaFS/Device/Native Other/PARTITION_STYLE.cs b/AlphaFS/Device/Native Other/PARTITION_STYLE.cs index 26f24f987..e16b1fbda 100644 --- a/AlphaFS/Device/Native Other/PARTITION_STYLE.cs +++ b/AlphaFS/Device/Native Other/PARTITION_STYLE.cs @@ -23,10 +23,11 @@ namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { - /// Represents the format of a partition. - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// Represents the format of a partition. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// internal enum PARTITION_STYLE { /// Master boot record (MBR) format. This corresponds to standard AT-style MBR partitions. diff --git a/AlphaFS/Device/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs b/AlphaFS/Device/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs index 7d173cc6f..ad6dbc3d9 100644 --- a/AlphaFS/Device/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs +++ b/AlphaFS/Device/Native Other/STORAGE_ADAPTER_DESCRIPTOR.cs @@ -26,10 +26,11 @@ namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { - /// Used with the control code to retrieve the storage adapter descriptor data for a device. - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// Used with the control code to retrieve the storage adapter descriptor data for a device. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct STORAGE_ADAPTER_DESCRIPTOR { diff --git a/AlphaFS/Device/Native Other/STORAGE_BUS_TYPE.cs b/AlphaFS/Device/Native Other/STORAGE_BUS_TYPE.cs index 0d02dff4d..56c5c9f6c 100644 --- a/AlphaFS/Device/Native Other/STORAGE_BUS_TYPE.cs +++ b/AlphaFS/Device/Native Other/STORAGE_BUS_TYPE.cs @@ -23,10 +23,11 @@ namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { - /// Provides a symbolic means of representing storage bus types. - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// Provides a symbolic means of representing storage bus types. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// internal enum STORAGE_BUS_TYPE { /// Indicates an unknown bus type. diff --git a/AlphaFS/Device/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs b/AlphaFS/Device/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs index ef753040d..c01f317f2 100644 --- a/AlphaFS/Device/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs +++ b/AlphaFS/Device/Native Other/STORAGE_DEVICE_DESCRIPTOR.cs @@ -26,6 +26,10 @@ namespace Alphaleonis.Win32.Device internal static partial class NativeMethods { /// Used in conjunction with the IOCTL_STORAGE_QUERY_PROPERTY control code to retrieve the storage device descriptor data for a device. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct STORAGE_DEVICE_DESCRIPTOR { diff --git a/AlphaFS/Device/Native Other/STORAGE_DEVICE_NUMBER.cs b/AlphaFS/Device/Native Other/STORAGE_DEVICE_NUMBER.cs index cec0426f2..175246d62 100644 --- a/AlphaFS/Device/Native Other/STORAGE_DEVICE_NUMBER.cs +++ b/AlphaFS/Device/Native Other/STORAGE_DEVICE_NUMBER.cs @@ -25,17 +25,16 @@ namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { - /// - /// The STORAGE_DEVICE_NUMBER structure is used in conjunction with the IOCTL_STORAGE_GET_DEVICE_NUMBER request to retrieve the FILE_DEVICE_XXX device type, - /// the device number, and, for a device that can be partitioned, the partition number assigned to a device by the driver when the device is started. - /// The values in the STORAGE_DEVICE_NUMBER structure are guaranteed to remain unchanged until the device is removed or the system is restarted. - /// It is not guaranteed to be persistent across device restarts or system restarts. - /// + /// Contains information about a device. This structure is used by the IOCTL_STORAGE_GET_DEVICE_NUMBER control code. + /// + /// Minimum supported client: Windows XP + /// Minimum supported server: Windows Server 2003 + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct STORAGE_DEVICE_NUMBER { /// Specifies one of the system-defined FILE_DEVICE_XXX constants indicating the type of device (such as FILE_DEVICE_DISK, FILE_DEVICE_KEYBOARD, and so forth) or a vendor-defined value for a new type of device. - [MarshalAs(UnmanagedType.U4)] internal readonly StorageDeviceType DeviceType; + [MarshalAs(UnmanagedType.U4)] internal readonly DeviceType DeviceType; /// Indicates the number of this device. This value is set to 0xFFFFFFFF (-1) for the disks that represent the physical paths of an MPIO disk. [MarshalAs(UnmanagedType.U4)] diff --git a/AlphaFS/Device/Native Other/STORAGE_PROPERTY_ID.cs b/AlphaFS/Device/Native Other/STORAGE_PROPERTY_ID.cs index 0ad8fbfa5..71224b85f 100644 --- a/AlphaFS/Device/Native Other/STORAGE_PROPERTY_ID.cs +++ b/AlphaFS/Device/Native Other/STORAGE_PROPERTY_ID.cs @@ -23,10 +23,11 @@ namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { - /// Enumerates the possible values of the PropertyId member of the structure passed as input to the IOCTL_STORAGE_QUERY_PROPERTY request to retrieve the properties of a storage device or adapter. - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// Enumerates the possible values of the PropertyId member of the structure passed as input to the IOCTL_STORAGE_QUERY_PROPERTY request to retrieve the properties of a storage device or adapter. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// public enum STORAGE_PROPERTY_ID { /// Indicates that the caller is querying for the device descriptor, . @@ -35,7 +36,7 @@ public enum STORAGE_PROPERTY_ID /// Indicates that the caller is querying for the adapter descriptor, . StorageAdapterProperty - ///// Indicates that the caller is querying for the device identifiers provided with the SCSI vital product data pages. Data is returned using the structure. + ///// Indicates that the caller is querying for the device identifiers provided with the SCSI vital product data pages. Data is returned using the STORAGE_DEVICE_ID_DESCRIPTOR structure. //StorageDeviceIdProperty, ///// Indicates that the caller is querying for the unique device identifiers. Data is returned using the STORAGE_DEVICE_UNIQUE_IDENTIFIER structure. diff --git a/AlphaFS/Device/Native Other/STORAGE_PROPERTY_QUERY.cs b/AlphaFS/Device/Native Other/STORAGE_PROPERTY_QUERY.cs index 342e1e69b..578e6a495 100644 --- a/AlphaFS/Device/Native Other/STORAGE_PROPERTY_QUERY.cs +++ b/AlphaFS/Device/Native Other/STORAGE_PROPERTY_QUERY.cs @@ -26,6 +26,10 @@ namespace Alphaleonis.Win32.Device internal static partial class NativeMethods { /// Indicates the properties of a storage device or adapter to retrieve as the input buffer passed to the IOCTL_STORAGE_QUERY_PROPERTY control code. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct STORAGE_PROPERTY_QUERY { diff --git a/AlphaFS/Device/Native Other/STORAGE_QUERY_TYPE.cs b/AlphaFS/Device/Native Other/STORAGE_QUERY_TYPE.cs index a428babb4..69323a3c3 100644 --- a/AlphaFS/Device/Native Other/STORAGE_QUERY_TYPE.cs +++ b/AlphaFS/Device/Native Other/STORAGE_QUERY_TYPE.cs @@ -23,10 +23,11 @@ namespace Alphaleonis.Win32.Device { internal static partial class NativeMethods { - /// Used by the structure passed to the IOCTL_STORAGE_QUERY_PROPERTY control code to indicate what information is returned about a property of a storage device or adapter. - /// Minimum supported client: Windows XP [desktop apps only] - /// Minimum supported server: Windows Server 2003 [desktop apps only] - /// + /// Used by the structure passed to the IOCTL_STORAGE_QUERY_PROPERTY control code to indicate what information is returned about a property of a storage device or adapter. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// public enum STORAGE_QUERY_TYPE { /// Instructs the driver to return an appropriate descriptor. diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index 774fb3065..f6e5aeebb 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -119,6 +119,8 @@ private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, if (!SetDeviceInfoDataFromDeviceNumber(isElevated, deviceNumber, deviceInfo)) return; + var dosDeviceName = isDrive ? Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)) : null; + // If physicalDriveNumberPath != null, the drive is opened using: "\\.\PhysicalDriveX" path format // which is the device, not the volume/logical drive. @@ -142,9 +144,13 @@ private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, // The Win32 API to retrieve the total size of the device requires an elevated process or the TotalSize is 0. // The Win32 API to retrieve the total size of the device partition does not require elevation, so use that value. - if (!isElevated && StorageDeviceInfo.TotalSize == 0 && null != StoragePartitionInfo) + if (StoragePartitionInfo.OnDynamicDisk && null != dosDeviceName) + + StorageDeviceInfo.TotalSize = new DiskSpaceInfo(dosDeviceName, false, true, true).TotalNumberOfBytes; + + else if (!isElevated && StorageDeviceInfo.TotalSize == 0 && null != StoragePartitionInfo) - StorageDeviceInfo.TotalSize = isDevice ? StoragePartitionInfo.TotalSize : new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; + StorageDeviceInfo.TotalSize = isDevice ? StoragePartitionInfo.TotalSize : new DiskSpaceInfo(dosDeviceName ?? localDevicePath, false, true, true).TotalNumberOfBytes; } diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 7b728b86a..1ec58de0e 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -42,7 +42,7 @@ public sealed class StorageDeviceInfo /// [AlphaFS] Initializes an empty StorageDeviceInfo instance. public StorageDeviceInfo() { - DeviceType = StorageDeviceType.Unknown; + DeviceType = Device.DeviceType.Unknown; DeviceNumber = -1; @@ -77,7 +77,7 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() /// The storage device type. - public StorageDeviceType DeviceType { get; private set; } + public DeviceType DeviceType { get; private set; } /// The device number of the storage device, starting at 0. diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index 00b9db9ab..f0bfa275c 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -123,6 +123,11 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis } break; + + + default: + Console.WriteLine(); + break; } diff --git a/AlphaFS/Device/Structures, Enumerations/StorageDeviceType.cs b/AlphaFS/Device/Structures, Enumerations/DeviceType.cs similarity index 61% rename from AlphaFS/Device/Structures, Enumerations/StorageDeviceType.cs rename to AlphaFS/Device/Structures, Enumerations/DeviceType.cs index 160e2f4f5..b2a3a22a6 100644 --- a/AlphaFS/Device/Structures, Enumerations/StorageDeviceType.cs +++ b/AlphaFS/Device/Structures, Enumerations/DeviceType.cs @@ -26,255 +26,255 @@ namespace Alphaleonis.Win32.Device /// The type of device. Values from 0 through 32,767 are reserved for use by Microsoft. Values from 32,768 through 65,535 are reserved for use by other vendors. /// The following values are defined by Microsoft. [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags", Justification = "Enum values should not be combinable.")] - public enum StorageDeviceType + public enum DeviceType { /// Indicates an unknown storage device type. None = 0, /// FILE_DEVICE_BEEP parameter. - Beep = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BEEP, + Beep = NativeMethods.DEVICE_TYPE.FILE_DEVICE_BEEP, /// FILE_DEVICE_CD_ROM parameter. - CDRom = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM, // .NET DriveInfo.DriveType property also uses "CDRom" instead of "CdRom". + CDRom = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CD_ROM, // .NET DriveInfo.DriveType property also uses "CDRom" instead of "CdRom". /// FILE_DEVICE_CD_ROM_FILE_SYSTEM parameter. - CDRomFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CD_ROM_FILE_SYSTEM, + CDRomFileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CD_ROM_FILE_SYSTEM, /// FILE_DEVICE_CONTROLLER parameter. - Controller = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CONTROLLER, + Controller = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CONTROLLER, /// FILE_DEVICE_DATALINK parameter. - DataLink = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DATALINK, + DataLink = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DATALINK, /// FILE_DEVICE_DFS parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] - Dfs = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS, + Dfs = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DFS, /// FILE_DEVICE_DISK parameter. - Disk = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK, + Disk = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DISK, /// FILE_DEVICE_DISK_FILE_SYSTEM parameter. - DiskFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK_FILE_SYSTEM, + DiskFileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DISK_FILE_SYSTEM, /// FILE_DEVICE_FILE_SYSTEM parameter. - FileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM, + FileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM, /// FILE_DEVICE_INPORT_PORT parameter. - InPort = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_INPORT_PORT, + InPort = NativeMethods.DEVICE_TYPE.FILE_DEVICE_INPORT_PORT, /// FILE_DEVICE_KEYBOARD parameter. - Keyboard = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_KEYBOARD, + Keyboard = NativeMethods.DEVICE_TYPE.FILE_DEVICE_KEYBOARD, /// FILE_DEVICE_MAILSLOT parameter. - MailSlot = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MAILSLOT, + MailSlot = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MAILSLOT, /// FILE_DEVICE_MIDI_IN parameter. - MidiIn = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MIDI_IN, + MidiIn = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MIDI_IN, /// FILE_DEVICE_MIDI_OUT parameter. - MidiOut = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MIDI_OUT, + MidiOut = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MIDI_OUT, /// FILE_DEVICE_MOUSE parameter. - Mouse = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MOUSE, + Mouse = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MOUSE, /// FILE_DEVICE_MULTI_UNC_PROVIDER parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi")] - MultiUncProvider = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MULTI_UNC_PROVIDER, + MultiUncProvider = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MULTI_UNC_PROVIDER, /// FILE_DEVICE_NAMED_PIPE parameter. - NamedPipe = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NAMED_PIPE, + NamedPipe = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NAMED_PIPE, /// FILE_DEVICE_NETWORK parameter. - Network = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NETWORK, + Network = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NETWORK, /// FILE_DEVICE_NETWORK_BROWSER parameter. - NetworkBrowser = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NETWORK_BROWSER, + NetworkBrowser = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NETWORK_BROWSER, /// FILE_DEVICE_NETWORK_FILE_SYSTEM parameter. - NetworkFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NETWORK_FILE_SYSTEM, + NetworkFileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NETWORK_FILE_SYSTEM, /// FILE_DEVICE_NULL parameter. - NullDevice = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NULL, + NullDevice = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NULL, /// FILE_DEVICE_PARALLEL_PORT parameter. - ParallelPort = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_PARALLEL_PORT, + ParallelPort = NativeMethods.DEVICE_TYPE.FILE_DEVICE_PARALLEL_PORT, /// FILE_DEVICE_PHYSICAL_NETCARD parameter. - PhysicalNetCard = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_PHYSICAL_NETCARD, + PhysicalNetCard = NativeMethods.DEVICE_TYPE.FILE_DEVICE_PHYSICAL_NETCARD, /// FILE_DEVICE_PRINTER parameter. - Printer = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_PRINTER, + Printer = NativeMethods.DEVICE_TYPE.FILE_DEVICE_PRINTER, /// FILE_DEVICE_SCANNER parameter. - Scanner = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SCANNER, + Scanner = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SCANNER, /// FILE_DEVICE_SERIAL_MOUSE_PORT parameter. - SerialMousePort = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SERIAL_MOUSE_PORT, + SerialMousePort = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SERIAL_MOUSE_PORT, /// FILE_DEVICE_SERIAL_PORT parameter. - SerialPort = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SERIAL_PORT, + SerialPort = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SERIAL_PORT, /// FILE_DEVICE_SCREEN parameter. - Screen = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SCREEN, + Screen = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SCREEN, /// FILE_DEVICE_SOUND parameter. - Sound = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SOUND, + Sound = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SOUND, /// FILE_DEVICE_STREAMS parameter. - Streams = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_STREAMS, + Streams = NativeMethods.DEVICE_TYPE.FILE_DEVICE_STREAMS, /// FILE_DEVICE_TAPE parameter. - Tape = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_TAPE, + Tape = NativeMethods.DEVICE_TYPE.FILE_DEVICE_TAPE, /// FILE_DEVICE_TAPE_FILE_SYSTEM parameter. - TapeFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_TAPE_FILE_SYSTEM, + TapeFileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_TAPE_FILE_SYSTEM, /// FILE_DEVICE_TRANSPORT parameter. - Transport = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_TRANSPORT, + Transport = NativeMethods.DEVICE_TYPE.FILE_DEVICE_TRANSPORT, /// FILE_DEVICE_UNKNOWN parameter. - Unknown = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_UNKNOWN, + Unknown = NativeMethods.DEVICE_TYPE.FILE_DEVICE_UNKNOWN, /// FILE_DEVICE_VIDEO parameter. - Video = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VIDEO, + Video = NativeMethods.DEVICE_TYPE.FILE_DEVICE_VIDEO, /// FILE_DEVICE_VIRTUAL_DISK parameter. - VirtualDisk = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VIRTUAL_DISK, + VirtualDisk = NativeMethods.DEVICE_TYPE.FILE_DEVICE_VIRTUAL_DISK, /// FILE_DEVICE_WAVE_IN parameter. - WaveIn = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_WAVE_IN, + WaveIn = NativeMethods.DEVICE_TYPE.FILE_DEVICE_WAVE_IN, /// FILE_DEVICE_WAVE_OUT parameter. - WaveOut = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_WAVE_OUT, + WaveOut = NativeMethods.DEVICE_TYPE.FILE_DEVICE_WAVE_OUT, /// FILE_DEVICE_8042_PORT parameter. - Port8042 = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_8042_PORT, + Port8042 = NativeMethods.DEVICE_TYPE.FILE_DEVICE_8042_PORT, /// FILE_DEVICE_NETWORK_REDIRECTOR parameter. - NetworkRedirector = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NETWORK_REDIRECTOR, + NetworkRedirector = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NETWORK_REDIRECTOR, /// FILE_DEVICE_BATTERY parameter. - Battery = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BATTERY, + Battery = NativeMethods.DEVICE_TYPE.FILE_DEVICE_BATTERY, /// FILE_DEVICE_BUS_EXTENDER parameter. - BusExtender = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BUS_EXTENDER, + BusExtender = NativeMethods.DEVICE_TYPE.FILE_DEVICE_BUS_EXTENDER, /// FILE_DEVICE_MODEM parameter. - Modem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MODEM, + Modem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MODEM, /// FILE_DEVICE_VDM parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vdm")] - Vdm = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VDM, + Vdm = NativeMethods.DEVICE_TYPE.FILE_DEVICE_VDM, /// FILE_DEVICE_MASS_STORAGE parameter. - MassStorage = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE, + MassStorage = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE, /// FILE_DEVICE_SMB parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smb")] - Smb = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SMB, + Smb = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SMB, /// FILE_DEVICE_KS parameter. - KS = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_KS, + KS = NativeMethods.DEVICE_TYPE.FILE_DEVICE_KS, /// FILE_DEVICE_CHANGER parameter. - Changer = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER, + Changer = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CHANGER, /// FILE_DEVICE_SMARTCARD parameter. - Smartcard = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SMARTCARD, + Smartcard = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SMARTCARD, /// FILE_DEVICE_ACPI parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Acpi")] - Acpi = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_ACPI, + Acpi = NativeMethods.DEVICE_TYPE.FILE_DEVICE_ACPI, /// FILE_DEVICE_DVD parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dvd")] - Dvd = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DVD, + Dvd = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DVD, /// FILE_DEVICE_FULLSCREEN_VIDEO parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fullscreen")] - FullscreenVideo = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_FULLSCREEN_VIDEO, + FullscreenVideo = NativeMethods.DEVICE_TYPE.FILE_DEVICE_FULLSCREEN_VIDEO, /// FILE_DEVICE_DFS_FILE_SYSTEM parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] - DfsFileSystem = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS_FILE_SYSTEM, + DfsFileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DFS_FILE_SYSTEM, /// FILE_DEVICE_DFS_VOLUME parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] - DfsVolume = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DFS_VOLUME, + DfsVolume = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DFS_VOLUME, /// FILE_DEVICE_SERENUM parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Serenum")] - Serenum = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SERENUM, + Serenum = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SERENUM, /// FILE_DEVICE_TERMSRV parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Termsrv")] - Termsrv = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_TERMSRV, + Termsrv = NativeMethods.DEVICE_TYPE.FILE_DEVICE_TERMSRV, /// FILE_DEVICE_KSEC parameter. - KSec = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_KSEC, + KSec = NativeMethods.DEVICE_TYPE.FILE_DEVICE_KSEC, /// FILE_DEVICE_FIPS parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fips")] - Fips = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_FIPS, + Fips = NativeMethods.DEVICE_TYPE.FILE_DEVICE_FIPS, /// FILE_DEVICE_INFINIBAND parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infiniband")] - Infiniband = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_INFINIBAND, + Infiniband = NativeMethods.DEVICE_TYPE.FILE_DEVICE_INFINIBAND, /// FILE_DEVICE_VMBUS parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vm")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vm")] - VmBus = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_VMBUS, + VmBus = NativeMethods.DEVICE_TYPE.FILE_DEVICE_VMBUS, /// FILE_DEVICE_CRYPT_PROVIDER parameter. - CryptProvider = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CRYPT_PROVIDER, + CryptProvider = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CRYPT_PROVIDER, /// FILE_DEVICE_WPD parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wpd")] - Wpd = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_WPD, + Wpd = NativeMethods.DEVICE_TYPE.FILE_DEVICE_WPD, /// FILE_DEVICE_BLUETOOTH parameter. - Bluetooth = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BLUETOOTH, + Bluetooth = NativeMethods.DEVICE_TYPE.FILE_DEVICE_BLUETOOTH, /// FILE_DEVICE_MT_COMPOSITE parameter. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mt")] - MtComposite = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MT_COMPOSITE, + MtComposite = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MT_COMPOSITE, /// FILE_DEVICE_MT_TRANSPORT parameter. - MTTransport = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_MT_TRANSPORT, + MTTransport = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MT_TRANSPORT, /// FILE_DEVICE_BIOMETRIC parameter. - Biometric = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_BIOMETRIC, + Biometric = NativeMethods.DEVICE_TYPE.FILE_DEVICE_BIOMETRIC, /// FILE_DEVICE_PMI parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pmi")] - Pmi = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_PMI, + Pmi = NativeMethods.DEVICE_TYPE.FILE_DEVICE_PMI, /// FILE_DEVICE_EHSTOR parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ehstor")] - Ehstor = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_EHSTOR, + Ehstor = NativeMethods.DEVICE_TYPE.FILE_DEVICE_EHSTOR, /// FILE_DEVICE_DEVAPI parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Devapi")] - Devapi = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_DEVAPI, + Devapi = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DEVAPI, /// FILE_DEVICE_GPIO parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpio")] - Gpio = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_GPIO, + Gpio = NativeMethods.DEVICE_TYPE.FILE_DEVICE_GPIO, /// FILE_DEVICE_USBEX parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usbex")] - Usbex = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_USBEX, + Usbex = NativeMethods.DEVICE_TYPE.FILE_DEVICE_USBEX, /// FILE_DEVICE_CONSOLE parameter. - Console = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_CONSOLE, + Console = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CONSOLE, /// FILE_DEVICE_NFP parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nfp")] - Nfp = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_NFP, + Nfp = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NFP, /// FILE_DEVICE_SYSENV parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sysenv")] - Sysenv = NativeMethods.STORAGE_DEVICE_TYPE.FILE_DEVICE_SYSENV + Sysenv = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SYSENV } } diff --git a/AlphaFS/Device/Structures, Enumerations/StorageMediaType.cs b/AlphaFS/Device/Structures, Enumerations/StorageMediaType.cs index b414c4fc4..30898dba9 100644 --- a/AlphaFS/Device/Structures, Enumerations/StorageMediaType.cs +++ b/AlphaFS/Device/Structures, Enumerations/StorageMediaType.cs @@ -28,396 +28,396 @@ namespace Alphaleonis.Win32.Device public enum StorageMediaType { /// Format is unknown. - Unknown = NativeMethods.STORAGE_MEDIA_TYPE.Unknown, + Unknown = NativeMethods.MEDIA_TYPE.Unknown, /// A 5.25" floppy, with 1.2MB and 512 bytes/sector. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] - Floppy51Pt2512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_1Pt2_512, + Floppy51Pt2512 = NativeMethods.MEDIA_TYPE.F5_1Pt2_512, /// A 3.5" floppy, with 1.44MB and 512 bytes/sector. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] - Floppy31Pt44512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_1Pt44_512, + Floppy31Pt44512 = NativeMethods.MEDIA_TYPE.F3_1Pt44_512, /// A 3.5" floppy, with 2.88MB and 512 bytes/sector. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] - Floppy32Pt88512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_2Pt88_512, + Floppy32Pt88512 = NativeMethods.MEDIA_TYPE.F3_2Pt88_512, /// A 3.5" floppy, with 20.8MB and 512 bytes/sector. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] - Floppy320Pt8512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_20Pt8_512, + Floppy320Pt8512 = NativeMethods.MEDIA_TYPE.F3_20Pt8_512, /// A 3.5" floppy, with 720KB and 512 bytes/sector. - Floppy3720512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_720_512, + Floppy3720512 = NativeMethods.MEDIA_TYPE.F3_720_512, /// A 5.25" floppy, with 360KB and 512 bytes/sector. - Floppy5360512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_360_512, + Floppy5360512 = NativeMethods.MEDIA_TYPE.F5_360_512, /// A 5.25" floppy, with 320KB and 512 bytes/sector. - Floppy5320512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_320_512, + Floppy5320512 = NativeMethods.MEDIA_TYPE.F5_320_512, /// A 5.25" floppy, with 320KB and 1024 bytes/sector. - Floppy53201024 = NativeMethods.STORAGE_MEDIA_TYPE.F5_320_1024, + Floppy53201024 = NativeMethods.MEDIA_TYPE.F5_320_1024, /// A 5.25" floppy, with 180KB and 512 bytes/sector. - Floppy5180512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_180_512, + Floppy5180512 = NativeMethods.MEDIA_TYPE.F5_180_512, /// A 5.25" floppy, with 160KB and 512 bytes/sector. - Floppy5160512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_160_512, + Floppy5160512 = NativeMethods.MEDIA_TYPE.F5_160_512, /// Removable media other than floppy. - RemovableMedia = NativeMethods.STORAGE_MEDIA_TYPE.RemovableMedia, + RemovableMedia = NativeMethods.MEDIA_TYPE.RemovableMedia, /// Fixed hard disk media. - FixedMedia = NativeMethods.STORAGE_MEDIA_TYPE.FixedMedia, + FixedMedia = NativeMethods.MEDIA_TYPE.FixedMedia, /// A 3.5" floppy, with 120MB and 512 bytes/sector. - Floppy3120M512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_120M_512, + Floppy3120M512 = NativeMethods.MEDIA_TYPE.F3_120M_512, /// A 3.5" floppy, with 640KB and 512 bytes/sector. - Floppy3640512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_640_512, + Floppy3640512 = NativeMethods.MEDIA_TYPE.F3_640_512, /// A 5.25" floppy, with 640KB and 512 bytes/sector. - Floppy5640512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_640_512, + Floppy5640512 = NativeMethods.MEDIA_TYPE.F5_640_512, /// A 5.25" floppy, with 720KB and 512 bytes/sector. - Floppy5720512 = NativeMethods.STORAGE_MEDIA_TYPE.F5_720_512, + Floppy5720512 = NativeMethods.MEDIA_TYPE.F5_720_512, /// A 3.5" floppy, with 1.2MB and 512 bytes/sector. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] - Floppy31Pt2512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_1Pt2_512, + Floppy31Pt2512 = NativeMethods.MEDIA_TYPE.F3_1Pt2_512, /// A 3.5" floppy, with 1.23MB and 1024 bytes/sector. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] - Floppy31Pt231024 = NativeMethods.STORAGE_MEDIA_TYPE.F3_1Pt23_1024, + Floppy31Pt231024 = NativeMethods.MEDIA_TYPE.F3_1Pt23_1024, /// A 5.25" floppy, with 1.23MB and 1024 bytes/sector. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pt")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pt")] - Floppy51Pt231024 = NativeMethods.STORAGE_MEDIA_TYPE.F5_1Pt23_1024, + Floppy51Pt231024 = NativeMethods.MEDIA_TYPE.F5_1Pt23_1024, /// A 3.5" floppy, with 128MB and 512 bytes/sector. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mb")] - Floppy3128Mb512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_128Mb_512, + Floppy3128Mb512 = NativeMethods.MEDIA_TYPE.F3_128Mb_512, /// A 3.5" floppy, with 230MB and 512 bytes/sector. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mb")] - Floppy3230Mb512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_230Mb_512, + Floppy3230Mb512 = NativeMethods.MEDIA_TYPE.F3_230Mb_512, /// An 8" floppy, with 256KB and 128 bytes/sector. - Floppy8256128 = NativeMethods.STORAGE_MEDIA_TYPE.F8_256_128, + Floppy8256128 = NativeMethods.MEDIA_TYPE.F8_256_128, /// A 3.5" floppy, with 200MB and 512 bytes/sector. (HiFD). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mb")] - Floppy3200Mb512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_200Mb_512, + Floppy3200Mb512 = NativeMethods.MEDIA_TYPE.F3_200Mb_512, /// A 3.5" floppy, with 240MB and 512 bytes/sector. (HiFD). - Floppy3240M512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_240M_512, + Floppy3240M512 = NativeMethods.MEDIA_TYPE.F3_240M_512, /// A 3.5" floppy, with 32MB and 512 bytes/sector. - Floppy332M512 = NativeMethods.STORAGE_MEDIA_TYPE.F3_32M_512, + Floppy332M512 = NativeMethods.MEDIA_TYPE.F3_32M_512, /// One of the following tape types: DAT, DDS1, DDS2, and so on. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dds")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] - Dds4Mm = NativeMethods.STORAGE_MEDIA_TYPE.DDS_4mm, + Dds4Mm = NativeMethods.MEDIA_TYPE.DDS_4mm, /// MiniQIC tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Qic")] - MiniQic = NativeMethods.STORAGE_MEDIA_TYPE.MiniQic, + MiniQic = NativeMethods.MEDIA_TYPE.MiniQic, /// Travan tape (TR-1, TR-2, TR-3, and so on). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Travan")] - Travan = NativeMethods.STORAGE_MEDIA_TYPE.Travan, + Travan = NativeMethods.MEDIA_TYPE.Travan, /// QIC tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Qic")] - Qic = NativeMethods.STORAGE_MEDIA_TYPE.QIC, + Qic = NativeMethods.MEDIA_TYPE.QIC, /// An 8mm Exabyte metal particle tape. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mp")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mp")] - Mp8Mm = NativeMethods.STORAGE_MEDIA_TYPE.MP_8mm, + Mp8Mm = NativeMethods.MEDIA_TYPE.MP_8mm, /// An 8mm Exabyte advanced metal evaporative tape. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ame")] - Ame8Mm = NativeMethods.STORAGE_MEDIA_TYPE.AME_8mm, + Ame8Mm = NativeMethods.MEDIA_TYPE.AME_8mm, /// An 8mm Sony AIT1 tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ait")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] - Ait18Mm = NativeMethods.STORAGE_MEDIA_TYPE.AIT1_8mm, + Ait18Mm = NativeMethods.MEDIA_TYPE.AIT1_8mm, /// DLT compact tape (IIIxt or IV). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dlt")] - Dlt = NativeMethods.STORAGE_MEDIA_TYPE.DLT, + Dlt = NativeMethods.MEDIA_TYPE.DLT, /// Philips NCTP tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nctp")] - Nctp = NativeMethods.STORAGE_MEDIA_TYPE.NCTP, + Nctp = NativeMethods.MEDIA_TYPE.NCTP, /// IBM 3480 tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] - Ibm3480 = NativeMethods.STORAGE_MEDIA_TYPE.IBM_3480, + Ibm3480 = NativeMethods.MEDIA_TYPE.IBM_3480, /// IBM 3490E tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] - Ibm3490E = NativeMethods.STORAGE_MEDIA_TYPE.IBM_3490E, + Ibm3490E = NativeMethods.MEDIA_TYPE.IBM_3490E, /// IBM Magstar 3590 tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Magstar")] - IbmMagstar3590 = NativeMethods.STORAGE_MEDIA_TYPE.IBM_Magstar_3590, + IbmMagstar3590 = NativeMethods.MEDIA_TYPE.IBM_Magstar_3590, /// IBM Magstar MP tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Magstar")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ibm")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mp")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mp")] - IbmMagstarMp = NativeMethods.STORAGE_MEDIA_TYPE.IBM_Magstar_MP, + IbmMagstarMp = NativeMethods.MEDIA_TYPE.IBM_Magstar_MP, /// STK data D3 tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Stk")] - StkDataD3 = NativeMethods.STORAGE_MEDIA_TYPE.STK_DATA_D3, + StkDataD3 = NativeMethods.MEDIA_TYPE.STK_DATA_D3, /// Sony DTF tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dtf")] - SonyDtf = NativeMethods.STORAGE_MEDIA_TYPE.SONY_DTF, + SonyDtf = NativeMethods.MEDIA_TYPE.SONY_DTF, /// A 6mm digital videotape. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Dv")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dv")] - Dv6Mm = NativeMethods.STORAGE_MEDIA_TYPE.DV_6mm, + Dv6Mm = NativeMethods.MEDIA_TYPE.DV_6mm, /// Exabyte DMI tape (or compatible). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dmi")] - Dmi = NativeMethods.STORAGE_MEDIA_TYPE.DMI, + Dmi = NativeMethods.MEDIA_TYPE.DMI, /// Sony D2S or D2L tape. - SonyD2 = NativeMethods.STORAGE_MEDIA_TYPE.SONY_D2, + SonyD2 = NativeMethods.MEDIA_TYPE.SONY_D2, /// Cleaner (all drive types that support cleaners). - CleanerCartridge = NativeMethods.STORAGE_MEDIA_TYPE.CLEANER_CARTRIDGE, + CleanerCartridge = NativeMethods.MEDIA_TYPE.CLEANER_CARTRIDGE, /// CD. - CDRom = NativeMethods.STORAGE_MEDIA_TYPE.CD_ROM, + CDRom = NativeMethods.MEDIA_TYPE.CD_ROM, /// CD (write once). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Cd")] - CdR = NativeMethods.STORAGE_MEDIA_TYPE.CD_R, + CdR = NativeMethods.MEDIA_TYPE.CD_R, /// CD (rewriteable). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Cd")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] - CdRw = NativeMethods.STORAGE_MEDIA_TYPE.CD_RW, + CdRw = NativeMethods.MEDIA_TYPE.CD_RW, /// DVD. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dvd")] - DvdRom = NativeMethods.STORAGE_MEDIA_TYPE.DVD_ROM, + DvdRom = NativeMethods.MEDIA_TYPE.DVD_ROM, /// DVD (write once). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dvd")] - DvdR = NativeMethods.STORAGE_MEDIA_TYPE.DVD_R, + DvdR = NativeMethods.MEDIA_TYPE.DVD_R, /// DVD (rewriteable). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dvd")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] - DvdRw = NativeMethods.STORAGE_MEDIA_TYPE.DVD_RW, + DvdRw = NativeMethods.MEDIA_TYPE.DVD_RW, /// Magneto-optical 3.5" (rewriteable). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mo")] - Mo3Rw = NativeMethods.STORAGE_MEDIA_TYPE.MO_3_RW, + Mo3Rw = NativeMethods.MEDIA_TYPE.MO_3_RW, /// Magneto-optical 5.25" (write once). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mo")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] - Mo5Wo = NativeMethods.STORAGE_MEDIA_TYPE.MO_5_WO, + Mo5Wo = NativeMethods.MEDIA_TYPE.MO_5_WO, /// Magneto-optical 5.25" (rewriteable; not LIMDOW). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mo")] - Mo5Rw = NativeMethods.STORAGE_MEDIA_TYPE.MO_5_RW, + Mo5Rw = NativeMethods.MEDIA_TYPE.MO_5_RW, /// Magneto-optical 5.25" (rewriteable; LIMDOW). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Limdow")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mo")] - Mo5Limdow = NativeMethods.STORAGE_MEDIA_TYPE.MO_5_LIMDOW, + Mo5Limdow = NativeMethods.MEDIA_TYPE.MO_5_LIMDOW, /// Phase change 5.25" (write once). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pc")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] - Pc5Wo = NativeMethods.STORAGE_MEDIA_TYPE.PC_5_WO, + Pc5Wo = NativeMethods.MEDIA_TYPE.PC_5_WO, /// Phase change 5.25" (rewriteable). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pc")] - Pc5Rw = NativeMethods.STORAGE_MEDIA_TYPE.PC_5_RW, + Pc5Rw = NativeMethods.MEDIA_TYPE.PC_5_RW, /// Phase change dual (rewriteable). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pd")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pd")] - Pd5Rw = NativeMethods.STORAGE_MEDIA_TYPE.PD_5_RW, + Pd5Rw = NativeMethods.MEDIA_TYPE.PD_5_RW, /// Ablative 5.25" (write once). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Abl")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] - Abl5Wo = NativeMethods.STORAGE_MEDIA_TYPE.ABL_5_WO, + Abl5Wo = NativeMethods.MEDIA_TYPE.ABL_5_WO, /// Pinnacle Apex 4.6GB (rewriteable) [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] - PinnacleApex5Rw = NativeMethods.STORAGE_MEDIA_TYPE.PINNACLE_APEX_5_RW, + PinnacleApex5Rw = NativeMethods.MEDIA_TYPE.PINNACLE_APEX_5_RW, /// Sony 12" (write once). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] - Sony12Wo = NativeMethods.STORAGE_MEDIA_TYPE.SONY_12_WO, + Sony12Wo = NativeMethods.MEDIA_TYPE.SONY_12_WO, /// Philips/LMS 12" (write once). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] - Philips12Wo = NativeMethods.STORAGE_MEDIA_TYPE.PHILIPS_12_WO, + Philips12Wo = NativeMethods.MEDIA_TYPE.PHILIPS_12_WO, /// Hitachi 12" (write once). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] - Hitachi12Wo = NativeMethods.STORAGE_MEDIA_TYPE.HITACHI_12_WO, + Hitachi12Wo = NativeMethods.MEDIA_TYPE.HITACHI_12_WO, /// Cygnet/ATG 12" (write once). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] - Cygnet12Wo = NativeMethods.STORAGE_MEDIA_TYPE.CYGNET_12_WO, + Cygnet12Wo = NativeMethods.MEDIA_TYPE.CYGNET_12_WO, /// Kodak 14" (write once). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wo")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Wo")] - Kodak14Wo = NativeMethods.STORAGE_MEDIA_TYPE.KODAK_14_WO, + Kodak14Wo = NativeMethods.MEDIA_TYPE.KODAK_14_WO, /// MO near field recording (Terastor). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mo")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nfr")] - MoNfr525 = NativeMethods.STORAGE_MEDIA_TYPE.MO_NFR_525, + MoNfr525 = NativeMethods.MEDIA_TYPE.MO_NFR_525, /// Nikon 12" (rewriteable). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Rw")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rw")] - Nikon12Rw = NativeMethods.STORAGE_MEDIA_TYPE.NIKON_12_RW, + Nikon12Rw = NativeMethods.MEDIA_TYPE.NIKON_12_RW, /// Iomega Zip. - IomegaZip = NativeMethods.STORAGE_MEDIA_TYPE.IOMEGA_ZIP, + IomegaZip = NativeMethods.MEDIA_TYPE.IOMEGA_ZIP, /// Iomega Jaz. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Jaz")] - IomegaJaz = NativeMethods.STORAGE_MEDIA_TYPE.IOMEGA_JAZ, + IomegaJaz = NativeMethods.MEDIA_TYPE.IOMEGA_JAZ, /// Syquest EZ135. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ez")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ez")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Syquest")] - SyquestEz135 = NativeMethods.STORAGE_MEDIA_TYPE.SYQUEST_EZ135, + SyquestEz135 = NativeMethods.MEDIA_TYPE.SYQUEST_EZ135, /// Syquest EzFlyer. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ezflyer")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Syquest")] - SyquestEzflyer = NativeMethods.STORAGE_MEDIA_TYPE.SYQUEST_EZFLYER, + SyquestEzflyer = NativeMethods.MEDIA_TYPE.SYQUEST_EZFLYER, /// Syquest SyJet. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Syjet")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Syquest")] - SyquestSyjet = NativeMethods.STORAGE_MEDIA_TYPE.SYQUEST_SYJET, + SyquestSyjet = NativeMethods.MEDIA_TYPE.SYQUEST_SYJET, /// Avatar 2.5" floppy. - AvatarF2 = NativeMethods.STORAGE_MEDIA_TYPE.AVATAR_F2, + AvatarF2 = NativeMethods.MEDIA_TYPE.AVATAR_F2, /// An 8mm Hitachi tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mp")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mp")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] - Mp28Mm = NativeMethods.STORAGE_MEDIA_TYPE.MP2_8mm, + Mp28Mm = NativeMethods.MEDIA_TYPE.MP2_8mm, /// Ampex DST small tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dst")] - DstS = NativeMethods.STORAGE_MEDIA_TYPE.DST_S, + DstS = NativeMethods.MEDIA_TYPE.DST_S, /// Ampex DST medium tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dst")] - DstM = NativeMethods.STORAGE_MEDIA_TYPE.DST_M, + DstM = NativeMethods.MEDIA_TYPE.DST_M, /// Ampex DST large tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dst")] - DstL = NativeMethods.STORAGE_MEDIA_TYPE.DST_L, + DstL = NativeMethods.MEDIA_TYPE.DST_L, /// Ecrix 8mm tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vxa")] - VxaTape1 = NativeMethods.STORAGE_MEDIA_TYPE.VXATape_1, + VxaTape1 = NativeMethods.MEDIA_TYPE.VXATape_1, /// Ecrix 8mm tape. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vxa")] - VxaTape2 = NativeMethods.STORAGE_MEDIA_TYPE.VXATape_2, + VxaTape2 = NativeMethods.MEDIA_TYPE.VXATape_2, /// STK 9840. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Stk")] - Stk9840 = NativeMethods.STORAGE_MEDIA_TYPE.STK_9840, + Stk9840 = NativeMethods.MEDIA_TYPE.STK_9840, /// LTO Ultrium (IBM, HP, Seagate). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lto")] - LtoUltrium = NativeMethods.STORAGE_MEDIA_TYPE.LTO_Ultrium, + LtoUltrium = NativeMethods.MEDIA_TYPE.LTO_Ultrium, /// LTO Accelis (IBM, HP, Seagate). [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Accelis")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lto")] - LtoAccelis = NativeMethods.STORAGE_MEDIA_TYPE.LTO_Accelis, + LtoAccelis = NativeMethods.MEDIA_TYPE.LTO_Accelis, /// DVD-RAM. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dvd")] - DvdRam = NativeMethods.STORAGE_MEDIA_TYPE.DVD_RAM, + DvdRam = NativeMethods.MEDIA_TYPE.DVD_RAM, /// AIT tape (AIT2 or higher). [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mm")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ait")] - Ait8Mm = NativeMethods.STORAGE_MEDIA_TYPE.AIT_8mm, + Ait8Mm = NativeMethods.MEDIA_TYPE.AIT_8mm, /// OnStream ADR1. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Adr")] - Adr1 = NativeMethods.STORAGE_MEDIA_TYPE.ADR_1, + Adr1 = NativeMethods.MEDIA_TYPE.ADR_1, /// OnStream ADR2. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Adr")] - Adr2 = NativeMethods.STORAGE_MEDIA_TYPE.ADR_2, + Adr2 = NativeMethods.MEDIA_TYPE.ADR_2, /// STK 9940. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Stk")] - Stk9940 = NativeMethods.STORAGE_MEDIA_TYPE.STK_9940, + Stk9940 = NativeMethods.MEDIA_TYPE.STK_9940, /// SAIT tape. /// Windows Server 2003: This is not supported before Windows Server 2003 with SP1. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sait")] - Sait = NativeMethods.STORAGE_MEDIA_TYPE.SAIT, + Sait = NativeMethods.MEDIA_TYPE.SAIT, /// Exabyte VXA tape. /// Windows Server 2008: This is not supported before Windows Server 2008. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vxa")] - VxaTape = NativeMethods.STORAGE_MEDIA_TYPE.VXATape + VxaTape = NativeMethods.MEDIA_TYPE.VXATape } } From 7bff3afbcb0373245824272d2c500925f239c000 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 20 Jun 2018 11:19:12 +0200 Subject: [PATCH 124/133] Code improvement. --- AlphaFS/AlphaFS.csproj | 3 +- .../Local/Local.GetStorageDeviceInfo.cs | 8 +- .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 81 +++++++++++++++- .../PhysicalDiskInfo_Properties.cs | 94 ------------------- .../Path Class/Path.GetRegularPath.cs | 2 +- AlphaFS/NativeError.cs | 9 ++ 6 files changed, 95 insertions(+), 102 deletions(-) delete mode 100644 AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 682111fa2..87ec7289a 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -202,7 +202,6 @@ - @@ -744,7 +743,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs index a14c20097..9de6c1dad 100644 --- a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs @@ -46,11 +46,11 @@ internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isD // Accessing a volume like: "\\.\D" on a dynamic disk fails with ERROR_INVALID_FUNCTION. // On retry, the drive is accessed using the: "\\.\PhysicalDriveX" path format which is the device, not the volume/logical drive. - using (var safeHandle = OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + using (var safeFileHandle = OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) { int lastError; - using (var safeBuffer = GetDeviceIoData(safeHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, localDevicePath, out lastError)) + using (var safeBuffer = GetDeviceIoData(safeFileHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, localDevicePath, out lastError)) { if (null != safeBuffer) { @@ -59,7 +59,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isD if (getByDeviceNumber && deviceNumber != storageDeviceInfo.DeviceNumber) return null; - SetStorageDeviceInfoData(isElevated, safeHandle, localDevicePath, storageDeviceInfo); + SetStorageDeviceInfoData(isElevated, safeFileHandle, localDevicePath, storageDeviceInfo); if (!localDevicePath.StartsWith(Path.PhysicalDrivePrefix, StringComparison.OrdinalIgnoreCase)) @@ -73,7 +73,7 @@ internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isD if (!retry && !isDevice && lastError == Win32Errors.ERROR_INVALID_FUNCTION) { - var volDiskExtents = GetVolumeDiskExtents(safeHandle, localDevicePath); + var volDiskExtents = GetVolumeDiskExtents(safeFileHandle, localDevicePath); if (volDiskExtents.HasValue) foreach (var extent in volDiskExtents.Value.Extents) diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index f6e5aeebb..7c1636303 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -20,6 +20,7 @@ */ using System; +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Security; @@ -87,6 +88,77 @@ internal PhysicalDiskInfo(int deviceNumber, StorageDeviceInfo storageDeviceInfo, #endregion // Constructors + #region Properties + + /// An initialized instance. + private DeviceInfo DeviceInfo { get; set; } + + + /// The . + public string DeviceDescription + { + get { return null != DeviceInfo ? DeviceInfo.DeviceDescription : null; } + } + + + /// The path to the device. + /// Returns a string that represents the path to the device. + /// A drive path such as: C:, D:\, + /// a volume path such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// or a string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string. + /// + public string DevicePath + { + get { return null != DeviceInfo ? DeviceInfo.DevicePath : null; } + } + + + /// The Win32 Device name. + public string DosDeviceName { get; private set; } + + + /// An of logical drives that are located on the physical disk or null when no entries found. + public IEnumerable LogicalDrives { get; private set; } + + + /// The . + public string Name + { + get { return null != DeviceInfo ? DeviceInfo.FriendlyName : null; } + } + + + /// An of partition index numbers that are located on the physical disk or null when no entries found. + public IEnumerable PartitionIndexes { get; private set; } + + + /// The (PDO) information provided by a device's firmware to Windows. + public string PhysicalDeviceObjectName + { + get { return null != DeviceInfo ? DeviceInfo.PhysicalDeviceObjectName : null; } + } + + + /// The storage device adapter information. Retrieving this information requires an elevated state. + public StorageAdapterInfo StorageAdapterInfo { get; private set; } + + + /// The storage device information. + public StorageDeviceInfo StorageDeviceInfo { get; private set; } + + + /// The storage device partition information. + public StoragePartitionInfo StoragePartitionInfo { get; private set; } + + + /// An of volume strings of volumes that are located on the physical disk or null when no entries found. + public IEnumerable VolumeGuids { get; private set; } + + #endregion // Properties + + + #region Methods + [SecurityCritical] private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) { @@ -141,13 +213,18 @@ private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, PopulatePhysicalDisk(isElevated); + // Update device/partition TotalSize property when applicable. + // // The Win32 API to retrieve the total size of the device requires an elevated process or the TotalSize is 0. // The Win32 API to retrieve the total size of the device partition does not require elevation, so use that value. if (StoragePartitionInfo.OnDynamicDisk && null != dosDeviceName) - + { StorageDeviceInfo.TotalSize = new DiskSpaceInfo(dosDeviceName, false, true, true).TotalNumberOfBytes; + // 2018-0620 TODO: The StorageDeviceInfo.PartitionNumber is 0, which is wrong; it should be the partition number. + } + else if (!isElevated && StorageDeviceInfo.TotalSize == 0 && null != StoragePartitionInfo) StorageDeviceInfo.TotalSize = isDevice ? StoragePartitionInfo.TotalSize : new DiskSpaceInfo(dosDeviceName ?? localDevicePath, false, true, true).TotalNumberOfBytes; @@ -283,5 +360,7 @@ public override int GetHashCode() { return !(left == right); } + + #endregion // Methods } } diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs deleted file mode 100644 index a9c784bb6..000000000 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo_Properties.cs +++ /dev/null @@ -1,94 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 Alphaleonis.Win32.Filesystem; - -namespace Alphaleonis.Win32.Device -{ - public sealed partial class PhysicalDiskInfo - { - /// An initialized instance. - private DeviceInfo DeviceInfo { get; set; } - - - /// The . - public string DeviceDescription - { - get { return null != DeviceInfo ? DeviceInfo.DeviceDescription : null; } - } - - - /// The path to the device. - /// Returns a string that represents the path to the device. - /// A drive path such as: C:, D:\, - /// a volume path such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// or a string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string. - /// - public string DevicePath - { - get { return null != DeviceInfo ? DeviceInfo.DevicePath : null; } - } - - - /// The Win32 Device name. - public string DosDeviceName { get; private set; } - - - /// An of logical drives that are located on the physical disk or null when no entries found. - public IEnumerable LogicalDrives { get; private set; } - - - /// The . - public string Name - { - get { return null != DeviceInfo ? DeviceInfo.FriendlyName : null; } - } - - - /// An of partition index numbers that are located on the physical disk or null when no entries found. - public IEnumerable PartitionIndexes { get; private set; } - - - /// The (PDO) information provided by a device's firmware to Windows. - public string PhysicalDeviceObjectName - { - get { return null != DeviceInfo ? DeviceInfo.PhysicalDeviceObjectName : null; } - } - - - /// The storage device adapter information. Retrieving this information requires an elevated state. - public StorageAdapterInfo StorageAdapterInfo { get; private set; } - - - /// The storage device information. - public StorageDeviceInfo StorageDeviceInfo { get; private set; } - - - /// The storage device partition information. - public StoragePartitionInfo StoragePartitionInfo { get; private set; } - - - /// An of volume strings of volumes that are located on the physical disk or null when no entries found. - public IEnumerable VolumeGuids { get; private set; } - } -} diff --git a/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs b/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs index 0e204b4f2..75bc0123f 100644 --- a/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs +++ b/AlphaFS/Filesystem/Path Class/Path.GetRegularPath.cs @@ -79,7 +79,7 @@ internal static string GetRegularPathCore(string path, GetFullPathOptions option return path.StartsWith(GlobalRootPrefix, StringComparison.OrdinalIgnoreCase) || path.StartsWith(VolumePrefix, StringComparison.OrdinalIgnoreCase) || - path.StartsWith(PhysicalDrivePrefix, StringComparison.OrdinalIgnoreCase) || !path.StartsWith(LongPathPrefix, StringComparison.Ordinal) + !path.StartsWith(LongPathPrefix, StringComparison.Ordinal) ? path : (path.StartsWith(LongPathUncPrefix, StringComparison.OrdinalIgnoreCase) ? UncPrefix + path.Substring(LongPathUncPrefix.Length) : path.Substring(LongPathPrefix.Length)); diff --git a/AlphaFS/NativeError.cs b/AlphaFS/NativeError.cs index e6f04b5c6..fdbc72bf7 100644 --- a/AlphaFS/NativeError.cs +++ b/AlphaFS/NativeError.cs @@ -72,6 +72,15 @@ public static void ThrowException(uint errorCode, string readPath, string writeP if (null != writePath) writePath = Path.GetCleanExceptionPath(writePath); + + if (errorCode == Win32Errors.ERROR_PATH_NOT_FOUND || errorCode == Win32Errors.ERROR_FILE_NOT_FOUND) + { + if (null != readPath && readPath.StartsWith(Path.PhysicalDrivePrefix, StringComparison.OrdinalIgnoreCase)) + + errorCode = Win32Errors.ERROR_NOT_READY; + } + + var errorMessage = string.Format(CultureInfo.InvariantCulture, "({0}) {1}.", errorCode, new Win32Exception((int) errorCode).Message.Trim().TrimEnd('.').Trim()); From 49a54b8aac5317b7140b37c6959e044e508c43cd Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 20 Jun 2018 19:19:53 +0200 Subject: [PATCH 125/133] Code improvement, work in progress. --- ...Disks_ReturnsStorageDeviceInfoForDevice.cs | 25 ++-- ...ePath_ReturnsStorageDeviceInfoForVolume.cs | 29 +++-- ...umber_ReturnsStorageDeviceInfoForDevice.cs | 35 +++++- AlphaFS.UnitTest/UnitTest Utility/Dump.cs | 3 +- .../Local/Local.GetStorageDeviceInfo.cs | 102 +++++++++++----- .../Local/Local.GetVolumeDiskExtents.cs | 12 +- AlphaFS/Device/Local/Local.OpenDevice.cs | 2 +- .../Local/Local.SetStorageDeviceInfoData.cs | 6 +- .../Local.EnumeratePhysicalDisks.cs | 9 +- .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 114 ++++++++++-------- .../Storage/Device.StorageDeviceInfo.cs | 9 +- .../Storage/Device.StoragePartitionInfo.cs | 28 ++--- AlphaFS/Utils.cs | 6 +- 13 files changed, 234 insertions(+), 146 deletions(-) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs index b0398ea4c..ed1b6c250 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_Device.EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDevice.cs @@ -76,19 +76,30 @@ public void AlphaFS_Device_EnumeratePhysicalDisks_ReturnsStorageDeviceInfoForDev Assert.AreEqual(pDiskInfo.DosDeviceName, pDiskInfo.PhysicalDeviceObjectName); - // PartitionNumber should be -1 for CDRom. + // PartitionNumber should be 0 for logical drive on dynamic disk. - if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.DeviceType.CDRom) - Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + if (pDiskInfo.StoragePartitionInfo.OnDynamicDisk) + Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); - // PartitionNumber should be 0 for device. else - Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + { + // PartitionNumber should be -1 for CDRom. + if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.DeviceType.CDRom) + Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); - // TotalSize should always match for device. + // PartitionNumber should be > 0 for logical drive because it is not the device. + else + Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + } - Assert.AreEqual(pDiskInfo.StorageDeviceInfo.TotalSize, pDiskInfo.StoragePartitionInfo.TotalSize); + + // TotalSize depends on dynamic disk on device. + + if (pDiskInfo.StoragePartitionInfo.OnDynamicDisk) + Assert.AreNotEqual(pDiskInfo.StorageDeviceInfo.TotalSize, pDiskInfo.StoragePartitionInfo.TotalSize); + else + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.TotalSize, pDiskInfo.StoragePartitionInfo.TotalSize); // Show all partition information. diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs index 278e5951d..55763c6b0 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingLogicalDrivePath_ReturnsStorageDeviceInfoForVolume.cs @@ -84,27 +84,30 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingLogicalDrivePath_Return Assert.AreNotEqual(pDiskInfo.DosDeviceName, pDiskInfo.PhysicalDeviceObjectName); - // (It seems that, not 100% sure) PartitionNumber should be 0 for logical drive on dynamic disk. + // PartitionNumber should be -1 for CDRom. - if (pDiskInfo.StoragePartitionInfo.OnDynamicDisk) - Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.DeviceType.CDRom) + Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + // PartitionNumber should be > 0 for logical drive because it is not the device. else - { - // PartitionNumber should be -1 for CDRom. + Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + - if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.DeviceType.CDRom) - Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.DeviceNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); - // PartitionNumber should be > 0 for logical drive because it is not the device. - else - Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); - } + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.DeviceNumber, pDiskInfo.StoragePartitionInfo.DeviceNumber); - Assert.AreEqual(pDiskInfo.StorageDeviceInfo.DeviceNumber, pDiskInfo.StorageAdapterInfo.DeviceNumber); + // Show all partition information. - Assert.AreEqual(pDiskInfo.StorageDeviceInfo.DeviceNumber, pDiskInfo.StoragePartitionInfo.DeviceNumber); + if (null != pDiskInfo.StoragePartitionInfo && null != pDiskInfo.StoragePartitionInfo.GptPartitionInfo) + foreach (var partition in pDiskInfo.StoragePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, true); + + if (null != pDiskInfo.StoragePartitionInfo && null != pDiskInfo.StoragePartitionInfo.MbrPartitionInfo) + foreach (var partition in pDiskInfo.StoragePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, true); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs index 2f441473e..cb6346321 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS PhysicalDisk Class/AlphaFS_PhysicalDiskInfo.CreateInstance_UsingPhysicalDriveNumber_ReturnsStorageDeviceInfoForDevice.cs @@ -68,14 +68,30 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingPhysicalDriveNumber_Ret Assert.IsTrue(pDiskInfo.DosDeviceName.Contains(string.Format(CultureInfo.InvariantCulture, @"{0}\DR", physicalDiskNumber))); - // PartitionNumber should be 0 for device. + // PartitionNumber should be 0 for device on dynamic disk. - Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + if (pDiskInfo.StoragePartitionInfo.OnDynamicDisk) + Assert.AreNotEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + else + { + // PartitionNumber should be -1 for CDRom. - // TotalSize should always match for device. + if (pDiskInfo.StorageDeviceInfo.DeviceType == Alphaleonis.Win32.Device.DeviceType.CDRom) + Assert.AreEqual(-1, pDiskInfo.StorageDeviceInfo.PartitionNumber); - Assert.AreEqual(pDiskInfo.StorageDeviceInfo.TotalSize, pDiskInfo.StoragePartitionInfo.TotalSize); + // PartitionNumber should be 0 for device. + else + Assert.AreEqual(0, pDiskInfo.StorageDeviceInfo.PartitionNumber); + } + + + // TotalSize depends on dynamic disk on device. + + if (pDiskInfo.StoragePartitionInfo.OnDynamicDisk) + Assert.AreNotEqual(pDiskInfo.StorageDeviceInfo.TotalSize, pDiskInfo.StoragePartitionInfo.TotalSize); + else + Assert.AreEqual(pDiskInfo.StorageDeviceInfo.TotalSize, pDiskInfo.StoragePartitionInfo.TotalSize); @@ -86,6 +102,17 @@ public void AlphaFS_PhysicalDiskInfo_CreateInstance_UsingPhysicalDriveNumber_Ret Assert.AreEqual(physicalDiskNumber, pDiskInfo.StoragePartitionInfo.DeviceNumber); + // Show all partition information. + + if (null != pDiskInfo.StoragePartitionInfo && null != pDiskInfo.StoragePartitionInfo.GptPartitionInfo) + foreach (var partition in pDiskInfo.StoragePartitionInfo.GptPartitionInfo) + UnitTestConstants.Dump(partition, true); + + if (null != pDiskInfo.StoragePartitionInfo && null != pDiskInfo.StoragePartitionInfo.MbrPartitionInfo) + foreach (var partition in pDiskInfo.StoragePartitionInfo.MbrPartitionInfo) + UnitTestConstants.Dump(partition, true); + + Console.WriteLine(); } } diff --git a/AlphaFS.UnitTest/UnitTest Utility/Dump.cs b/AlphaFS.UnitTest/UnitTest Utility/Dump.cs index c420d5574..f3bdffed3 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/Dump.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/Dump.cs @@ -22,6 +22,7 @@ using System; using System.Collections; using System.ComponentModel; +using System.Globalization; using System.Linq; using System.Text; @@ -74,7 +75,7 @@ private static string Write(object value) long number; if (long.TryParse(value.ToString(), out number)) - return value.ToString(); + return number.ToString("N0", CultureInfo.CurrentCulture); var objectType = value as IEnumerable; diff --git a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs index 9de6c1dad..4d8708508 100644 --- a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs @@ -20,81 +20,117 @@ */ using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Globalization; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { public static partial class Local { // /// When this method is called from a non-elevated state, the property always returns 0. - + /// Returns a instance that represent the storage device that is related to . /// [SecurityCritical] internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isDevice, int deviceNumber, string devicePath, out string localDevicePath) { - localDevicePath = devicePath; + localDevicePath = FileSystemHelper.GetLocalDevicePath(devicePath); var getByDeviceNumber = deviceNumber > -1; var retry = false; Retry: + int lastError; + // Accessing a volume like: "\\.\D" on a dynamic disk fails with ERROR_INVALID_FUNCTION. // On retry, the drive is accessed using the: "\\.\PhysicalDriveX" path format which is the device, not the volume/logical drive. using (var safeFileHandle = OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - { - int lastError; - using (var safeBuffer = GetDeviceIoData(safeFileHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, localDevicePath, out lastError)) - { - if (null != safeBuffer) - { - var storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure()); + using (var safeBuffer = GetDeviceIoData(safeFileHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, localDevicePath, out lastError)) - if (getByDeviceNumber && deviceNumber != storageDeviceInfo.DeviceNumber) - return null; + if (null != safeBuffer) + { + var storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure()); - SetStorageDeviceInfoData(isElevated, safeFileHandle, localDevicePath, storageDeviceInfo); + if (getByDeviceNumber && deviceNumber != storageDeviceInfo.DeviceNumber) + return null; + SetStorageDeviceInfoData(isElevated, safeFileHandle, localDevicePath, storageDeviceInfo); - if (!localDevicePath.StartsWith(Path.PhysicalDrivePrefix, StringComparison.OrdinalIgnoreCase)) - localDevicePath = null; - return storageDeviceInfo; - } + if (!localDevicePath.StartsWith(Path.PhysicalDrivePrefix, StringComparison.OrdinalIgnoreCase)) + localDevicePath = null; + return storageDeviceInfo; + } - // A logical drive path like \\.\D: fails on a dynamic disk. - if (!retry && !isDevice && lastError == Win32Errors.ERROR_INVALID_FUNCTION) - { - var volDiskExtents = GetVolumeDiskExtents(safeFileHandle, localDevicePath); + // A logical drive path on a dynamic disk like \\.\D: fails. - if (volDiskExtents.HasValue) - foreach (var extent in volDiskExtents.Value.Extents) - { - var newDeviceNumber = (int) extent.DiskNumber; + if (!retry && !isDevice && lastError == Win32Errors.ERROR_INVALID_FUNCTION) + { + foreach (var physicalDeviceNumber in GetDeviceNumbersForVolume(null, localDevicePath)) + { + if (getByDeviceNumber && deviceNumber != physicalDeviceNumber) + continue; - if (getByDeviceNumber && deviceNumber != newDeviceNumber) - continue; + // By opening the device as PhysicalDriveX, StorageDeviceInfo.PartitionNumber = 0. - localDevicePath = Path.PhysicalDrivePrefix + newDeviceNumber.ToString(CultureInfo.InvariantCulture); + localDevicePath = Path.PhysicalDrivePrefix + physicalDeviceNumber.ToString(CultureInfo.InvariantCulture); - isDevice = true; - retry = true; + isDevice = true; + retry = true; - goto Retry; - } - } + goto Retry; } + } + + + return null; + } - return null; + + /// Returns an of physical drive device numbers used by the specified volume. + /// + /// An initialized instance. + /// + /// A drive path such as: \\.\C: + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// + [SecurityCritical] + internal static IEnumerable GetDeviceNumbersForVolume(SafeFileHandle safeFileHandle, string localDevicePath) + { + var physicalDrives = new Collection(); + + var disposeHandle = null == safeFileHandle; + + try + { + if (null == safeFileHandle) + safeFileHandle = OpenDevice(localDevicePath, NativeMethods.FILE_ANY_ACCESS); + + var volDiskExtents = GetVolumeDiskExtents(safeFileHandle, localDevicePath); + + if (volDiskExtents.HasValue) + + foreach (var extent in volDiskExtents.Value.Extents) + + physicalDrives.Add((int) extent.DiskNumber); } + finally + { + if (disposeHandle && null != safeFileHandle && !safeFileHandle.IsClosed) + safeFileHandle.Close(); + } + + return physicalDrives; } } } diff --git a/AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs b/AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs index 547c92c07..f95f5dcaf 100644 --- a/AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs +++ b/AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs @@ -33,10 +33,13 @@ public static partial class Local private static NativeMethods.VOLUME_DISK_EXTENTS? GetVolumeDiskExtents(SafeFileHandle safeFileHandle, string pathForException) { var structSize = Marshal.SizeOf(typeof(NativeMethods.DISK_EXTENT_SINGLE)); + var bufferSize = structSize; - while(true) + // 2018-06-20 Note: Although the code should handle multiple disk extents, it has only been tested with one disk extent. + + while (true) using (var safeBuffer = new SafeGlobalMemoryBufferHandle(bufferSize)) { var success = NativeMethods.DeviceIoControl(safeFileHandle, NativeMethods.IoControlCode.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, safeBuffer, (uint) safeBuffer.Capacity, IntPtr.Zero, IntPtr.Zero); @@ -66,12 +69,7 @@ public static partial class Local } - // 2016-06-18 TODO: When lastError = ERROR_MORE_DATA, the drive is part of a mirror or volume, or the volume is on multiple disks. - - // Encountered a drive such as a CDRom/mounted .iso file. - if (lastError == Win32Errors.ERROR_INVALID_FUNCTION) - return null; - + // When ERROR_MORE_DATA, the drive is part of a mirror or volume, or the volume is on multiple disks. bufferSize = Utils.GetDoubledBufferSizeOrThrowException(safeBuffer, lastError, bufferSize, pathForException); } diff --git a/AlphaFS/Device/Local/Local.OpenDevice.cs b/AlphaFS/Device/Local/Local.OpenDevice.cs index 0d40c9ce0..584bf6bf2 100644 --- a/AlphaFS/Device/Local/Local.OpenDevice.cs +++ b/AlphaFS/Device/Local/Local.OpenDevice.cs @@ -49,8 +49,8 @@ public static SafeFileHandle OpenDevice(string devicePath, FileSystemRights file { // fileSystemRights: If this parameter is 0 (FILE_ANY_ACCESS), the application can query certain metadata such as file, directory, or device attributes // without accessing that file or device, even if GENERIC_READ access would have been denied. - // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. // + // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. // // When opening a volume or removable media drive (for example, a floppy disk drive or flash memory thumb drive), the lpFileName string should be the following form: "\\.\X:". // Do not use a trailing backslash (\), which indicates the root directory of a drive. diff --git a/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs b/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs index 723a17908..19587134f 100644 --- a/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs +++ b/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Device public static partial class Local { [SecurityCritical] - private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle safeFileHandle, string localDevicePath, StorageDeviceInfo storageDeviceInfo) + private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle safeFileHandle, string pathForException, StorageDeviceInfo storageDeviceInfo) { var storagePropertyQuery = new NativeMethods.STORAGE_PROPERTY_QUERY { @@ -36,7 +36,7 @@ private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle saf }; - using (var safeBuffer = InvokeDeviceIoData(safeFileHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, localDevicePath, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) + using (var safeBuffer = InvokeDeviceIoData(safeFileHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_QUERY_PROPERTY, storagePropertyQuery, pathForException, Filesystem.NativeMethods.DefaultFileBufferSize / 2)) { var deviceDescriptor = safeBuffer.PtrToStructure(); @@ -73,7 +73,7 @@ private static void SetStorageDeviceInfoData(bool isElevated, SafeFileHandle saf { int lastError; - using (var safeBuffer = GetDeviceIoData(safeFileHandle,NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, localDevicePath, out lastError)) + using (var safeBuffer = GetDeviceIoData(safeFileHandle,NativeMethods.IoControlCode.IOCTL_DISK_GET_LENGTH_INFO, pathForException, out lastError)) storageDeviceInfo.TotalSize = null != safeBuffer ? safeBuffer.ReadInt64() : 0; } diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs index 445163113..c0f802609 100644 --- a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs +++ b/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs @@ -27,7 +27,7 @@ namespace Alphaleonis.Win32.Device { public static partial class Local { - /// [AlphaFS] Enumerates the physical disks (including CD-ROM/DVD devices) on the Computer, populated with volume/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CD/DVD-ROM devices) on the Computer, populated with volume/logical drive information. /// Returns an collection that represents the physical disks on the Computer. [SecurityCritical] public static IEnumerable EnumeratePhysicalDisks() @@ -36,7 +36,7 @@ public static IEnumerable EnumeratePhysicalDisks() } - /// [AlphaFS] Enumerates the physical disks (including CD-ROM/DVD devices) on the Computer, populated with volume/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CD/DVD-ROM devices) on the Computer, populated with volume/logical drive information. /// Returns an collection that represents the physical disks on the Computer. /// Retrieve instances by device number. [SecurityCritical] @@ -46,7 +46,7 @@ public static IEnumerable EnumeratePhysicalDisks(int deviceNum } - /// [AlphaFS] Enumerates the physical disks (including CD-ROM/DVD devices) on the Computer, populated with volume/logical drive information. + /// [AlphaFS] Enumerates the physical disks (including CD/DVD-ROM devices) on the Computer, populated with volume/logical drive information. /// Returns an collection that represents the physical disks on the Computer. /// true indicates the current process is in an elevated state, allowing to retrieve more data. /// Retrieve a instance by device number. @@ -57,9 +57,6 @@ internal static IEnumerable EnumeratePhysicalDisksCore(bool is { string unusedPhysicalDriveNumberPath; - - // The StorageDeviceInfo is always needed as it contains the device- and partition number. - var storageDeviceInfo = GetStorageDeviceInfo(isElevated, true, deviceNumber, deviceInfo.DevicePath, out unusedPhysicalDriveNumberPath); if (null != storageDeviceInfo) diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index 7c1636303..d9e15560c 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -169,13 +169,12 @@ private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, bool isVolume; bool isDevice; - if (!getByDeviceNumber && Utils.IsNullOrWhiteSpace(devicePath) && null != deviceInfo) + if (null != deviceInfo) devicePath = deviceInfo.DevicePath; var localDevicePath = FileSystemHelper.GetValidatedDevicePath(getByDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : devicePath, out isDrive, out isVolume, out isDevice); - if (isDrive) - localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); + localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); string physicalDriveNumberPath = null; @@ -191,66 +190,32 @@ private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, if (!SetDeviceInfoDataFromDeviceNumber(isElevated, deviceNumber, deviceInfo)) return; - var dosDeviceName = isDrive ? Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)) : null; - // If physicalDriveNumberPath != null, the drive is opened using: "\\.\PhysicalDriveX" path format // which is the device, not the volume/logical drive. localDevicePath = FileSystemHelper.GetValidatedDevicePath(physicalDriveNumberPath ?? localDevicePath, out isDrive, out isVolume, out isDevice); - DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); - - - using (var safeFileHandle = Local.OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - { - StorageAdapterInfo = Local.GetStorageAdapterInfo(safeFileHandle, deviceNumber, localDevicePath, DeviceInfo.BusReportedDeviceDescription); - - StoragePartitionInfo = Local.GetStoragePartitionInfo(safeFileHandle, deviceNumber, localDevicePath); - } + AddDeviceInfoData(isElevated, deviceNumber, localDevicePath); - PopulatePhysicalDisk(isElevated); - - - // Update device/partition TotalSize property when applicable. - // - // The Win32 API to retrieve the total size of the device requires an elevated process or the TotalSize is 0. - // The Win32 API to retrieve the total size of the device partition does not require elevation, so use that value. - - if (StoragePartitionInfo.OnDynamicDisk && null != dosDeviceName) - { - StorageDeviceInfo.TotalSize = new DiskSpaceInfo(dosDeviceName, false, true, true).TotalNumberOfBytes; - - // 2018-0620 TODO: The StorageDeviceInfo.PartitionNumber is 0, which is wrong; it should be the partition number. - } + UpdateDeviceInfodata(isElevated, isDevice, localDevicePath); - else if (!isElevated && StorageDeviceInfo.TotalSize == 0 && null != StoragePartitionInfo) - - StorageDeviceInfo.TotalSize = isDevice ? StoragePartitionInfo.TotalSize : new DiskSpaceInfo(dosDeviceName ?? localDevicePath, false, true, true).TotalNumberOfBytes; + PopulatePhysicalDisk(isElevated); } - - private bool SetDeviceInfoDataFromDeviceNumber(bool isElevated, int deviceNumber, DeviceInfo deviceInfo) - { - if (null == deviceInfo) - foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) - { - string unusedDevicePath; - var storageDeviceInfo = Local.GetStorageDeviceInfo(isElevated, true, deviceNumber, device.DevicePath, out unusedDevicePath); - - if (null != storageDeviceInfo) - { - deviceInfo = device; - break; - } - } + private void AddDeviceInfoData(bool isElevated, int deviceNumber, string localDevicePath) + { + DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); - DeviceInfo = deviceInfo; + using (var safeFileHandle = Local.OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + { + StorageAdapterInfo = Local.GetStorageAdapterInfo(safeFileHandle, deviceNumber, localDevicePath, DeviceInfo.BusReportedDeviceDescription); - return null != DeviceInfo; + StoragePartitionInfo = Local.GetStoragePartitionInfo(safeFileHandle, deviceNumber, localDevicePath); + } } @@ -298,10 +263,61 @@ private void PopulatePhysicalDisk(bool isElevated) LogicalDrives = _logicalDriveCollection; } - + [SecurityCritical] + private bool SetDeviceInfoDataFromDeviceNumber(bool isElevated, int deviceNumber, DeviceInfo deviceInfo) + { + if (null == deviceInfo) + foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) + { + string unusedDevicePath; + + var storageDeviceInfo = Local.GetStorageDeviceInfo(isElevated, true, deviceNumber, device.DevicePath, out unusedDevicePath); + + if (null != storageDeviceInfo) + { + deviceInfo = device; + break; + } + } + + + DeviceInfo = deviceInfo; + + return null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); + } + + [SecurityCritical] + private void UpdateDeviceInfodata(bool isElevated, bool isDevice, string localDevicePath) + { + if (StoragePartitionInfo.OnDynamicDisk) + { + // At this point, PartitionNumber is 0 which points to the device. + // Get the user data partition information. + + foreach (var partition in StoragePartitionInfo.GptPartitionInfo) + { + if (partition.PartitionType == PartitionType.LdmData) + { + StorageDeviceInfo.PartitionNumber = partition.PartitionNumber; + + StorageDeviceInfo.TotalSize = partition.PartitionLength; + + break; + } + } + } + + else if (!isElevated && StorageDeviceInfo.TotalSize == 0 && null != StoragePartitionInfo) + + StorageDeviceInfo.TotalSize = isDevice ? StoragePartitionInfo.TotalSize : new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; + } + + + + /// Returns the "FriendlyName" of the physical disk. /// Returns a string that represents this instance. public override string ToString() diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 1ec58de0e..87451f743 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -86,12 +86,11 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() /// /// The partition number of the storage device, starting at 1. - /// Partition number 0 is the device. - /// If the device cannot be partitioned, like a CDROM, -1 is returned. - /// -1 is also returned if the device is accessed by its path: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - /// instead of a volume /logical drive path. + /// If the device cannot be partitioned, like a CD/DVD-ROM, -1 is returned. + /// If this value is 0, the information points to the device, not partition. + /// If the partition is on a dynamic disk (), the partition's number is returned. /// - public int PartitionNumber { get; private set; } + public int PartitionNumber { get; internal set; } /// The product ID of the physical disk. diff --git a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs index f0bfa275c..29754b203 100644 --- a/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs +++ b/AlphaFS/Device/Storage/Device.StoragePartitionInfo.cs @@ -62,17 +62,15 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis MediaType = (StorageMediaType) disk.Geometry.MediaType; PartitionCount = (int) drive.PartitionCount; - - + MbrSignature = disk.PartitionInformation.MbrSignature; GptDiskId = disk.PartitionInformation.DiskId; - PartitionStyle = (PartitionStyle) disk.PartitionInformation.PartitionStyle; - TotalSize = disk.DiskSize; - + PartitionStyle = (PartitionStyle) disk.PartitionInformation.PartitionStyle; + switch (PartitionStyle) { case PartitionStyle.Gpt: @@ -123,17 +121,7 @@ internal StoragePartitionInfo(int diskNumber, NativeMethods.DISK_GEOMETRY_EX dis } break; - - - default: - Console.WriteLine(); - break; } - - - OnDynamicDisk = null != GptPartitionInfo && GptPartitionInfo.Any(partition => partition.PartitionType == PartitionType.LdmData || partition.PartitionType == PartitionType.LdmMetadata) || - - null != MbrPartitionInfo && MbrPartitionInfo.Any(partition => partition.DiskPartitionType == DiskPartitionType.Ldm); } #endregion // Constructors @@ -215,7 +203,15 @@ public string GptUsableLengthUnitSize /// true if the partition is on a dynamic disk. - public bool OnDynamicDisk { get; private set; } + public bool OnDynamicDisk + { + get + { + return null != GptPartitionInfo && GptPartitionInfo.Any(partition => partition.PartitionType == PartitionType.LdmData || partition.PartitionType == PartitionType.LdmMetadata) || + + null != MbrPartitionInfo && MbrPartitionInfo.Any(partition => partition.DiskPartitionType == DiskPartitionType.Ldm); + } + } /// Contains partition information specific to master boot record (MBR) disks. diff --git a/AlphaFS/Utils.cs b/AlphaFS/Utils.cs index fba573a81..c2b6c8c69 100644 --- a/AlphaFS/Utils.cs +++ b/AlphaFS/Utils.cs @@ -79,7 +79,6 @@ internal static int GetDoubledBufferSizeOrThrowException(SafeHandle safeBuffer, { case Win32Errors.ERROR_MORE_DATA: case Win32Errors.ERROR_INSUFFICIENT_BUFFER: - case Win32Errors.ERROR_INVALID_PARAMETER: if (bufferSize == 0) bufferSize = NativeMethods.DefaultFileBufferSize / 32; // 128 @@ -88,6 +87,11 @@ internal static int GetDoubledBufferSizeOrThrowException(SafeHandle safeBuffer, break; + //case Win32Errors.ERROR_INVALID_PARAMETER: + //case Win32Errors.ERROR_INVALID_FUNCTION: + //break + + default: IsValidHandle(safeBuffer, lastError, string.Format(CultureInfo.InvariantCulture, "Buffer size: {0}. Path: {1}", bufferSize.ToString(CultureInfo.InvariantCulture), pathForException)); break; From 3ac52a0e767c950fe4c05438b07aff0a828985a4 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 20 Jun 2018 20:40:47 +0200 Subject: [PATCH 126/133] Code improvement, cleanup. --- AlphaFS/AlphaFS.csproj | 4 +- .../Local.EnumeratePhysicalDisks.cs | 0 .../Local/Local.GetDeviceNumbersForVolume.cs | 68 + .../Local/Local.GetStorageDeviceInfo.cs | 40 - AlphaFS/Device/Test.cs | 1362 ----------------- 5 files changed, 70 insertions(+), 1404 deletions(-) rename AlphaFS/Device/{PhysicalDisk => Local}/Local.EnumeratePhysicalDisks.cs (100%) create mode 100644 AlphaFS/Device/Local/Local.GetDeviceNumbersForVolume.cs delete mode 100644 AlphaFS/Device/Test.cs diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 87ec7289a..4a1cc59f4 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -197,6 +197,7 @@ True + @@ -207,7 +208,6 @@ - @@ -215,7 +215,7 @@ - + diff --git a/AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/Local/Local.EnumeratePhysicalDisks.cs similarity index 100% rename from AlphaFS/Device/PhysicalDisk/Local.EnumeratePhysicalDisks.cs rename to AlphaFS/Device/Local/Local.EnumeratePhysicalDisks.cs diff --git a/AlphaFS/Device/Local/Local.GetDeviceNumbersForVolume.cs b/AlphaFS/Device/Local/Local.GetDeviceNumbersForVolume.cs new file mode 100644 index 000000000..03b67c615 --- /dev/null +++ b/AlphaFS/Device/Local/Local.GetDeviceNumbersForVolume.cs @@ -0,0 +1,68 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Collections.ObjectModel; +using System.Security; +using Microsoft.Win32.SafeHandles; + +namespace Alphaleonis.Win32.Device +{ + public static partial class Local + { + /// Returns an of physical drive device numbers used by the specified volume. + /// + /// An initialized instance. + /// + /// A drive path such as: \\.\C: + /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// + [SecurityCritical] + private static IEnumerable GetDeviceNumbersForVolume(SafeFileHandle safeFileHandle, string localDevicePath) + { + var physicalDrives = new Collection(); + + var disposeHandle = null == safeFileHandle; + + try + { + if (null == safeFileHandle) + safeFileHandle = OpenDevice(localDevicePath, NativeMethods.FILE_ANY_ACCESS); + + var volDiskExtents = GetVolumeDiskExtents(safeFileHandle, localDevicePath); + + if (volDiskExtents.HasValue) + + foreach (var extent in volDiskExtents.Value.Extents) + + physicalDrives.Add((int) extent.DiskNumber); + } + finally + { + if (disposeHandle && null != safeFileHandle && !safeFileHandle.IsClosed) + safeFileHandle.Close(); + } + + return physicalDrives; + } + } +} diff --git a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs index 4d8708508..da2f40863 100644 --- a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs @@ -20,13 +20,10 @@ */ using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Globalization; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; -using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { @@ -95,42 +92,5 @@ internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isD return null; } - - - /// Returns an of physical drive device numbers used by the specified volume. - /// - /// An initialized instance. - /// - /// A drive path such as: \\.\C: - /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// - [SecurityCritical] - internal static IEnumerable GetDeviceNumbersForVolume(SafeFileHandle safeFileHandle, string localDevicePath) - { - var physicalDrives = new Collection(); - - var disposeHandle = null == safeFileHandle; - - try - { - if (null == safeFileHandle) - safeFileHandle = OpenDevice(localDevicePath, NativeMethods.FILE_ANY_ACCESS); - - var volDiskExtents = GetVolumeDiskExtents(safeFileHandle, localDevicePath); - - if (volDiskExtents.HasValue) - - foreach (var extent in volDiskExtents.Value.Extents) - - physicalDrives.Add((int) extent.DiskNumber); - } - finally - { - if (disposeHandle && null != safeFileHandle && !safeFileHandle.IsClosed) - safeFileHandle.Close(); - } - - return physicalDrives; - } } } diff --git a/AlphaFS/Device/Test.cs b/AlphaFS/Device/Test.cs deleted file mode 100644 index 6ac7d049b..000000000 --- a/AlphaFS/Device/Test.cs +++ /dev/null @@ -1,1362 +0,0 @@ -//* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov -// * -// * Permission is hereby granted, free of charge, to any person obtaining a copy -// * of this software and associated documentation files (the "Software"), to deal -// * in the Software without restriction, including without limitation the rights -// * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// * copies of the Software, and to permit persons to whom the Software is -// * furnished to do so, subject to the following conditions: -// * -// * The above copyright notice and this permission notice shall be included in -// * all copies or substantial portions of the Software. -// * -// * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// * LIABILITY, WHETHER IN AN ACTION 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.IO; -//using System.Runtime.InteropServices; -//using System.Security.Cryptography; -//using System.Text; -//using Microsoft.Win32; -//using Microsoft.Win32.SafeHandles; - -//namespace Alphaleonis.Win32.Filesystem -//{ -// #region Helper: Enum - -// internal static class EnumHelper -// { -// internal static bool HasFlag(this Enum flags, T value) where T : struct -// { -// var iFlags = Convert.ToUInt64(flags); -// var iValue = Convert.ToUInt64(value); -// return ((iFlags & iValue) == iValue); -// } - -// internal static T SetFlag(this Enum flags, T value, bool state = true) -// { -// if (!Enum.IsDefined(typeof(T), value)) throw new ArgumentException("Enum value and flags types do not match."); -// if (state) return (T) Enum.ToObject(typeof(T), Convert.ToUInt64(flags) | Convert.ToUInt64(value)); -// return (T) Enum.ToObject(typeof(T), Convert.ToUInt64(flags) & ~Convert.ToUInt64(value)); -// } -// } - -// #endregion - -// #region Helper: Byte[] - -// internal static class ByteHelper -// { -// internal static int IndexOf(this byte[] bytes, byte value, int startIndex = 0) -// { -// while (startIndex < bytes.Length) -// if (bytes[startIndex++] == value) -// return startIndex - 1; -// return -1; -// } - -// internal static string GetString(this byte[] bytes, int offset) -// { -// string result = null; -// var index = -1; -// index = bytes.IndexOf(0, offset); -// if (index >= 0) result = Encoding.ASCII.GetString(bytes, offset, index - offset); -// return result; -// } - -// internal static T ToStruct(this byte[] bytes, int start = 0) where T : struct -// { -// var result = new T(); -// var size = Marshal.SizeOf(result); -// var ptr = Marshal.AllocHGlobal(size); -// Marshal.Copy(bytes, start, ptr, size); -// result = (T) Marshal.PtrToStructure(ptr, result.GetType()); -// Marshal.FreeHGlobal(ptr); -// return result; -// } -// } - -// #endregion - -// internal class Hardware -// { -// #region [extern] WindowsAPI - -// [DllImport("USER32.DLL", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] -// private static extern IntPtr CallWindowProcW([In] byte[] bytes, IntPtr hWnd, int msg, [In, Out] byte[] wParam, -// IntPtr lParam); - -// [DllImport("KERNEL32.DLL", CharSet = CharSet.Unicode, SetLastError = true)] -// private static extern bool VirtualProtect([In] byte[] bytes, IntPtr size, int newProtect, out int oldProtect); - -// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] -// private static extern SafeFileHandle CreateFileW([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, -// uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, -// uint dwFlagsAndAttributes, IntPtr hTemplateFile); - -// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, -// SetLastError = true)] -// private static extern bool GetVolumeNameForVolumeMountPoint(string mountPoint, StringBuilder name, -// uint bufferLength); - -// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] -// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, -// STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_DEVICE_ID_DESCRIPTOR lpOutBuffer, -// int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); - -// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] -// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, -// STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_ADAPTER_DESCRIPTOR lpOutBuffer, -// int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); - -// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] -// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, -// STORAGE_PROPERTY_QUERY lpInBuffer, int lpInBufferSize, ref STORAGE_DEVICE_DESCRIPTOR lpOutBuffer, -// int lpOutBufferSize, ref uint lpBytesReturned, int lpOverlapped); - -// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] -// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, -// SENDCMDINPARAMS lpInBuffer, int lpInBufferSize, ref SENDCMDOUTPARAMS lpOutBuffer, int lpOutBufferSize, -// ref uint lpBytesReturned, int lpOverlapped); - -// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] -// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, IntPtr lpInBuffer, -// int lpInBufferSize, ref GETVERSIONOUTPARAMS lpOutBuffer, int lpOutBufferSize, ref uint lpBytesReturned, -// int lpOverlapped); - -// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] -// private static extern bool DeviceIoControl(SafeFileHandle hHandle, uint dwIoControlCode, IntPtr lpInBuffer, -// int lpInBufferSize, ref VOLUMEDISKEXTENTS lpOutBuffer, int lpOutBufferSize, ref uint lpBytesReturned, -// int lpOverlapped); - -// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall)] -// private static extern int CloseHandle(int hObject); - -// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] -// internal static extern int EnumSystemFirmwareTables(BiosFirmwareTableProvider providerSignature, -// IntPtr firmwareTableBuffer, int bufferSize); - -// [DllImport("KERNEL32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] -// private static extern int GetSystemFirmwareTable(BiosFirmwareTableProvider providerSignature, -// int dwFirmwareTableID, IntPtr lpTableBuffer, int dwBufferSize); - -// [DllImport("USER32.DLL", CallingConvention = CallingConvention.StdCall, SetLastError = true)] -// private static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, -// uint dwFlags); - -// #endregion - -// private static byte[] _MD5; -// private static byte[] _SHA1; -// private static byte[] _SHA256; -// private static byte[] _SHA512; - -// private static string GenerateDate = DateTime.Now.ToString("yyyyMMddHH"); - -// // HDD // - -// #region [constants] HDD - -// private const int VER_PLATFORM_WIN32_NT = 2; -// private const int IDENTIFY_BUFFER_SIZE = 512; -// private const int CREATE_NEW = 0x1; -// private const int OPEN_EXISTING = 0x3; -// private const uint GENERIC_READ = 0x80000000; -// private const uint GENERIC_WRITE = 0x40000000; -// private const int FILE_SHARE_READ = 0x00000001; -// private const int FILE_SHARE_WRITE = 0x00000002; -// private const uint IDE_ATAPI_IDENTIFY = 0xA1; -// private const uint IDE_ATA_IDENTIFY = 0xEC; -// private const uint CAP_SMART_CMD = 0x04; -// private const uint METHOD_BUFFERED = 0; -// private const uint FILE_ANY_ACCESS = 0; -// private const uint FILE_ATTRIBUTE_NORMAL = 0x00000080; -// private const uint FILE_DEVICE_CONTROLLER = 0x00000004; -// private const uint IOCTL_SCSI_BASE = FILE_DEVICE_CONTROLLER; -// private const uint FILE_DEVICE_MASS_STORAGE = 0x0000002d; -// private const uint IOCTL_STORAGE_BASE = FILE_DEVICE_MASS_STORAGE; -// private const uint IOCTL_VOLUME_BASE = 0x00000056; -// private const uint IOCTL_SCSI_PASS_THROUGH = 0x0004d004; -// private const uint IOCTL_DISK_GET_DRIVE_GEOMETRY = 0x00070000; -// private const uint IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = 0x000700a0; -// private const uint DFP_GET_VERSION = 0x00074080; -// private const uint DFP_SEND_DRIVE_COMMAND = 0x0007c084; -// private const uint DFP_RECEIVE_DRIVE_DATA = 0x0007c088; -// private const uint IOCTL_STORAGE_GET_DEVICE_NUMBER = 0x002d1080; -// private const uint IOCTL_STORAGE_QUERY_PROPERTY = 0x002d1400; - -// private const uint IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = 0x00560000; - -// // PropertyId For DeviceIoControl // -// private const uint StorageDeviceProperty = 0; -// private const uint StorageAdapterProperty = 1; -// private const uint StorageDeviceIdProperty = 2; - -// private const uint StorageDeviceSeekPenaltyProperty = 7; - -// // Query Type For DeviceIoControl // -// private const uint PropertyStandardQuery = 0; -// private const uint PropertyExistsQuery = 1; - -// #endregion - -// #region [enum] STORAGE_BUS_TYPE - -// internal enum STORAGE_BUS_TYPE : byte -// { -// BusTypeUnknown = 0x00, -// BusTypeScsi = 0x01, -// BusTypeAtapi = 0x02, -// BusTypeAta = 0x03, -// BusType1394 = 0x04, -// BusTypeSsa = 0x05, -// BusTypeFibre = 0x06, -// BusTypeUsb = 0x07, -// BusTypeRAID = 0x08, -// BusTypeiScsi = 0x09, -// BusTypeSas = 0x0A, -// BusTypeSata = 0x0B, -// BusTypeSd = 0x0C, -// BusTypeMmc = 0x0D, -// BusTypeVirtual = 0x0E, -// BusTypeFileBackedVirtual = 0x0F, -// BusTypeMax = 0x10, -// BusTypeMaxReserved = 0x7F -// } - -// #endregion - -// #region [struct] VOLUMEDISKEXTENTS - -// [StructLayout(LayoutKind.Explicit)] -// internal struct VOLUMEDISKEXTENTS -// { -// [FieldOffset(0)] internal uint numberOfDiskExtents; -// [FieldOffset(8)] internal uint diskNumber; -// [FieldOffset(16)] internal long startingOffset; -// [FieldOffset(24)] internal long extentLength; -// } - -// #endregion - -// #region [struct] STORAGE_PROPERTY_QUERY - -// [StructLayout(LayoutKind.Sequential)] -// private struct STORAGE_PROPERTY_QUERY -// { -// internal uint PropertyId; -// internal uint QueryType; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] -// internal byte[] AdditionalParameters; -// } - -// #endregion - -// #region [struct] STORAGE_DEVICE_DESCRIPTOR - -// [StructLayout(LayoutKind.Sequential)] -// internal struct STORAGE_DEVICE_DESCRIPTOR -// { -// internal int Version; -// internal int Size; -// internal byte DeviceType; -// internal byte DeviceTypeModifier; -// internal byte RemovableMedia; -// internal byte CommandQueueing; -// internal int VendorIdOffset; -// internal int ProductIdOffset; -// internal int ProductRevisionOffset; -// internal int SerialNumberOffset; -// internal STORAGE_BUS_TYPE BusType; -// internal int RawPropertiesLength; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10240)] -// internal byte[] RawDeviceProperties; -// } - -// #endregion - -// #region [struct] STORAGE_DEVICE_ID_DESCRIPTOR - -// [StructLayout(LayoutKind.Sequential)] -// internal struct STORAGE_DEVICE_ID_DESCRIPTOR -// { -// internal int Version; -// internal int Size; -// internal int NumberOfIdentifiers; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10240)] -// internal byte[] Identifiers; -// } - -// #endregion - -// #region [struct] STORAGE_ADAPTER_DESCRIPTOR - -// [StructLayout(LayoutKind.Sequential)] -// internal struct STORAGE_ADAPTER_DESCRIPTOR -// { -// internal uint Version; -// internal uint Size; -// internal uint MaximumTransferLength; -// internal uint MaximumPhysicalPages; -// internal uint AlignmentMask; -// internal byte AdapterUsesPio; -// internal byte AdapterScansDown; -// internal byte CommandQueueing; -// internal byte AcceleratedTransfer; -// internal STORAGE_BUS_TYPE BusType; -// internal ushort BusMajorVersion; -// internal ushort BusMinorVersion; -// internal byte SrbType; -// internal byte AddressType; -// } - -// #endregion - -// #region [struct] GETVERSIONOUTPARAMS - -// [StructLayout(LayoutKind.Sequential)] -// internal struct GETVERSIONOUTPARAMS -// { -// internal byte bVersion; -// internal byte bRevision; -// internal byte bReserved; -// internal byte bIDEDeviceMap; -// internal int fCapabilities; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] -// internal int[] dwReserved; -// } - -// #endregion - -// #region [struct] IDEREGS - -// [StructLayout(LayoutKind.Sequential, Size = 8)] -// internal struct IDEREGS -// { -// internal byte Features; -// internal byte SectorCount; -// internal byte SectorNumber; -// internal byte CylinderLow; -// internal byte CylinderHigh; -// internal byte DriveHead; -// internal byte Command; -// internal byte Reserved; -// } - -// #endregion - -// #region [struct] SENDCMDINPARAMS - -// [StructLayout(LayoutKind.Sequential, Size = 32)] -// internal struct SENDCMDINPARAMS -// { -// internal int BufferSize; -// internal IDEREGS DriveRegs; -// internal byte DriveNumber; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] -// internal byte[] bReserved; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] -// internal int[] dwReserved; -// } - -// #endregion - -// #region [struct] DRIVERSTATUS - -// [StructLayout(LayoutKind.Sequential, Size = 12)] -// internal struct DRIVERSTATUS -// { -// internal byte DriveError; -// internal byte IDEStatus; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] -// internal byte[] bReserved; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] -// internal int[] dwReserved; -// } - -// #endregion - -// #region [struct] IDSECTOR - -// [StructLayout(LayoutKind.Sequential)] -// internal struct IDSECTOR -// { -// internal short GenConfig; -// internal short NumberCylinders; -// internal short Reserved; -// internal short NumberHeads; -// internal short BytesPerTrack; -// internal short BytesPerSector; -// internal short SectorsPerTrack; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] -// internal short[] VendorUnique; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] -// internal byte[] SerialNumber; - -// internal short BufferClass; -// internal short BufferSize; -// internal short ECCSize; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] -// internal byte[] FirmwareRevision; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)] -// internal byte[] ModelNumber; - -// internal short MoreVendorUnique; -// internal short DoubleWordIO; -// internal short Capabilities; -// internal short Reserved1; -// internal short PIOTiming; -// internal short DMATiming; -// internal short BS; -// internal short NumberCurrentCyls; -// internal short NumberCurrentHeads; -// internal short NumberCurrentSectorsPerTrack; -// internal int CurrentSectorCapacity; -// internal short MultipleSectorCapacity; -// internal short MultipleSectorStuff; -// internal int TotalAddressableSectors; -// internal short SingleWordDMA; -// internal short MultiWordDMA; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 382)] -// internal byte[] bReserved; -// } - -// #endregion - -// #region [struct] SENDCMDOUTPARAMS - -// [StructLayout(LayoutKind.Sequential)] -// internal struct SENDCMDOUTPARAMS -// { -// internal uint cBufferSize; -// internal DRIVERSTATUS Status; -// internal IDSECTOR IDS; -// } - -// #endregion - -// [StructLayout(LayoutKind.Sequential)] -// internal struct PhysicalDisk -// { -// internal byte Number; -// internal string Model; -// internal string Firmware; -// internal string SerialNumber; -// internal bool RemovableMedia; -// internal VOLUMEDISKEXTENTS Extents; -// internal STORAGE_DEVICE_DESCRIPTOR Device; -// internal STORAGE_DEVICE_ID_DESCRIPTOR DeviceID; -// internal STORAGE_ADAPTER_DESCRIPTOR Adapter; -// internal GETVERSIONOUTPARAMS Version; -// internal SENDCMDOUTPARAMS Params; -// } - -// #region CTL_CODE - -// private uint CTL_CODE(uint DeviceType, uint Function, uint Method, uint Access) -// { -// return ((DeviceType << 16) | (Access << 14) | (Function << 2) | Method); -// } - -// #endregion - -// #region [private] SwapChars - -// private string SwapChars(char[] chars) -// { -// for (var i = 0; i <= chars.Length - 2; i += 2) -// { -// char T; -// T = chars[i]; -// chars[i] = chars[i + 1]; -// chars[i + 1] = T; -// } - -// return new string(chars); -// } - -// #endregion - -// #region [private] SwapBytes - -// private string SwapBytes(byte[] bytes) -// { -// for (var i = 0; i <= bytes.Length - 2; i += 2) -// { -// byte T; -// T = bytes[i]; -// bytes[i] = bytes[i + 1]; -// bytes[i + 1] = T; -// } - -// return Encoding.ASCII.GetString(bytes); -// } - -// #endregion - -// #region [private] SwapRawString - -// private string SwapRawString(string hexString) -// { -// var Result = new StringBuilder(); -// for (var i = 0; i < hexString.Length; i += 4) -// { -// Result.Append(Convert.ToChar(Convert.ToByte(hexString.Substring(i + 2, 2), 16))); -// Result.Append(Convert.ToChar(Convert.ToByte(hexString.Substring(i + 0, 2), 16))); -// } - -// return Result.ToString().Trim('\0', ' '); -// } - -// #endregion - -// #region [private] GetPhysicalDisk - -// private PhysicalDisk GetPhysicalDisk(string path) -// { -// var drive = System.IO.Path.GetPathRoot(path).TrimEnd('\\'); - -// using (var hDisk = CreateFileW(@"\\.\" + drive, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero)) -// { -// var Result = new PhysicalDisk(); -// uint iBytesReturned = 0; -// Result.SerialNumber = string.Empty; -// Result.Firmware = string.Empty; -// Result.Model = string.Empty; - -// //var StoragePropertyQuery = new STORAGE_PROPERTY_QUERY(); - -// Result.Extents = new VOLUMEDISKEXTENTS(); -// Result.Adapter = new STORAGE_ADAPTER_DESCRIPTOR(); -// Result.Device = new STORAGE_DEVICE_DESCRIPTOR(); -// Result.DeviceID = new STORAGE_DEVICE_ID_DESCRIPTOR(); -// Result.Version = new GETVERSIONOUTPARAMS(); -// Result.Params = new SENDCMDOUTPARAMS(); - -// var IOCMD = CTL_CODE(IOCTL_VOLUME_BASE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS); -// if (DeviceIoControl(hDisk, IOCMD, IntPtr.Zero, 0, ref Result.Extents, Marshal.SizeOf(Result.Extents), ref iBytesReturned, 0)) -// { -// Console.ForegroundColor = ConsoleColor.DarkGray; -// Console.WriteLine("Received: IOCTL_VOLUME_BASE"); -// Result.Number = Convert.ToByte(Result.Extents.diskNumber); -// } - - - -// //StoragePropertyQuery.PropertyId = StorageAdapterProperty; -// //StoragePropertyQuery.QueryType = PropertyStandardQuery; - -// //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.Adapter, Marshal.SizeOf(Result.Adapter), ref iBytesReturned, 0)) -// //{ -// // Console.ForegroundColor = ConsoleColor.DarkGray; -// // Console.WriteLine("Received: STORAGE_ADAPTER_DESCRIPTOR"); -// // Console.WriteLine("> Version: "+Result.Adapter.Version+", Size: "+Result.Adapter.Size); -// // Console.WriteLine("> MaximumPhysicalPages: "+Result.Adapter.MaximumPhysicalPages); -// // Console.WriteLine("> MaximumTransferLength: "+Result.Adapter.MaximumTransferLength); -// // Console.WriteLine("> CommandQueueing: "+Result.Adapter.CommandQueueing); -// // Console.WriteLine("> BusMajorVersion: "+Result.Adapter.BusMajorVersion); -// // Console.WriteLine("> BusMinorVersion: "+Result.Adapter.BusMinorVersion); -// // Console.WriteLine("> BusType: "+Result.Adapter.BusType); -// //} - - - -// //StoragePropertyQuery.PropertyId = StorageDeviceIdProperty; -// //StoragePropertyQuery.QueryType = PropertyStandardQuery; -// //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.DeviceID, Marshal.SizeOf(Result.DeviceID), ref iBytesReturned, 0)) -// //{ -// // /File.WriteAllBytes("Hardware."+GenerateDate+".RAID-"+drive[0]+".bin", Result.DeviceID.Identifiers); -// // Console.ForegroundColor = ConsoleColor.DarkGray; -// // Console.WriteLine("Received: STORAGE_DEVICE_ID_DESCRIPTOR"); -// // Console.WriteLine("> Version: "+Result.DeviceID.Version+", Size: "+Result.DeviceID.Size); -// // Console.WriteLine("> NumberOfIdentifiers: "+Result.DeviceID.NumberOfIdentifiers); -// //} - - - -// //StoragePropertyQuery.PropertyId = StorageDeviceProperty; -// //StoragePropertyQuery.QueryType = PropertyStandardQuery; -// //if (DeviceIoControl(hDisk, IOCTL_STORAGE_QUERY_PROPERTY, StoragePropertyQuery, Marshal.SizeOf(StoragePropertyQuery), ref Result.Device, Marshal.SizeOf(Result.Device), ref iBytesReturned, 0)) -// //{ -// // /File.WriteAllBytes("Hardware."+GenerateDate+".HDD-"+drive[0]+".bin", Result.Device.RawDeviceProperties); -// // Console.ForegroundColor = ConsoleColor.DarkGray; -// // Console.WriteLine("Received: STORAGE_DEVICE_DESCRIPTOR"); -// // Console.WriteLine("> RemovableMedia: "+Convert.ToBoolean(Result.Device.RemovableMedia)); -// // Console.WriteLine("> DeviceType: "+Result.Device.DeviceType); -// // Console.WriteLine("> BusType: "+Result.Device.BusType); - -// // var buffer = Encoding.ASCII.GetString(Result.Device.RawDeviceProperties); -// // var basepos = Marshal.SizeOf(Result.Device) - Result.Device.RawDeviceProperties.Length; - -// // if (Result.Device.ProductIdOffset > 0) -// // Result.Model = buffer.Substring(Result.Device.ProductIdOffset - basepos, 20).Trim('\0', ' '); -// // if (Result.Device.ProductRevisionOffset > 0) -// // Result.Firmware = buffer.Substring(Result.Device.ProductRevisionOffset - basepos, 8).Trim('\0', ' '); -// // if (Result.Device.SerialNumberOffset > 0) -// // Result.SerialNumber = -// // buffer.Substring(Result.Device.SerialNumberOffset - basepos, 40).Trim('\0', ' '); -// // if (Result.SerialNumber != null && Result.SerialNumber.Length == 40) -// // Result.SerialNumber = SwapRawString(Result.SerialNumber); - -// // Result.RemovableMedia = Convert.ToBoolean(Result.Device.RemovableMedia); -// //} - -// DeviceIoControl(hDisk, DFP_GET_VERSION, IntPtr.Zero, 0, ref Result.Version, Marshal.SizeOf(Result.Version), ref iBytesReturned, 0); - -// if ((Result.Version.fCapabilities & CAP_SMART_CMD) > 0) -// { -// Console.ForegroundColor = ConsoleColor.DarkGray; -// Console.WriteLine("Received: GETVERSIONOUTPARAMS"); -// Console.WriteLine("> Version: "+Result.Version.bVersion+"."+Result.Version.bRevision); -// var SCI = new SENDCMDINPARAMS -// { -// DriveRegs = {Command = (int) IDE_ATA_IDENTIFY}, -// DriveNumber = Result.Number, -// BufferSize = IDENTIFY_BUFFER_SIZE -// }; - -// if (DeviceIoControl(hDisk, DFP_RECEIVE_DRIVE_DATA, SCI, Marshal.SizeOf(SCI), ref Result.Params, Marshal.SizeOf(Result.Params), ref iBytesReturned, 0)) -// { -// Console.WriteLine("Received: SENDCMDOUTPARAMS"); -// Console.WriteLine("> IDS.Capabilities: "+Result.Params.IDS.Capabilities); -// Console.WriteLine("> IDS.BufferSize: "+Result.Params.IDS.BufferSize); -// Console.WriteLine("> IDS.SectorsPerTrack: "+Result.Params.IDS.SectorsPerTrack); -// Console.WriteLine("> IDS.NumberCylinders: "+Result.Params.IDS.NumberCylinders); -// Console.WriteLine("> IDS.NumberHeads: "+Result.Params.IDS.NumberHeads); - -// Result.Model = SwapBytes(Result.Params.IDS.ModelNumber).Trim(); -// Result.Firmware = SwapBytes(Result.Params.IDS.FirmwareRevision).Trim(); -// Result.SerialNumber = SwapBytes(Result.Params.IDS.SerialNumber).Trim(); -// } - -// } - -// return Result; -// } - -// throw new Win32Exception(); -// } - -// #endregion - -// // CPU // - -// #region [enum] BiosFirmwareTableProvider - -// internal enum BiosFirmwareTableProvider -// { -// ACPI = (byte) 'A' << 24 | (byte) 'C' << 16 | (byte) 'P' << 8 | (byte) 'I', -// FIRM = (byte) 'F' << 24 | (byte) 'I' << 16 | (byte) 'R' << 8 | (byte) 'M', -// RSMB = (byte) 'R' << 24 | (byte) 'S' << 16 | (byte) 'M' << 8 | (byte) 'B' -// } - -// #endregion - -// #region [enum] SMBIOSTableType - -// internal enum SMBIOSTableType : sbyte -// { -// BIOSInformation = 0, -// SystemInformation = 1, -// BaseBoardInformation = 2, -// EnclosureInformation = 3, -// ProcessorInformation = 4, -// MemoryControllerInformation = 5, -// MemoryModuleInformation = 6, -// CacheInformation = 7, -// PortConnectorInformation = 8, -// SystemSlotsInformation = 9, -// OnBoardDevicesInformation = 10, -// OEMStrings = 11, -// SystemConfigurationOptions = 12, -// BIOSLanguageInformation = 13, -// GroupAssociations = 14, -// SystemEventLog = 15, -// PhysicalMemoryArray = 16, -// MemoryDevice = 17, -// MemoryErrorInformation = 18, -// MemoryArrayMappedAddress = 19, -// MemoryDeviceMappedAddress = 20, -// EndofTable = 127 -// } - -// #endregion - -// #region [enum] SMBIOSTableEntry - -// [StructLayout(LayoutKind.Sequential)] -// internal struct SMBIOSTableHeader -// { -// internal SMBIOSTableType type; -// internal byte length; -// internal ushort Handle; -// } - -// [StructLayout(LayoutKind.Sequential)] -// internal struct SMBIOSTableEntry -// { -// internal SMBIOSTableHeader header; -// internal uint index; -// } - -// #endregion - -// #region [enum] SMBIOSTableInfo - -// [StructLayout(LayoutKind.Sequential)] -// internal struct SMBIOSTableBiosInfo -// { -// internal SMBIOSTableHeader header; -// internal byte vendor; -// internal byte version; -// internal ushort startingSegment; -// internal byte releaseDate; -// internal byte biosRomSize; -// internal ulong characteristics; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] -// internal byte[] extensionBytes; -// } - -// [StructLayout(LayoutKind.Sequential)] -// internal struct SMBIOSTableSystemInfo -// { -// internal SMBIOSTableHeader header; -// internal byte manufacturer; -// internal byte productName; -// internal byte version; -// internal byte serialNumber; - -// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] -// internal byte[] UUID; - -// internal byte wakeUpType; -// } - -// [StructLayout(LayoutKind.Sequential)] -// internal struct SMBIOSTableBaseBoardInfo -// { -// internal SMBIOSTableHeader header; -// internal byte manufacturer; -// internal byte productName; -// internal byte version; -// internal byte serialNumber; -// } - -// [StructLayout(LayoutKind.Sequential)] -// internal struct SMBIOSTableEnclosureInfo -// { -// internal SMBIOSTableHeader header; -// internal byte manufacturer; -// internal byte type; -// internal byte version; -// internal byte serialNumber; -// internal byte assetTagNumber; -// internal byte bootUpState; -// internal byte powerSupplyState; -// internal byte thermalState; -// internal byte securityStatus; -// internal long OEM_Defined; -// } - -// [StructLayout(LayoutKind.Sequential)] -// internal struct SMBIOSTableProcessorInfo -// { -// internal SMBIOSTableHeader header; -// internal byte socketDesignation; -// internal byte processorType; -// internal byte processorFamily; -// internal byte processorManufacturer; -// internal ulong processorID; -// internal byte processorVersion; -// internal byte processorVoltage; -// internal ushort externalClock; -// internal ushort maxSpeed; -// internal ushort currentSpeed; -// internal byte status; -// internal byte processorUpgrade; -// internal ushort L1CacheHandler; -// internal ushort L2CacheHandler; -// internal ushort L3CacheHandler; -// internal byte serialNumber; -// internal byte assetTag; -// internal byte partNumber; -// } - -// [StructLayout(LayoutKind.Sequential)] -// internal struct SMBIOSTableCacheInfo -// { -// internal SMBIOSTableHeader header; -// internal byte socketDesignation; -// internal long cacheConfiguration; -// internal ushort maximumCacheSize; -// internal ushort installedSize; -// internal ushort supportedSRAMType; -// internal ushort currentSRAMType; -// internal byte cacheSpeed; -// internal byte errorCorrectionType; -// internal byte systemCacheType; -// internal byte associativity; -// } - -// #endregion - -// #region [struct] RawSMBIOSData - -// [StructLayout(LayoutKind.Sequential)] -// internal struct RawSMBIOSData -// { -// internal byte Used20CallingMethod; -// internal byte MajorVersion; -// internal byte MinorVersion; -// internal byte DmiRevision; -// internal uint Length; -// internal SMBIOSTableBiosInfo BiosInfo; -// internal SMBIOSTableSystemInfo SystemInfo; -// internal SMBIOSTableBaseBoardInfo BaseBoardInfo; -// internal SMBIOSTableEnclosureInfo EnclosureInfo; -// internal SMBIOSTableProcessorInfo ProcessorInfo; -// internal SMBIOSTableCacheInfo CacheInfo; -// } - -// #endregion - -// #region [private] GetTable - -// private static byte[] GetTable(BiosFirmwareTableProvider provider, string table) -// { -// var id = table[3] << 24 | table[2] << 16 | table[1] << 8 | table[0]; -// return GetTable(provider, id); -// } - -// private static byte[] GetTable(BiosFirmwareTableProvider provider, int table) -// { -// var Result = new byte[0]; -// try -// { -// var sizeNeeded = GetSystemFirmwareTable(provider, table, IntPtr.Zero, 0); -// if (sizeNeeded > 0) -// { -// var bufferPtr = Marshal.AllocHGlobal(sizeNeeded); -// GetSystemFirmwareTable(provider, table, bufferPtr, sizeNeeded); -// if (Marshal.GetLastWin32Error() == 0) -// { -// Result = new byte[sizeNeeded]; -// Marshal.Copy(bufferPtr, Result, 0, sizeNeeded); -// } - -// Marshal.FreeHGlobal(bufferPtr); -// } -// } -// catch -// { -// } - -// return Result; -// } - -// #endregion - -// #region [private] EnumerateTables - -// private static string[] EnumerateTables(BiosFirmwareTableProvider provider) -// { -// var Result = new string[0]; -// try -// { -// var sizeNeeded = EnumSystemFirmwareTables(provider, IntPtr.Zero, 0); -// if (sizeNeeded > 0) -// { -// var buffer = new byte[sizeNeeded]; -// var bufferPtr = Marshal.AllocHGlobal(sizeNeeded); -// EnumSystemFirmwareTables(provider, bufferPtr, sizeNeeded); -// if (Marshal.GetLastWin32Error() == 0) -// { -// Result = new string[sizeNeeded / 4]; -// Marshal.Copy(bufferPtr, buffer, 0, sizeNeeded); -// for (var i = 0; i < Result.Length; i++) Result[i] = Encoding.ASCII.GetString(buffer, 4 * i, 4); -// } - -// Marshal.FreeHGlobal(bufferPtr); -// } -// } -// catch -// { -// } - -// return Result; -// } - -// #endregion - -// #region [private] GetRawStrings - -// private static string[] GetRawStrings(byte[] bytes, SMBIOSTableEntry entry, ref int pos) -// { -// var result = new List(); -// pos += entry.header.length; -// do -// { -// string s = bytes.GetString(pos); -// result.Add(s); -// pos += s.Length; -// } while (bytes[++pos] != 0); - -// pos++; -// return result.ToArray(); -// } - -// #endregion - -// // VIDEO // - -// #region [enum] DisplayDeviceStateFlags - -// internal enum DisplayDeviceStateFlags -// { -// AttachedToDesktop = 0x0000001, -// MultiDriver = 0x0000002, -// PrimaryDevice = 0x0000004, -// MirroringDriver = 0x0000008, -// VGACompatible = 0x0000010, -// Removable = 0x0000020, -// ModesPruned = 0x8000000, -// Remote = 0x4000000, -// Disconnect = 0x2000000 -// } - -// #endregion - -// #region [struct] DISPLAY_DEVICE - -// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] -// internal struct DISPLAY_DEVICE -// { -// [MarshalAs(UnmanagedType.U4)] internal int structSize; - -// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] -// internal string DeviceName; - -// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] -// internal string DeviceString; - -// [MarshalAs(UnmanagedType.U4)] internal DisplayDeviceStateFlags StateFlags; - -// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] -// internal string DeviceID; - -// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] -// internal string DeviceKey; -// } - -// #endregion - -// internal Hardware() -// { -// using (var Binary = new BinaryWriter(new MemoryStream())) -// { - -// Console.WriteLine(); - -// Console.ForegroundColor = ConsoleColor.White; - -// Console.WriteLine("[SMBIOS]"); - -// // Get BIOS Information // -// var RSMB_Tables = EnumerateTables(BiosFirmwareTableProvider.RSMB); -// if (RSMB_Tables.Length > 0) -// { -// var RSMB = GetTable(BiosFirmwareTableProvider.RSMB, RSMB_Tables[0]); -// if (RSMB.Length > 0) -// { - -// File.WriteAllBytes("BIOS." + BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(RSMB), 0).Replace("-", "") + ".RSMB.bin", RSMB); - -// Binary.Write(RSMB); - -// var RawStrings = new string[0]; -// RawSMBIOSData SMBIOS = RSMB.ToStruct(); - -// if (SMBIOS.Length > 8) -// { -// var pos = 0x08; -// while (pos < SMBIOS.Length) -// { - -// Console.ForegroundColor = ConsoleColor.Green; -// SMBIOSTableEntry tableEntry = RSMB.ToStruct(pos); -// switch (tableEntry.header.type) -// { -// case SMBIOSTableType.BIOSInformation: -// SMBIOS.BiosInfo = RSMB.ToStruct(pos); -// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - -// Console.WriteLine("BIOSInformation"); - -// Console.ForegroundColor = ConsoleColor.Yellow; - -// if (SMBIOS.BiosInfo.vendor > 0 && SMBIOS.BiosInfo.vendor <= RawStrings.Length) -// Console.WriteLine("Vendor: " + RawStrings[SMBIOS.BiosInfo.vendor - 1]); - -// if (SMBIOS.BiosInfo.version > 0 && SMBIOS.BiosInfo.version <= RawStrings.Length) -// Console.WriteLine("Version: " + RawStrings[SMBIOS.BiosInfo.version - 1]); -// break; -// case SMBIOSTableType.SystemInformation: -// SMBIOS.SystemInfo = RSMB.ToStruct(pos); -// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - -// Console.WriteLine("SystemInformation"); - -// Console.ForegroundColor = ConsoleColor.Yellow; - -// if (SMBIOS.SystemInfo.manufacturer > 0 && -// SMBIOS.SystemInfo.manufacturer <= RawStrings.Length) -// Console.WriteLine("Manufacturer: " + RawStrings[SMBIOS.SystemInfo.manufacturer - 1]); - -// if (SMBIOS.SystemInfo.productName > 0 && -// SMBIOS.SystemInfo.productName <= RawStrings.Length) -// Console.WriteLine("Product name: " + RawStrings[SMBIOS.SystemInfo.productName - 1]); - -// if (SMBIOS.SystemInfo.version > 0 && SMBIOS.SystemInfo.version <= RawStrings.Length) -// Console.WriteLine("Version: " + RawStrings[SMBIOS.SystemInfo.version - 1]); - -// if (SMBIOS.SystemInfo.serialNumber > 0 && -// SMBIOS.SystemInfo.serialNumber <= RawStrings.Length) -// Console.WriteLine("Serial Number: " + RawStrings[SMBIOS.SystemInfo.serialNumber - 1]); -// break; -// case SMBIOSTableType.BaseBoardInformation: -// SMBIOS.BaseBoardInfo = RSMB.ToStruct(pos); -// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - -// Console.WriteLine("BaseBoardInformation"); - -// Console.ForegroundColor = ConsoleColor.Yellow; - -// if (SMBIOS.BaseBoardInfo.manufacturer > 0 && -// SMBIOS.BaseBoardInfo.manufacturer <= RawStrings.Length) -// Console.WriteLine("Manufacturer: " + -// RawStrings[SMBIOS.BaseBoardInfo.manufacturer - 1]); - -// if (SMBIOS.BaseBoardInfo.productName > 0 && -// SMBIOS.BaseBoardInfo.productName <= RawStrings.Length) -// Console.WriteLine("Product name: " + RawStrings[SMBIOS.BaseBoardInfo.productName - 1]); - -// if (SMBIOS.BaseBoardInfo.version > 0 && SMBIOS.BaseBoardInfo.version <= RawStrings.Length) -// Console.WriteLine("Version: " + RawStrings[SMBIOS.BaseBoardInfo.version - 1]); - -// if (SMBIOS.BaseBoardInfo.serialNumber > 0 && -// SMBIOS.BaseBoardInfo.serialNumber <= RawStrings.Length) -// Console.WriteLine( -// "Serial Number: " + RawStrings[SMBIOS.BaseBoardInfo.serialNumber - 1]); -// break; -// case SMBIOSTableType.EnclosureInformation: -// SMBIOS.EnclosureInfo = RSMB.ToStruct(pos); -// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - -// Console.WriteLine("EnclosureInformation"); - -// Console.ForegroundColor = ConsoleColor.Yellow; - -// if (SMBIOS.EnclosureInfo.manufacturer > 0 && -// SMBIOS.EnclosureInfo.manufacturer <= RawStrings.Length) -// Console.WriteLine("Manufacturer: " + -// RawStrings[SMBIOS.EnclosureInfo.manufacturer - 1]); - -// if (SMBIOS.EnclosureInfo.version > 0 && SMBIOS.EnclosureInfo.version <= RawStrings.Length) -// Console.WriteLine("Version: " + RawStrings[SMBIOS.EnclosureInfo.version - 1]); - -// if (SMBIOS.EnclosureInfo.serialNumber > 0 && -// SMBIOS.EnclosureInfo.serialNumber <= RawStrings.Length) -// Console.WriteLine( -// "Serial Number: " + RawStrings[SMBIOS.EnclosureInfo.serialNumber - 1]); - -// if (SMBIOS.EnclosureInfo.assetTagNumber > 0 && -// SMBIOS.EnclosureInfo.assetTagNumber <= RawStrings.Length) -// Console.WriteLine("Asset Tag Number: " + -// RawStrings[SMBIOS.EnclosureInfo.assetTagNumber - 1]); -// break; -// case SMBIOSTableType.ProcessorInformation: -// SMBIOS.ProcessorInfo = RSMB.ToStruct(pos); -// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - -// Console.WriteLine("ProcessorInformation"); - -// Console.ForegroundColor = ConsoleColor.Yellow; - -// if (SMBIOS.ProcessorInfo.processorManufacturer > 0 && -// SMBIOS.ProcessorInfo.processorManufacturer <= RawStrings.Length) -// Console.WriteLine("Manufacturer: " + -// RawStrings[SMBIOS.ProcessorInfo.processorManufacturer - 1]); - -// if (SMBIOS.ProcessorInfo.processorType > 0 && -// SMBIOS.ProcessorInfo.processorType <= RawStrings.Length) -// Console.WriteLine("Model: " + RawStrings[SMBIOS.ProcessorInfo.processorType - 1]); - -// if (SMBIOS.ProcessorInfo.processorFamily > 0 && -// SMBIOS.ProcessorInfo.processorFamily <= RawStrings.Length) -// Console.WriteLine("Family: " + RawStrings[SMBIOS.ProcessorInfo.processorFamily - 1]); - -// if (SMBIOS.ProcessorInfo.serialNumber > 0 && -// SMBIOS.ProcessorInfo.serialNumber <= RawStrings.Length) -// Console.WriteLine( -// "Serial Number: " + RawStrings[SMBIOS.ProcessorInfo.serialNumber - 1]); - -// if (SMBIOS.ProcessorInfo.assetTag > 0 && -// SMBIOS.ProcessorInfo.assetTag <= RawStrings.Length) -// Console.WriteLine("Asset Tag: " + RawStrings[SMBIOS.ProcessorInfo.assetTag - 1]); -// break; -// case SMBIOSTableType.CacheInformation: -// SMBIOS.CacheInfo = RSMB.ToStruct(pos); -// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); - -// Console.WriteLine("CacheInformation [" + RawStrings[0] + "]"); - -// Console.ForegroundColor = ConsoleColor.Yellow; - -// Console.WriteLine("Installed Size: " + SMBIOS.CacheInfo.installedSize); - -// Console.WriteLine("Maximum CacheSize: " + SMBIOS.CacheInfo.maximumCacheSize); -// break; -// default: -// Console.WriteLine(tableEntry.header.type); -// RawStrings = GetRawStrings(RSMB, tableEntry, ref pos); -// break; -// } -// } -// } -// } -// } - -// var tableIndex = 0; -// foreach (var biosTable in EnumerateTables(BiosFirmwareTableProvider.FIRM)) -// { -// var FIRM = GetTable(BiosFirmwareTableProvider.FIRM, biosTable); - -// File.WriteAllBytes("BIOS." + BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(FIRM), 0).Replace("-", "") + ".FIRM" + (tableIndex++) + ".bin", FIRM); - -// } - - -// Console.WriteLine(); - -// Console.ForegroundColor = ConsoleColor.White; - -// Console.WriteLine("[CPU]"); - -// // Get CPU Information (Count, ID) // -// byte[] code_x86 = { -// 0x55, 0x89, 0xe5, 0x57, 0x8b, 0x7d, 0x10, 0x6a, 0x01, 0x58, 0x53, 0x0f, 0xa2, 0x89, 0x07, 0x89, 0x57, -// 0x04, 0x5b, 0x5f, 0x89, 0xec, 0x5d, 0xc2, 0x10, 0x00 -// }; -// byte[] code_x64 = { -// 0x53, 0x48, 0xc7, 0xc0, 0x01, 0x00, 0x00, 0x00, 0x0f, 0xa2, 0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, -// 0x5b, 0xc3 -// }; -// var CPUID = new byte[8]; -// byte[] asmCode; -// int protect; -// if (IntPtr.Size == 8) asmCode = code_x64; -// else asmCode = code_x86; -// var asmSize = new IntPtr(asmCode.Length); -// if (!VirtualProtect(asmCode, asmSize, 0x40, out protect)) -// Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); -// asmSize = new IntPtr(CPUID.Length); -// if (CallWindowProcW(asmCode, IntPtr.Zero, 0, CPUID, asmSize) == IntPtr.Zero) return; -// var RegKey = -// Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor"); -// var ProcessorName = RegKey.OpenSubKey("0").GetValue("ProcessorNameString").ToString(); -// var CPUIdentifier = RegKey.OpenSubKey("0").GetValue("Identifier").ToString(); -// var ProcessorCores = RegKey.GetSubKeyNames(); - - -// Console.ForegroundColor = ConsoleColor.Green; - -// Console.WriteLine(ProcessorName + ", " + CPUIdentifier); - -// Console.ForegroundColor = ConsoleColor.Yellow; - -// Console.WriteLine("> Processor Cores: " + ProcessorCores.Length); - -// Console.WriteLine("> ID: " + BitConverter.ToString(CPUID, 0).Replace("-", "")); - -// Binary.Write(ProcessorName); -// Binary.Write(CPUIdentifier); -// Binary.Write(ProcessorCores.Length); -// Binary.Write(CPUID); - - -// Console.WriteLine(); - -// Console.ForegroundColor = ConsoleColor.White; - -// Console.WriteLine("[DRIVES]"); - -// // Get HDD Information // -// foreach (var drive in Environment.GetLogicalDrives()) -// { -// var disk = GetPhysicalDisk(drive); -// if (disk.RemovableMedia) continue; - -// Console.ForegroundColor = ConsoleColor.Green; - -// Console.WriteLine("Disk: " + drive); - -// Console.ForegroundColor = ConsoleColor.Yellow; - -// Console.WriteLine("> Model: " + disk.Model + ", Firmware: " + disk.Firmware + "\n> Serial: " + -// disk.SerialNumber); -// if (string.IsNullOrEmpty(disk.Model) || string.IsNullOrEmpty(disk.Firmware)) continue; -// Binary.Write(disk.Model); -// Binary.Write(disk.Firmware); -// Binary.Write(disk.SerialNumber); -// } - - -// Console.WriteLine(); - -// Console.ForegroundColor = ConsoleColor.White; - -// Console.WriteLine("[VIDEO]"); - -// // Get VIDEO Information // -// try -// { -// var display = new DISPLAY_DEVICE(); -// display.structSize = Marshal.SizeOf(display); -// for (uint i = 0; EnumDisplayDevices(null, i, ref display, 0); i++) -// { -// if (display.DeviceString == null) continue; -// if (display.StateFlags.HasFlag(DisplayDeviceStateFlags.PrimaryDevice)) -// { - -// Console.ForegroundColor = ConsoleColor.Green; - -// Console.WriteLine(display.DeviceString); - -// Console.ForegroundColor = ConsoleColor.Yellow; - -// Console.WriteLine("DeviceID: " + display.DeviceID); - -// Console.WriteLine("State Flags: " + display.StateFlags); -// Binary.Write(display.DeviceString); -// if (display.DeviceID != null) Binary.Write(display.DeviceID); -// } -// } -// } -// catch (Exception) -// { -// /* Ignore all exceptions of detecting video */ -// } - -// // Seek Stream Origin To Beginning and Compute Binary Buffer to MD5 // -// Binary.BaseStream.Seek(0, SeekOrigin.Begin); -// _MD5 = new MD5CryptoServiceProvider().ComputeHash(Binary.BaseStream); -// // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA1 // -// Binary.BaseStream.Seek(0, SeekOrigin.Begin); -// _SHA1 = new SHA1CryptoServiceProvider().ComputeHash(Binary.BaseStream); -// // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA256 // -// Binary.BaseStream.Seek(0, SeekOrigin.Begin); -// _SHA256 = new SHA256CryptoServiceProvider().ComputeHash(Binary.BaseStream); -// // Seek Stream Origin To Beginning and Compute Binary Buffer to SHA512 // -// Binary.BaseStream.Seek(0, SeekOrigin.Begin); -// _SHA512 = new SHA512CryptoServiceProvider().ComputeHash(Binary.BaseStream); -// } - -// Console.ResetColor(); -// } - -// internal byte[] MD5 -// { -// get -// { -// if (_MD5 == null || _MD5.Length < 16) return new byte[0]; -// return _MD5; -// } -// } - -// internal byte[] SHA1 -// { -// get -// { -// if (_SHA1 == null || _SHA1.Length < 16) return new byte[0]; -// return _SHA1; -// } -// } - -// internal byte[] SHA256 -// { -// get -// { -// if (_SHA256 == null || _SHA256.Length < 16) return new byte[0]; -// return _SHA256; -// } -// } - -// internal byte[] SHA512 -// { -// get -// { -// if (_SHA512 == null || _SHA512.Length < 16) return new byte[0]; -// return _SHA512; -// } -// } - -// internal string MD5String -// { -// get -// { -// if (_MD5 == null || _MD5.Length < 16) return ""; -// return BitConverter.ToString(_MD5, 0).Replace("-", ""); -// } -// } - -// internal string SHA1String -// { -// get -// { -// if (_SHA1 == null || _SHA1.Length < 16) return ""; -// return BitConverter.ToString(_SHA1, 0).Replace("-", ""); -// } -// } - -// internal string SHA256String -// { -// get -// { -// if (_SHA256 == null || _SHA256.Length < 16) return ""; -// return BitConverter.ToString(_SHA256, 0).Replace("-", ""); -// } -// } - -// internal string SHA512String -// { -// get -// { -// if (_SHA512 == null || _SHA512.Length < 16) return ""; -// return BitConverter.ToString(_SHA512, 0).Replace("-", ""); -// } -// } -// } -//} From 7d591a8095bc247c5af82055bf0f2f28d0198150 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Wed, 20 Jun 2018 21:58:47 +0200 Subject: [PATCH 127/133] Split file. --- AlphaFS/AlphaFS.csproj | 3 +- ...DiskInfo.CreatePhysicalDiskInfoInstance.cs | 251 +++++++++++++++++ .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 261 +----------------- 3 files changed, 268 insertions(+), 247 deletions(-) create mode 100644 AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 4a1cc59f4..52a6682b9 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -202,6 +202,7 @@ + @@ -743,7 +744,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs new file mode 100644 index 000000000..cdb071e43 --- /dev/null +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs @@ -0,0 +1,251 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Globalization; +using System.Security; +using System.Security.AccessControl; +using Alphaleonis.Win32.Filesystem; +using Alphaleonis.Win32.Security; + +namespace Alphaleonis.Win32.Device +{ + public sealed partial class PhysicalDiskInfo + { + [SecurityCritical] + private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) + { + var isElevated = ProcessContext.IsElevatedProcess; + var getByDeviceNumber = deviceNumber > -1; + + bool isDrive; + bool isVolume; + bool isDevice; + + if (null != deviceInfo) + devicePath = deviceInfo.DevicePath; + + var localDevicePath = FileSystemHelper.GetValidatedDevicePath(getByDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : devicePath, out isDrive, out isVolume, out isDevice); + + localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); + + string physicalDriveNumberPath = null; + + // The StorageDeviceInfo is always needed as it contains the device- and partition number. + + StorageDeviceInfo = storageDeviceInfo ?? Local.GetStorageDeviceInfo(isElevated, isDevice, deviceNumber, localDevicePath, out physicalDriveNumberPath); + + if (null == StorageDeviceInfo) + return; + + deviceNumber = getByDeviceNumber ? deviceNumber : StorageDeviceInfo.DeviceNumber; + + if (!SetDeviceInfoDataFromDeviceNumber(isElevated, deviceNumber, deviceInfo)) + return; + + + // If physicalDriveNumberPath != null, the drive is opened using: "\\.\PhysicalDriveX" path format + // which is the device, not the volume/logical drive. + + localDevicePath = FileSystemHelper.GetValidatedDevicePath(physicalDriveNumberPath ?? localDevicePath, out isDrive, out isVolume, out isDevice); + + + AddDeviceInfoData(isElevated, deviceNumber, localDevicePath); + + UpdateDeviceInfodata(isElevated, isDevice, localDevicePath); + + PopulatePhysicalDisk(isElevated); + } + + + private void AddDeviceInfoData(bool isElevated, int deviceNumber, string localDevicePath) + { + DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); + + + using (var safeFileHandle = Local.OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) + { + StorageAdapterInfo = Local.GetStorageAdapterInfo(safeFileHandle, deviceNumber, localDevicePath, DeviceInfo.BusReportedDeviceDescription); + + StoragePartitionInfo = Local.GetStoragePartitionInfo(safeFileHandle, deviceNumber, localDevicePath); + } + } + + + /// Retrieves volumes/logical drives that belong to the PhysicalDiskInfo instance. + [SecurityCritical] + private void PopulatePhysicalDisk(bool isElevated) + { + var deviceNumber = StorageDeviceInfo.DeviceNumber; + + _partitionIndexCollection = new Collection(); + _volumeGuidCollection = new Collection(); + _logicalDriveCollection = new Collection(); + + + foreach (var volumeGuid in Volume.EnumerateVolumes()) + { + string unusedLocalDevicePath; + + // The StorageDeviceInfo is always needed as it contains the device- and partition number. + + var storageDeviceInfo = Local.GetStorageDeviceInfo(isElevated, false, deviceNumber, volumeGuid, out unusedLocalDevicePath); + + if (null == storageDeviceInfo) + continue; + + + _partitionIndexCollection.Add(storageDeviceInfo.PartitionNumber); + + _volumeGuidCollection.Add(volumeGuid); + + + // Resolve logical drive from volume matching DeviceNumber and PartitionNumber. + + var driveName = Volume.GetVolumeDisplayName(volumeGuid); + + if (!Utils.IsNullOrWhiteSpace(driveName)) + + _logicalDriveCollection.Add(Path.RemoveTrailingDirectorySeparator(driveName)); + } + + + PartitionIndexes = _partitionIndexCollection; + + VolumeGuids = _volumeGuidCollection; + + LogicalDrives = _logicalDriveCollection; + } + + + [SecurityCritical] + private bool SetDeviceInfoDataFromDeviceNumber(bool isElevated, int deviceNumber, DeviceInfo deviceInfo) + { + if (null == deviceInfo) + foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) + { + string unusedDevicePath; + + var storageDeviceInfo = Local.GetStorageDeviceInfo(isElevated, true, deviceNumber, device.DevicePath, out unusedDevicePath); + + if (null != storageDeviceInfo) + { + deviceInfo = device; + break; + } + } + + + DeviceInfo = deviceInfo; + + return null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); + } + + + [SecurityCritical] + private void UpdateDeviceInfodata(bool isElevated, bool isDevice, string localDevicePath) + { + if (StoragePartitionInfo.OnDynamicDisk) + { + // At this point, PartitionNumber is 0 which points to the device. + // Get the user data partition information. + + foreach (var partition in StoragePartitionInfo.GptPartitionInfo) + { + if (partition.PartitionType == PartitionType.LdmData) + { + StorageDeviceInfo.PartitionNumber = partition.PartitionNumber; + + StorageDeviceInfo.TotalSize = partition.PartitionLength; + + break; + } + } + } + + else if (!isElevated && StorageDeviceInfo.TotalSize == 0 && null != StoragePartitionInfo) + + StorageDeviceInfo.TotalSize = isDevice ? StoragePartitionInfo.TotalSize : new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; + } + + + + + /// Returns the "FriendlyName" of the physical disk. + /// Returns a string that represents this instance. + public override string ToString() + { + return Name ?? DevicePath; + } + + + /// Determines whether the specified Object is equal to the current Object. + /// Another object to compare to. + /// true if the specified Object is equal to the current Object; otherwise, false. + public override bool Equals(object obj) + { + if (null == obj || GetType() != obj.GetType()) + return false; + + var other = obj as PhysicalDiskInfo; + + return null != other && + other.Name == Name && + other.DevicePath == DevicePath && + other.DosDeviceName == DosDeviceName && + other.PhysicalDeviceObjectName == PhysicalDeviceObjectName && + other.PartitionIndexes == PartitionIndexes && + other.VolumeGuids == VolumeGuids && + other.LogicalDrives == LogicalDrives && + other.StorageAdapterInfo == StorageAdapterInfo && + other.StorageDeviceInfo == StorageDeviceInfo && + other.StoragePartitionInfo == StoragePartitionInfo; + } + + + /// Serves as a hash function for a particular type. + /// Returns a hash code for the current Object. + public override int GetHashCode() + { + return null != DevicePath ? DevicePath.GetHashCode() : 0; + } + + + /// Implements the operator == + /// A. + /// B. + /// The result of the operator. + public static bool operator ==(PhysicalDiskInfo left, PhysicalDiskInfo right) + { + return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); + } + + + /// Implements the operator != + /// A. + /// B. + /// The result of the operator. + public static bool operator !=(PhysicalDiskInfo left, PhysicalDiskInfo right) + { + return !(left == right); + } + } +} diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index d9e15560c..c4e9e36c1 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -22,11 +22,8 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Globalization; using System.Security; -using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; -using Alphaleonis.Win32.Security; namespace Alphaleonis.Win32.Device { @@ -51,8 +48,8 @@ private PhysicalDiskInfo() } - /// [AlphaFS] Initializes an instance from a physical disk number. - /// A number that indicates a physical disk on the Computer. + /// [AlphaFS] Initializes an instance from a physical disk device number. + /// A device number that indicates a physical disk on the Computer. public PhysicalDiskInfo(int deviceNumber) { if (deviceNumber < 0) @@ -94,52 +91,47 @@ internal PhysicalDiskInfo(int deviceNumber, StorageDeviceInfo storageDeviceInfo, private DeviceInfo DeviceInfo { get; set; } - /// The . + /// The device description. public string DeviceDescription { - get { return null != DeviceInfo ? DeviceInfo.DeviceDescription : null; } + get { return null != DeviceInfo ? DeviceInfo.DeviceDescription : string.Empty; } } - /// The path to the device. - /// Returns a string that represents the path to the device. - /// A drive path such as: C:, D:\, - /// a volume path such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ - /// or a string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string. - /// + /// The device path. public string DevicePath { - get { return null != DeviceInfo ? DeviceInfo.DevicePath : null; } + get { return null != DeviceInfo ? DeviceInfo.DevicePath : string.Empty; } } - /// The Win32 Device name. + /// The Win32 device name. public string DosDeviceName { get; private set; } - /// An of logical drives that are located on the physical disk or null when no entries found. + /// An of logical drives that are located on the physical disk. public IEnumerable LogicalDrives { get; private set; } - /// The . + /// The device (friendly) name. public string Name { - get { return null != DeviceInfo ? DeviceInfo.FriendlyName : null; } + get { return null != DeviceInfo ? DeviceInfo.FriendlyName : string.Empty; } } - /// An of partition index numbers that are located on the physical disk or null when no entries found. + /// An of partition index numbers that are located on the physical disk. public IEnumerable PartitionIndexes { get; private set; } - /// The (PDO) information provided by a device's firmware to Windows. + /// The device (PDO) information provided by a device's firmware to Windows. public string PhysicalDeviceObjectName { - get { return null != DeviceInfo ? DeviceInfo.PhysicalDeviceObjectName : null; } + get { return null != DeviceInfo ? DeviceInfo.PhysicalDeviceObjectName : string.Empty; } } - /// The storage device adapter information. Retrieving this information requires an elevated state. + /// The storage device adapter information. public StorageAdapterInfo StorageAdapterInfo { get; private set; } @@ -151,232 +143,9 @@ public string PhysicalDeviceObjectName public StoragePartitionInfo StoragePartitionInfo { get; private set; } - /// An of volume strings of volumes that are located on the physical disk or null when no entries found. + /// An of volume strings that are located on the physical disk. public IEnumerable VolumeGuids { get; private set; } #endregion // Properties - - - #region Methods - - [SecurityCritical] - private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, StorageDeviceInfo storageDeviceInfo, DeviceInfo deviceInfo) - { - var isElevated = ProcessContext.IsElevatedProcess; - var getByDeviceNumber = deviceNumber > -1; - - bool isDrive; - bool isVolume; - bool isDevice; - - if (null != deviceInfo) - devicePath = deviceInfo.DevicePath; - - var localDevicePath = FileSystemHelper.GetValidatedDevicePath(getByDeviceNumber ? Path.PhysicalDrivePrefix + deviceNumber.ToString(CultureInfo.InvariantCulture) : devicePath, out isDrive, out isVolume, out isDevice); - - localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - - string physicalDriveNumberPath = null; - - // The StorageDeviceInfo is always needed as it contains the device- and partition number. - - StorageDeviceInfo = storageDeviceInfo ?? Local.GetStorageDeviceInfo(isElevated, isDevice, deviceNumber, localDevicePath, out physicalDriveNumberPath); - - if (null == StorageDeviceInfo) - return; - - deviceNumber = getByDeviceNumber ? deviceNumber : StorageDeviceInfo.DeviceNumber; - - if (!SetDeviceInfoDataFromDeviceNumber(isElevated, deviceNumber, deviceInfo)) - return; - - - // If physicalDriveNumberPath != null, the drive is opened using: "\\.\PhysicalDriveX" path format - // which is the device, not the volume/logical drive. - - localDevicePath = FileSystemHelper.GetValidatedDevicePath(physicalDriveNumberPath ?? localDevicePath, out isDrive, out isVolume, out isDevice); - - - AddDeviceInfoData(isElevated, deviceNumber, localDevicePath); - - UpdateDeviceInfodata(isElevated, isDevice, localDevicePath); - - PopulatePhysicalDisk(isElevated); - } - - - private void AddDeviceInfoData(bool isElevated, int deviceNumber, string localDevicePath) - { - DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); - - - using (var safeFileHandle = Local.OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) - { - StorageAdapterInfo = Local.GetStorageAdapterInfo(safeFileHandle, deviceNumber, localDevicePath, DeviceInfo.BusReportedDeviceDescription); - - StoragePartitionInfo = Local.GetStoragePartitionInfo(safeFileHandle, deviceNumber, localDevicePath); - } - } - - - /// Retrieves volumes/logical drives that belong to the PhysicalDiskInfo instance. - [SecurityCritical] - private void PopulatePhysicalDisk(bool isElevated) - { - var deviceNumber = StorageDeviceInfo.DeviceNumber; - - _partitionIndexCollection = new Collection(); - _volumeGuidCollection = new Collection(); - _logicalDriveCollection = new Collection(); - - - foreach (var volumeGuid in Volume.EnumerateVolumes()) - { - string unusedLocalDevicePath; - - // The StorageDeviceInfo is always needed as it contains the device- and partition number. - - var storageDeviceInfo = Local.GetStorageDeviceInfo(isElevated, false, deviceNumber, volumeGuid, out unusedLocalDevicePath); - - if (null == storageDeviceInfo) - continue; - - - _partitionIndexCollection.Add(storageDeviceInfo.PartitionNumber); - - _volumeGuidCollection.Add(volumeGuid); - - - // Resolve logical drive from volume matching DeviceNumber and PartitionNumber. - - var driveName = Volume.GetVolumeDisplayName(volumeGuid); - - if (!Utils.IsNullOrWhiteSpace(driveName)) - - _logicalDriveCollection.Add(Path.RemoveTrailingDirectorySeparator(driveName)); - } - - - PartitionIndexes = _partitionIndexCollection; - - VolumeGuids = _volumeGuidCollection; - - LogicalDrives = _logicalDriveCollection; - } - - - [SecurityCritical] - private bool SetDeviceInfoDataFromDeviceNumber(bool isElevated, int deviceNumber, DeviceInfo deviceInfo) - { - if (null == deviceInfo) - foreach (var device in Local.EnumerateDevicesCore(null, new[] {DeviceGuid.Disk, DeviceGuid.CDRom}, false)) - { - string unusedDevicePath; - - var storageDeviceInfo = Local.GetStorageDeviceInfo(isElevated, true, deviceNumber, device.DevicePath, out unusedDevicePath); - - if (null != storageDeviceInfo) - { - deviceInfo = device; - break; - } - } - - - DeviceInfo = deviceInfo; - - return null != deviceInfo && !Utils.IsNullOrWhiteSpace(deviceInfo.DevicePath); - } - - - [SecurityCritical] - private void UpdateDeviceInfodata(bool isElevated, bool isDevice, string localDevicePath) - { - if (StoragePartitionInfo.OnDynamicDisk) - { - // At this point, PartitionNumber is 0 which points to the device. - // Get the user data partition information. - - foreach (var partition in StoragePartitionInfo.GptPartitionInfo) - { - if (partition.PartitionType == PartitionType.LdmData) - { - StorageDeviceInfo.PartitionNumber = partition.PartitionNumber; - - StorageDeviceInfo.TotalSize = partition.PartitionLength; - - break; - } - } - } - - else if (!isElevated && StorageDeviceInfo.TotalSize == 0 && null != StoragePartitionInfo) - - StorageDeviceInfo.TotalSize = isDevice ? StoragePartitionInfo.TotalSize : new DiskSpaceInfo(localDevicePath, false, true, true).TotalNumberOfBytes; - } - - - - - /// Returns the "FriendlyName" of the physical disk. - /// Returns a string that represents this instance. - public override string ToString() - { - return Name ?? DevicePath; - } - - - /// Determines whether the specified Object is equal to the current Object. - /// Another object to compare to. - /// true if the specified Object is equal to the current Object; otherwise, false. - public override bool Equals(object obj) - { - if (null == obj || GetType() != obj.GetType()) - return false; - - var other = obj as PhysicalDiskInfo; - - return null != other && - other.Name == Name && - other.DevicePath == DevicePath && - other.DosDeviceName == DosDeviceName && - other.PhysicalDeviceObjectName == PhysicalDeviceObjectName && - other.PartitionIndexes == PartitionIndexes && - other.VolumeGuids == VolumeGuids && - other.LogicalDrives == LogicalDrives && - other.StorageAdapterInfo == StorageAdapterInfo && - other.StorageDeviceInfo == StorageDeviceInfo && - other.StoragePartitionInfo == StoragePartitionInfo; - } - - - /// Serves as a hash function for a particular type. - /// Returns a hash code for the current Object. - public override int GetHashCode() - { - return null != DevicePath ? DevicePath.GetHashCode() : 0; - } - - - /// Implements the operator == - /// A. - /// B. - /// The result of the operator. - public static bool operator ==(PhysicalDiskInfo left, PhysicalDiskInfo right) - { - return ReferenceEquals(left, null) && ReferenceEquals(right, null) || !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right); - } - - - /// Implements the operator != - /// A. - /// B. - /// The result of the operator. - public static bool operator !=(PhysicalDiskInfo left, PhysicalDiskInfo right) - { - return !(left == right); - } - - #endregion // Methods } } From e4178118eb630d907638de572bfcaf4cc20ea4a1 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 21 Jun 2018 19:31:43 +0200 Subject: [PATCH 128/133] -Added method Alphaleonis.Win32.Device.Local.GetDevicePowerState; -Added property PhysicalDiskInfo.PowerStateEnabled; -Renamed native member; --- .../AlphaFS_DeviceTest.GetDevicePowerState.cs | 50 +++ .../AlphaFS_DeviceTest.cs | 31 ++ AlphaFS.UnitTest/AlphaFS.UnitTest.csproj | 2 + AlphaFS/AlphaFS.csproj | 6 +- AlphaFS/Device/Local/Local.GetDeviceIoData.cs | 2 +- ...Volume.cs => Local.GetDevicePowerState.cs} | 40 +-- .../Device/Local/Local.GetDiskGeometryEx.cs | 2 +- .../Local/Local.GetStorageDeviceInfo.cs | 50 +-- .../Device/Local/Local.InvokeDeviceIoData.cs | 2 +- AlphaFS/Device/Local/Local.OpenDevice.cs | 19 -- .../NativeMethods.DeviceManagement.cs | 12 + AlphaFS/Device/Native Other/DEVICE_TYPE.cs | 255 --------------- AlphaFS/Device/Native Other/FILE_DEVICE.cs | 255 +++++++++++++++ AlphaFS/Device/Native Other/IoControlCode.cs | 274 ++++++++-------- .../Native Other/STORAGE_DEVICE_NUMBER.cs | 4 +- ...DiskInfo.CreatePhysicalDiskInfoInstance.cs | 23 +- .../Device/PhysicalDisk/PhysicalDiskInfo.cs | 8 + .../Storage/Device.StorageAdapterInfo.cs | 2 +- .../Storage/Device.StorageDeviceInfo.cs | 6 +- .../Structures, Enumerations/DeviceType.cs | 296 +++++++++--------- AlphaFS/Filesystem/File Class/File.Create.cs | 66 ---- .../NativeMethods.FileManagement.cs | 5 - AlphaFS/Utils.cs | 29 +- 23 files changed, 720 insertions(+), 719 deletions(-) create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.GetDevicePowerState.cs create mode 100644 AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs rename AlphaFS/Device/Local/{Local.GetDeviceNumbersForVolume.cs => Local.GetDevicePowerState.cs} (52%) delete mode 100644 AlphaFS/Device/Native Other/DEVICE_TYPE.cs create mode 100644 AlphaFS/Device/Native Other/FILE_DEVICE.cs diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.GetDevicePowerState.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.GetDevicePowerState.cs new file mode 100644 index 000000000..d33143748 --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.GetDevicePowerState.cs @@ -0,0 +1,50 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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_DeviceTest + { + // Pattern: ___ + + + [TestMethod] + public void AlphaFS_Local_GetDevicePowerState() + { + UnitTestConstants.PrintUnitTestHeader(false); + + var devicePath = UnitTestConstants.SysDrive; + + + // We may assume that the system drive is awake when running unit tests. + + var isOn = Alphaleonis.Win32.Device.Local.GetDevicePowerState(devicePath); + + + Console.WriteLine("\tInput Device Path: [{0}] Power State On: [{1}]", devicePath, isOn); + + Assert.IsTrue(isOn); + } + } +} diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs new file mode 100644 index 000000000..00e838b3a --- /dev/null +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_DeviceTest.cs @@ -0,0 +1,31 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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; + +namespace AlphaFS.UnitTest +{ + /// This is a test class for Device.Local and is intended to contain all Device.Local Unit Tests. + [TestClass] + public partial class AlphaFS_DeviceTest + { + } +} diff --git a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj index baf85efff..2a7adad26 100644 --- a/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj +++ b/AlphaFS.UnitTest/AlphaFS.UnitTest.csproj @@ -144,9 +144,11 @@ AssemblyVersionInfo.cs + + diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 52a6682b9..a4c0eea2d 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -197,7 +197,7 @@ True - + @@ -373,7 +373,7 @@ - + @@ -744,7 +744,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Device/Local/Local.GetDeviceIoData.cs b/AlphaFS/Device/Local/Local.GetDeviceIoData.cs index de3ce3547..9d40cc82e 100644 --- a/AlphaFS/Device/Local/Local.GetDeviceIoData.cs +++ b/AlphaFS/Device/Local/Local.GetDeviceIoData.cs @@ -54,7 +54,7 @@ private static SafeGlobalMemoryBufferHandle GetDeviceIoData(SafeFileHandle sa { if (lastError == Win32Errors.ERROR_NOT_READY || - // A logical drive path like \\.\D: fails on a dynamic disk. + // A logical drive path like "\\.\D:" fails on a dynamic disk. lastError == Win32Errors.ERROR_INVALID_FUNCTION || // Request device number from a DeviceGuid.Image device. diff --git a/AlphaFS/Device/Local/Local.GetDeviceNumbersForVolume.cs b/AlphaFS/Device/Local/Local.GetDevicePowerState.cs similarity index 52% rename from AlphaFS/Device/Local/Local.GetDeviceNumbersForVolume.cs rename to AlphaFS/Device/Local/Local.GetDevicePowerState.cs index 03b67c615..6c4b5643b 100644 --- a/AlphaFS/Device/Local/Local.GetDeviceNumbersForVolume.cs +++ b/AlphaFS/Device/Local/Local.GetDevicePowerState.cs @@ -20,49 +20,29 @@ */ using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Security; -using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { public static partial class Local { - /// Returns an of physical drive device numbers used by the specified volume. - /// - /// An initialized instance. - /// - /// A drive path such as: \\.\C: + /// [AlphaFS] Retrieves the current power state for the specified storage device. + /// Returns true if the storage device is in the working state; otherwise, false. + /// + /// A disk path such as: \\.\PhysicalDrive0 + /// A drive path such as: C, C: or C:\ /// A volume such as: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ + /// A string such as: \\?\scsi#disk...{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} /// [SecurityCritical] - private static IEnumerable GetDeviceNumbersForVolume(SafeFileHandle safeFileHandle, string localDevicePath) + public static bool GetDevicePowerState(string devicePath) { - var physicalDrives = new Collection(); - - var disposeHandle = null == safeFileHandle; - - try + using (var safeFileHandle = OpenDevice(FileSystemHelper.GetLocalDevicePath(devicePath), NativeMethods.FILE_ANY_ACCESS)) { - if (null == safeFileHandle) - safeFileHandle = OpenDevice(localDevicePath, NativeMethods.FILE_ANY_ACCESS); - - var volDiskExtents = GetVolumeDiskExtents(safeFileHandle, localDevicePath); - - if (volDiskExtents.HasValue) - - foreach (var extent in volDiskExtents.Value.Extents) + bool isOn; - physicalDrives.Add((int) extent.DiskNumber); + return NativeMethods.GetDevicePowerState(safeFileHandle, out isOn) && isOn; } - finally - { - if (disposeHandle && null != safeFileHandle && !safeFileHandle.IsClosed) - safeFileHandle.Close(); - } - - return physicalDrives; } } } diff --git a/AlphaFS/Device/Local/Local.GetDiskGeometryEx.cs b/AlphaFS/Device/Local/Local.GetDiskGeometryEx.cs index 61305eca8..a5a31eea9 100644 --- a/AlphaFS/Device/Local/Local.GetDiskGeometryEx.cs +++ b/AlphaFS/Device/Local/Local.GetDiskGeometryEx.cs @@ -72,7 +72,7 @@ private static NativeMethods.DISK_GEOMETRY_EX GetDiskGeometryEx(SafeFileHandle s if (lastError == Win32Errors.ERROR_NOT_READY || - // A logical drive path like \\.\D: fails on a dynamic disk. + // A logical drive path like "\\.\D:" fails on a dynamic disk. lastError == Win32Errors.ERROR_INVALID_FUNCTION || // Request device number from a DeviceGuid.Image device. diff --git a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs index da2f40863..8ceafb749 100644 --- a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs +++ b/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs @@ -20,18 +20,17 @@ */ using System; +using System.Collections.Generic; using System.Globalization; using System.Security; using System.Security.AccessControl; using Alphaleonis.Win32.Filesystem; +using Microsoft.Win32.SafeHandles; namespace Alphaleonis.Win32.Device { public static partial class Local { - // /// When this method is called from a non-elevated state, the property always returns 0. - - /// Returns a instance that represent the storage device that is related to . /// [SecurityCritical] @@ -45,13 +44,12 @@ internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isD int lastError; - // Accessing a volume like: "\\.\D" on a dynamic disk fails with ERROR_INVALID_FUNCTION. - // On retry, the drive is accessed using the: "\\.\PhysicalDriveX" path format which is the device, not the volume/logical drive. + // On retry, the drive is accessed using "\\.\PhysicalDriveX" path format which is the device, not the volume/logical drive. using (var safeFileHandle = OpenDevice(localDevicePath, isElevated ? FileSystemRights.Read : NativeMethods.FILE_ANY_ACCESS)) using (var safeBuffer = GetDeviceIoData(safeFileHandle, NativeMethods.IoControlCode.IOCTL_STORAGE_GET_DEVICE_NUMBER, localDevicePath, out lastError)) - + { if (null != safeBuffer) { var storageDeviceInfo = new StorageDeviceInfo(safeBuffer.PtrToStructure()); @@ -69,28 +67,40 @@ internal static StorageDeviceInfo GetStorageDeviceInfo(bool isElevated, bool isD } - // A logical drive path on a dynamic disk like \\.\D: fails. + // A logical drive path on a dynamic disk like "\\.\D:" fails. - if (!retry && !isDevice && lastError == Win32Errors.ERROR_INVALID_FUNCTION) - { - foreach (var physicalDeviceNumber in GetDeviceNumbersForVolume(null, localDevicePath)) - { - if (getByDeviceNumber && deviceNumber != physicalDeviceNumber) - continue; + if (!retry && !isDevice && lastError == Win32Errors.ERROR_INVALID_FUNCTION) + foreach (var physicalDeviceNumber in GetDeviceNumbersForVolume(safeFileHandle, localDevicePath)) + { + if (getByDeviceNumber && deviceNumber != physicalDeviceNumber) + continue; - // By opening the device as PhysicalDriveX, StorageDeviceInfo.PartitionNumber = 0. + // StorageDeviceInfo.PartitionNumber = 0 when opening the device as "\\.\PhysicalDriveX". - localDevicePath = Path.PhysicalDrivePrefix + physicalDeviceNumber.ToString(CultureInfo.InvariantCulture); + localDevicePath = Path.PhysicalDrivePrefix + physicalDeviceNumber.ToString(CultureInfo.InvariantCulture); - isDevice = true; - retry = true; + isDevice = true; + retry = true; - goto Retry; - } + goto Retry; + } } - return null; } + + + /// Returns an of physical drive device numbers used by the specified volume. + [SecurityCritical] + private static IEnumerable GetDeviceNumbersForVolume(SafeFileHandle safeFileHandle, string pathForException) + { + var volDiskExtents = GetVolumeDiskExtents(safeFileHandle, pathForException); + + if (volDiskExtents.HasValue) + + foreach (var extent in volDiskExtents.Value.Extents) + + yield return (int) extent.DiskNumber; + } } } diff --git a/AlphaFS/Device/Local/Local.InvokeDeviceIoData.cs b/AlphaFS/Device/Local/Local.InvokeDeviceIoData.cs index 60ffb0f90..581dd8e05 100644 --- a/AlphaFS/Device/Local/Local.InvokeDeviceIoData.cs +++ b/AlphaFS/Device/Local/Local.InvokeDeviceIoData.cs @@ -55,7 +55,7 @@ internal static SafeGlobalMemoryBufferHandle InvokeDeviceIoData(SafeFileHandl { if (lastError == Win32Errors.ERROR_NOT_READY || - // A logical drive path like \\.\D: fails on a dynamic disk. + // A logical drive path like "\\.\D:" fails on a dynamic disk. lastError == Win32Errors.ERROR_INVALID_FUNCTION || // Request device number from a DeviceGuid.Image device. diff --git a/AlphaFS/Device/Local/Local.OpenDevice.cs b/AlphaFS/Device/Local/Local.OpenDevice.cs index 584bf6bf2..426182e0f 100644 --- a/AlphaFS/Device/Local/Local.OpenDevice.cs +++ b/AlphaFS/Device/Local/Local.OpenDevice.cs @@ -60,24 +60,5 @@ public static SafeFileHandle OpenDevice(string devicePath, FileSystemRights file return File.CreateFileCore(null, devicePath, ExtendedFileAttributes.Normal | ExtendedFileAttributes.NoBuffering, null, FileMode.Open, fileSystemRights, FileShare.ReadWrite, false, false, PathFormat.LongFullPath); } - - - - - internal static SafeFileHandle OpenDevice2(string devicePath, FileSystemRights fileSystemRights) - { - // fileSystemRights: If this parameter is 0 (FILE_ANY_ACCESS), the application can query certain metadata such as file, directory, or device attributes - // without accessing that file or device, even if GENERIC_READ access would have been denied. - // You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. - // - // - // When opening a volume or removable media drive (for example, a floppy disk drive or flash memory thumb drive), the lpFileName string should be the following form: "\\.\X:". - // Do not use a trailing backslash (\), which indicates the root directory of a drive. - // - // When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITE flag. - - - return File.CreateFileCore2(null, devicePath, ExtendedFileAttributes.Normal | ExtendedFileAttributes.NoBuffering, null, FileMode.Open, fileSystemRights, FileShare.ReadWrite, false, false, PathFormat.LongFullPath); - } } } diff --git a/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs b/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs index 55ea3d09c..266a6c35f 100644 --- a/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs +++ b/AlphaFS/Device/Native Methods/NativeMethods.DeviceManagement.cs @@ -297,5 +297,17 @@ internal static partial class NativeMethods internal static extern bool SetupDiGetDeviceRegistryProperty(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, SPDRP property, IntPtr propertyRegDataType, SafeGlobalMemoryBufferHandle propertyBuffer, [MarshalAs(UnmanagedType.U4)] uint propertyBufferSize, IntPtr requiredSize); #endregion // SetupDiXxx + + + /// Retrieves the current power state of the specified device. This function cannot be used to query the power state of a display device. + /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. + /// + /// Minimum supported client: Windows XP [desktop apps only] + /// Minimum supported server: Windows Server 2003 [desktop apps only] + /// + [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 GetDevicePowerState(SafeHandle hDevice, out bool pfOn); } } diff --git a/AlphaFS/Device/Native Other/DEVICE_TYPE.cs b/AlphaFS/Device/Native Other/DEVICE_TYPE.cs deleted file mode 100644 index 31705ecb6..000000000 --- a/AlphaFS/Device/Native Other/DEVICE_TYPE.cs +++ /dev/null @@ -1,255 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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.Device -{ - internal static partial class NativeMethods - { - /// The storage device type. - internal enum DEVICE_TYPE - { - /// FILE_DEVICE_BEEP parameter. - FILE_DEVICE_BEEP = 1, - - /// FILE_DEVICE_CD_ROM parameter. - FILE_DEVICE_CD_ROM = 2, - - /// FILE_DEVICE_CD_ROM_FILE_SYSTEM parameter. - FILE_DEVICE_CD_ROM_FILE_SYSTEM = 3, - - /// FILE_DEVICE_CONTROLLER parameter. - FILE_DEVICE_CONTROLLER = 4, - - /// FILE_DEVICE_DATALINK parameter. - FILE_DEVICE_DATALINK = 5, - - /// FILE_DEVICE_DFS parameter. - FILE_DEVICE_DFS = 6, - - /// FILE_DEVICE_DISK parameter. - FILE_DEVICE_DISK = 7, - - /// FILE_DEVICE_DISK_FILE_SYSTEM parameter. - FILE_DEVICE_DISK_FILE_SYSTEM = 8, - - /// FILE_DEVICE_FILE_SYSTEM parameter. - FILE_DEVICE_FILE_SYSTEM = 9, - - /// FILE_DEVICE_INPORT_PORT parameter. - FILE_DEVICE_INPORT_PORT = 10, - - /// FILE_DEVICE_KEYBOARD parameter. - FILE_DEVICE_KEYBOARD = 11, - - /// FILE_DEVICE_MAILSLOT parameter. - FILE_DEVICE_MAILSLOT = 12, - - /// FILE_DEVICE_MIDI_IN parameter. - FILE_DEVICE_MIDI_IN = 13, - - /// FILE_DEVICE_MIDI_OUT parameter. - FILE_DEVICE_MIDI_OUT = 14, - - /// FILE_DEVICE_MOUSE parameter. - FILE_DEVICE_MOUSE = 15, - - /// FILE_DEVICE_MULTI_UNC_PROVIDER parameter. - FILE_DEVICE_MULTI_UNC_PROVIDER = 16, - - /// FILE_DEVICE_NAMED_PIPE parameter. - FILE_DEVICE_NAMED_PIPE = 17, - - /// FILE_DEVICE_NETWORK parameter. - FILE_DEVICE_NETWORK = 18, - - /// FILE_DEVICE_NETWORK_BROWSER parameter. - FILE_DEVICE_NETWORK_BROWSER = 19, - - /// FILE_DEVICE_NETWORK_FILE_SYSTEM parameter. - FILE_DEVICE_NETWORK_FILE_SYSTEM = 20, - - /// FILE_DEVICE_NULL parameter. - FILE_DEVICE_NULL = 21, - - /// FILE_DEVICE_PARALLEL_PORT parameter. - FILE_DEVICE_PARALLEL_PORT = 22, - - /// FILE_DEVICE_PHYSICAL_NETCARD parameter. - FILE_DEVICE_PHYSICAL_NETCARD = 23, - - /// FILE_DEVICE_PRINTER parameter. - FILE_DEVICE_PRINTER = 24, - - /// FILE_DEVICE_SCANNER parameter. - FILE_DEVICE_SCANNER = 25, - - /// FILE_DEVICE_SERIAL_MOUSE_PORT parameter. - FILE_DEVICE_SERIAL_MOUSE_PORT = 26, - - /// FILE_DEVICE_SERIAL_PORT parameter. - FILE_DEVICE_SERIAL_PORT = 27, - - /// FILE_DEVICE_SCREEN parameter. - FILE_DEVICE_SCREEN = 28, - - /// FILE_DEVICE_SOUND parameter. - FILE_DEVICE_SOUND = 29, - - /// FILE_DEVICE_STREAMS parameter. - FILE_DEVICE_STREAMS = 30, - - /// FILE_DEVICE_TAPE parameter. - FILE_DEVICE_TAPE = 31, - - /// FILE_DEVICE_TAPE_FILE_SYSTEM parameter. - FILE_DEVICE_TAPE_FILE_SYSTEM = 32, - - /// FILE_DEVICE_TRANSPORT parameter. - FILE_DEVICE_TRANSPORT = 33, - - /// FILE_DEVICE_UNKNOWN parameter. - FILE_DEVICE_UNKNOWN = 34, - - /// FILE_DEVICE_VIDEO parameter. - FILE_DEVICE_VIDEO = 35, - - /// FILE_DEVICE_VIRTUAL_DISK parameter. - FILE_DEVICE_VIRTUAL_DISK = 36, - - /// FILE_DEVICE_WAVE_IN parameter. - FILE_DEVICE_WAVE_IN = 37, - - /// FILE_DEVICE_WAVE_OUT parameter. - FILE_DEVICE_WAVE_OUT = 38, - - /// FILE_DEVICE_8042_PORT parameter. - FILE_DEVICE_8042_PORT = 39, - - /// FILE_DEVICE_NETWORK_REDIRECTOR parameter. - FILE_DEVICE_NETWORK_REDIRECTOR = 40, - - /// FILE_DEVICE_BATTERY parameter. - FILE_DEVICE_BATTERY = 41, - - /// FILE_DEVICE_BUS_EXTENDER parameter. - FILE_DEVICE_BUS_EXTENDER = 42, - - /// FILE_DEVICE_MODEM parameter. - FILE_DEVICE_MODEM = 43, - - /// FILE_DEVICE_VDM parameter. - FILE_DEVICE_VDM = 44, - - /// FILE_DEVICE_MASS_STORAGE parameter. - FILE_DEVICE_MASS_STORAGE = 45, - - /// FILE_DEVICE_SMB parameter. - FILE_DEVICE_SMB = 46, - - /// FILE_DEVICE_KS parameter. - FILE_DEVICE_KS = 47, - - /// FILE_DEVICE_CHANGER parameter. - FILE_DEVICE_CHANGER = 48, - - /// FILE_DEVICE_SMARTCARD parameter. - FILE_DEVICE_SMARTCARD = 49, - - /// FILE_DEVICE_ACPI parameter. - FILE_DEVICE_ACPI = 50, - - /// FILE_DEVICE_DVD parameter. - FILE_DEVICE_DVD = 51, - - /// FILE_DEVICE_FULLSCREEN_VIDEO parameter. - FILE_DEVICE_FULLSCREEN_VIDEO = 52, - - /// FILE_DEVICE_DFS_FILE_SYSTEM parameter. - FILE_DEVICE_DFS_FILE_SYSTEM = 53, - - /// FILE_DEVICE_DFS_VOLUME parameter. - FILE_DEVICE_DFS_VOLUME = 54, - - /// FILE_DEVICE_SERENUM parameter. - FILE_DEVICE_SERENUM = 55, - - /// FILE_DEVICE_TERMSRV parameter. - FILE_DEVICE_TERMSRV = 56, - - /// FILE_DEVICE_KSEC parameter. - FILE_DEVICE_KSEC = 57, - - /// FILE_DEVICE_FIPS parameter. - FILE_DEVICE_FIPS = 58, - - /// FILE_DEVICE_INFINIBAND parameter. - FILE_DEVICE_INFINIBAND = 59, - - /// FILE_DEVICE_VMBUS parameter. - FILE_DEVICE_VMBUS = 62, - - /// FILE_DEVICE_CRYPT_PROVIDER parameter. - FILE_DEVICE_CRYPT_PROVIDER = 63, - - /// FILE_DEVICE_WPD parameter. - FILE_DEVICE_WPD = 64, - - /// FILE_DEVICE_BLUETOOTH parameter. - FILE_DEVICE_BLUETOOTH = 65, - - /// FILE_DEVICE_MT_COMPOSITE parameter. - FILE_DEVICE_MT_COMPOSITE = 66, - - /// FILE_DEVICE_MT_TRANSPORT parameter. - FILE_DEVICE_MT_TRANSPORT = 67, - - /// FILE_DEVICE_BIOMETRIC parameter. - FILE_DEVICE_BIOMETRIC = 68, - - /// FILE_DEVICE_PMI parameter. - FILE_DEVICE_PMI = 69, - - /// FILE_DEVICE_EHSTOR parameter. - FILE_DEVICE_EHSTOR = 70, - - /// FILE_DEVICE_DEVAPI parameter. - FILE_DEVICE_DEVAPI = 71, - - /// FILE_DEVICE_GPIO parameter. - FILE_DEVICE_GPIO = 72, - - /// FILE_DEVICE_USBEX parameter. - FILE_DEVICE_USBEX = 73, - - /// FILE_DEVICE_CONSOLE parameter. - FILE_DEVICE_CONSOLE = 80, - - /// FILE_DEVICE_NFP parameter. - FILE_DEVICE_NFP = 81, - - /// FILE_DEVICE_SYSENV parameter. - FILE_DEVICE_SYSENV = 82, - - /// FILE_DEVICE_MASS_STORAGE parameter. - FILE_DEVICE_VOLUME = 86 - } - } -} diff --git a/AlphaFS/Device/Native Other/FILE_DEVICE.cs b/AlphaFS/Device/Native Other/FILE_DEVICE.cs new file mode 100644 index 000000000..56f5cba5f --- /dev/null +++ b/AlphaFS/Device/Native Other/FILE_DEVICE.cs @@ -0,0 +1,255 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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.Device +{ + internal static partial class NativeMethods + { + /// The storage device type. + internal enum FILE_DEVICE + { + /// BEEP parameter. + BEEP = 1, + + /// CD_ROM parameter. + CD_ROM = 2, + + /// CD_ROM_FILE_SYSTEM parameter. + CD_ROM_FILE_SYSTEM = 3, + + /// CONTROLLER parameter. + CONTROLLER = 4, + + /// DATALINK parameter. + DATALINK = 5, + + /// DFS parameter. + DFS = 6, + + /// DISK parameter. + DISK = 7, + + /// DISK_FILE_SYSTEM parameter. + DISK_FILE_SYSTEM = 8, + + /// FILE_SYSTEM parameter. + FILE_SYSTEM = 9, + + /// INPORT_PORT parameter. + INPORT_PORT = 10, + + /// KEYBOARD parameter. + KEYBOARD = 11, + + /// MAILSLOT parameter. + MAILSLOT = 12, + + /// MIDI_IN parameter. + MIDI_IN = 13, + + /// MIDI_OUT parameter. + MIDI_OUT = 14, + + /// MOUSE parameter. + MOUSE = 15, + + /// MULTI_UNC_PROVIDER parameter. + MULTI_UNC_PROVIDER = 16, + + /// NAMED_PIPE parameter. + NAMED_PIPE = 17, + + /// NETWORK parameter. + NETWORK = 18, + + /// NETWORK_BROWSER parameter. + NETWORK_BROWSER = 19, + + /// NETWORK_FILE_SYSTEM parameter. + NETWORK_FILE_SYSTEM = 20, + + /// NULL parameter. + NULL = 21, + + /// PARALLEL_PORT parameter. + PARALLEL_PORT = 22, + + /// PHYSICAL_NETCARD parameter. + PHYSICAL_NETCARD = 23, + + /// PRINTER parameter. + PRINTER = 24, + + /// SCANNER parameter. + SCANNER = 25, + + /// SERIAL_MOUSE_PORT parameter. + SERIAL_MOUSE_PORT = 26, + + /// SERIAL_PORT parameter. + SERIAL_PORT = 27, + + /// SCREEN parameter. + SCREEN = 28, + + /// SOUND parameter. + SOUND = 29, + + /// STREAMS parameter. + STREAMS = 30, + + /// TAPE parameter. + TAPE = 31, + + /// TAPE_FILE_SYSTEM parameter. + TAPE_FILE_SYSTEM = 32, + + /// TRANSPORT parameter. + TRANSPORT = 33, + + /// UNKNOWN parameter. + UNKNOWN = 34, + + /// VIDEO parameter. + VIDEO = 35, + + /// VIRTUAL_DISK parameter. + VIRTUAL_DISK = 36, + + /// WAVE_IN parameter. + WAVE_IN = 37, + + /// WAVE_OUT parameter. + WAVE_OUT = 38, + + /// 8042_PORT parameter. + PORT_8042 = 39, + + /// NETWORK_REDIRECTOR parameter. + NETWORK_REDIRECTOR = 40, + + /// BATTERY parameter. + BATTERY = 41, + + /// BUS_EXTENDER parameter. + BUS_EXTENDER = 42, + + /// MODEM parameter. + MODEM = 43, + + /// VDM parameter. + VDM = 44, + + /// MASS_STORAGE parameter. + MASS_STORAGE = 45, + + /// SMB parameter. + SMB = 46, + + /// KS parameter. + KS = 47, + + /// CHANGER parameter. + CHANGER = 48, + + /// SMARTCARD parameter. + SMARTCARD = 49, + + /// ACPI parameter. + ACPI = 50, + + /// DVD parameter. + DVD = 51, + + /// FULLSCREEN_VIDEO parameter. + FULLSCREEN_VIDEO = 52, + + /// DFS_FILE_SYSTEM parameter. + DFS_FILE_SYSTEM = 53, + + /// DFS_VOLUME parameter. + DFS_VOLUME = 54, + + /// SERENUM parameter. + SERENUM = 55, + + /// TERMSRV parameter. + TERMSRV = 56, + + /// KSEC parameter. + KSEC = 57, + + /// FIPS parameter. + FIPS = 58, + + /// INFINIBAND parameter. + INFINIBAND = 59, + + /// VMBUS parameter. + VMBUS = 62, + + /// CRYPT_PROVIDER parameter. + CRYPT_PROVIDER = 63, + + /// WPD parameter. + WPD = 64, + + /// BLUETOOTH parameter. + BLUETOOTH = 65, + + /// MT_COMPOSITE parameter. + MT_COMPOSITE = 66, + + /// MT_TRANSPORT parameter. + MT_TRANSPORT = 67, + + /// BIOMETRIC parameter. + BIOMETRIC = 68, + + /// PMI parameter. + PMI = 69, + + /// EHSTOR parameter. + EHSTOR = 70, + + /// DEVAPI parameter. + DEVAPI = 71, + + /// GPIO parameter. + GPIO = 72, + + /// USBEX parameter. + USBEX = 73, + + /// CONSOLE parameter. + CONSOLE = 80, + + /// NFP parameter. + NFP = 81, + + /// SYSENV parameter. + SYSENV = 82, + + /// MASS_STORAGE parameter. + VOLUME = 86 + } + } +} diff --git a/AlphaFS/Device/Native Other/IoControlCode.cs b/AlphaFS/Device/Native Other/IoControlCode.cs index 27d1516a6..30ce68cbb 100644 --- a/AlphaFS/Device/Native Other/IoControlCode.cs +++ b/AlphaFS/Device/Native Other/IoControlCode.cs @@ -30,45 +30,45 @@ internal static partial class NativeMethods internal enum IoControlCode : uint { /// Retrieves the physical location of a specified volume on one or more disks. - IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (DEVICE_TYPE.FILE_DEVICE_VOLUME << 16) | (0 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = (FILE_DEVICE.VOLUME << 16) | (0 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// Return properties of a storage device or adapter. The request indicates the kind of information to retrieve, such as inquiry data for a device or capabilities and limitations of an adapter. - IOCTL_STORAGE_QUERY_PROPERTY = (DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x500 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_STORAGE_QUERY_PROPERTY = (FILE_DEVICE.MASS_STORAGE << 16) | (0x500 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), - #region FILE_DEVICE_MASS_STORAGE + #region MASS_STORAGE ///// Determines whether the media has changed on a removable-media device that the caller has opened for read or write access. If read or write access to the device is not necessary, the caller can improve performance by opening the device with FILE_READ_ATTRIBUTES and issuing anIOCTL_STORAGE_CHECK_VERIFY2 request instead. - //IOCTL_STORAGE_CHECK_VERIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0200 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_STORAGE_CHECK_VERIFY = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0200 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Determines whether the media has changed on a removable-media device - the caller has opened with FILE_READ_ATTRIBUTES. Because no file system is mounted when a device is opened in this way, this request can be processed much more quickly than an IOCTL_STORAGE_CHECK_VERIFY request. - //IOCTL_STORAGE_CHECK_VERIFY2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0200 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), // FileAccess.Any + //IOCTL_STORAGE_CHECK_VERIFY2 = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0200 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), // FileAccess.Any ///// Locks the device to prevent removal of the media. If the driver can prevent the media from being removed while the drive is in use, it disables or enables the mechanism that ejects media on a device - the caller has opened for read or write access. - //IOCTL_STORAGE_MEDIA_REMOVAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0201 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_STORAGE_MEDIA_REMOVAL = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0201 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Causes the device to eject the media if the device supports ejection capabilities. - //IOCTL_STORAGE_EJECT_MEDIA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0202 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_STORAGE_EJECT_MEDIA = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0202 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Causes media to be loaded in a device that the caller has opened for read or write access. If read or write access to the device is not necessary, the caller can improve performance by opening the device with FILE_READ_ATTRIBUTES and issuing an IOCTL_STORAGE_LOAD_MEDIA2 request instead. - //IOCTL_STORAGE_LOAD_MEDIA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0203 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_STORAGE_LOAD_MEDIA = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0203 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Causes media to be loaded in a device that the caller has opened with FILE_READ_ATTRIBUTES. Because no file system is mounted when a device is opened in this way, this request can be processed much more quickly than an IOCTL_STORAGE_LOAD_MEDIA request. - //IOCTL_STORAGE_LOAD_MEDIA2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0203 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_STORAGE_LOAD_MEDIA2 = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0203 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Claims a device for the exclusive use of the caller on a bus that supports multiple initiators and the concept of reserving a device, such as a SCSI bus. - //IOCTL_STORAGE_RESERVE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0204 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_STORAGE_RESERVE = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0204 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Releases a device previously reserved for the exclusive use of the caller on a bus that supports multiple initiators and the concept of reserving a device, such as a SCSI bus. - //IOCTL_STORAGE_RELEASE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0205 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_STORAGE_RELEASE = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0205 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// @@ -81,7 +81,7 @@ internal enum IoControlCode : uint ///// dynamically, that is, without requiring the machine to be rebooted. Such a driver is assumed to support devices connected on a dynamically ///// configurable I/O bus. ///// - //IOCTL_STORAGE_FIND_NEW_DEVICES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0206 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_STORAGE_FIND_NEW_DEVICES = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0206 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// @@ -91,7 +91,7 @@ internal enum IoControlCode : uint ///// Unlike IOCTL_STORAGE_MEDIA_REMOVAL, the driver tracks IOCTL_STORAGE_EJECTION_CONTROL requests by caller and ignores unlock requests for ///// which it has not received a lock request from the same caller, thereby preventing other callers from unlocking the drive. ///// - //IOCTL_STORAGE_EJECTION_CONTROL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0250 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_STORAGE_EJECTION_CONTROL = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0250 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -100,31 +100,31 @@ internal enum IoControlCode : uint ///// FILE_READ_ATTRIBUTES access and if the device has AutoPlay enabled in the registry. The caller must not open the device for read or write ///// access or the IOCTL operation will fail. This IOCTL has no effect on the AutoPlay setting in the registry. ///// - //IOCTL_STORAGE_MCN_CONTROL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0251 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_STORAGE_MCN_CONTROL = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0251 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Returns information about the geometry of floppy drives. - //IOCTL_STORAGE_GET_MEDIA_TYPES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0300 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_STORAGE_GET_MEDIA_TYPES = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0300 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Returns information about the types of media supported by a device. A storage class driver must handle this IOCTL to control devices to be accessed by the removable storage manager (RSM) either as stand-alone devices or as data transfer elements (drives) in a media library or changer device. - //IOCTL_STORAGE_GET_MEDIA_TYPES_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0301 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_STORAGE_GET_MEDIA_TYPES_EX = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0301 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Resets an I/O bus and, indirectly, each device on the bus. Resetting the bus clears all device reservations and transfer speed settings, which must then be renegotiated, making it a time-consuming operation that should be used very rarely. The caller requires only read access to issue a bus reset. //[Obsolete] - //IOCTL_STORAGE_RESET_BUS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0400 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_STORAGE_RESET_BUS = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0400 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// If possible, resets a non-SCSI storage device without affecting other devices on the bus. Device reset for SCSI devices is not supported. The caller requires only read access to issue a device reset and, to comply, the device must be capable of responding to I/O requests. If the device reset succeeds, pending I/O requests are canceled. //[Obsolete] - //IOCTL_STORAGE_RESET_DEVICE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0401 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_STORAGE_RESET_DEVICE = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0401 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), - /// Returns a STORAGE_DEVICE_NUMBER structure that contains the FILE_DEVICE_XXX type, device number, and, for a partitionable device, + /// Returns a STORAGE_DEVICE_NUMBER structure that contains the XXX type, device number, and, for a partitionable device, /// the partition number assigned to a device by the driver when the device is started. This request is usually issued by a fault-tolerant disk driver. /// - IOCTL_STORAGE_GET_DEVICE_NUMBER = (DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0420 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_STORAGE_GET_DEVICE_NUMBER = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0420 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -132,99 +132,99 @@ internal enum IoControlCode : uint ///// If the device supports prediction failure, the disk class driver queries the device for failure prediction status and reports the results. If the disk class driver assigns a nonzero value to the PredictFailure member of STORAGE_PREDICT_FAILURE in the output buffer at Irp->AssociatedIrp.SystemBuffer, the disk has bad sectors and is predicting a failure. The storage stack returns 512 bytes of vendor-specific information about the failure prediction in the VendorSpecific member of STORAGE_PREDICT_FAILURE. ///// If the PredictFailure member contains a value of zero, the disk is not predicting a failure. ///// - //IOCTL_STORAGE_PREDICT_FAILURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE << 16) | (0x0440 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_STORAGE_PREDICT_FAILURE = (FILE_DEVICE.MASS_STORAGE << 16) | (0x0440 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), - #endregion // FILE_DEVICE_MASS_STORAGE + #endregion // MASS_STORAGE - #region FILE_DEVICE_DISK + #region DISK /// Returns information about the physical disk's geometry (media type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector). /// IOCTL_DISK_GET_DRIVE_GEOMETRY_EX can retrieve information from both Master Boot Record (MBR) and GUID Partition Table (GPT)-type partitioned media. /// - IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0028 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = (FILE_DEVICE.DISK << 16) | (0x0028 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///////// Returns information about the type, size, and nature of a disk partition. (Floppy drivers need not handle this request.) - //IOCTL_DISK_GET_PARTITION_INFO_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0012 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_DISK_GET_PARTITION_INFO_EX = (FILE_DEVICE.DISK << 16) | (0x0012 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Changes the partition type of the specified disk partition. (Floppy drivers need not handle this request.) - //IOCTL_DISK_SET_PARTITION_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0002 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_DISK_SET_PARTITION_INFO = (FILE_DEVICE.DISK << 16) | (0x0002 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), /// Contains extended information about a drive's partitions. - IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0014 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + IOCTL_DISK_GET_DRIVE_LAYOUT_EX = (FILE_DEVICE.DISK << 16) | (0x0014 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Repartitions a disk as specified. (Floppy drivers need not handle this request.) - //IOCTL_DISK_SET_DRIVE_LAYOUT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0004 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_DISK_SET_DRIVE_LAYOUT = (FILE_DEVICE.DISK << 16) | (0x0004 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Performs a logical format of a specified extent on a disk. - //IOCTL_DISK_VERIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0005 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_DISK_VERIFY = (FILE_DEVICE.DISK << 16) | (0x0005 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Formats the specified set of contiguous tracks on the disk. - //IOCTL_DISK_FORMAT_TRACKS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0006 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_DISK_FORMAT_TRACKS = (FILE_DEVICE.DISK << 16) | (0x0006 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Maps defective blocks to new location on disk. This request instructs the device to reassign the bad block address to a good block from its spare-block pool. - //IOCTL_DISK_REASSIGN_BLOCKS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0007 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_DISK_REASSIGN_BLOCKS = (FILE_DEVICE.DISK << 16) | (0x0007 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Increments a reference counter that enables the collection of disk performance statistics, such as the numbers of bytes read and written since the driver last processed this request, for a corresponding disk monitoring application. In Microsoft Windows 2000 this IOCTL is handled by the filter driver diskperf. In Windows XP and later operating systems, the partition manager handles this request for disks and ftdisk.sys and dmio.sys handle this request for volumes. - //IOCTL_DISK_PERFORMANCE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0008 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_DISK_PERFORMANCE = (FILE_DEVICE.DISK << 16) | (0x0008 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Determines whether a disk is writable. - //IOCTL_DISK_IS_WRITABLE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0009 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_DISK_IS_WRITABLE = (FILE_DEVICE.DISK << 16) | (0x0009 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// - //IOCTL_DISK_LOGGING = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x000a << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_DISK_LOGGING = (FILE_DEVICE.DISK << 16) | (0x000a << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Is similar to IOCTL_DISK_FORMAT_TRACKS, except that it allows the caller to specify several more parameters. The additional extended parameters are the format gap length, the number of sectors per track, and an array whose element size is equal to the number of sectors per track. This array represents the track layout. - //IOCTL_DISK_FORMAT_TRACKS_EX = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x000b << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_DISK_FORMAT_TRACKS_EX = (FILE_DEVICE.DISK << 16) | (0x000b << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Do not use //[Obsolete] - //IOCTL_DISK_HISTOGRAM_STRUCTURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000c << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_DISK_HISTOGRAM_STRUCTURE = (FILE_DEVICE.DISK <<16) | (0x000c << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Do not use //[Obsolete] - //IOCTL_DISK_HISTOGRAM_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000d << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_DISK_HISTOGRAM_DATA = (FILE_DEVICE.DISK <<16) | (0x000d << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Do not use //[Obsolete] - //IOCTL_DISK_HISTOGRAM_RESET = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000e << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_DISK_HISTOGRAM_RESET = (FILE_DEVICE.DISK <<16) | (0x000e << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Do not use //[Obsolete] - //IOCTL_DISK_REQUEST_STRUCTURE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x000f << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_DISK_REQUEST_STRUCTURE = (FILE_DEVICE.DISK <<16) | (0x000f << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Do not use //[Obsolete] - //IOCTL_DISK_REQUEST_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x0010 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_DISK_REQUEST_DATA = (FILE_DEVICE.DISK <<16) | (0x0010 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Do not use //[Obsolete] - //IOCTL_DISK_CONTROLLER_NUMBER = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK <<16) | (0x0011 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_DISK_CONTROLLER_NUMBER = (FILE_DEVICE.DISK <<16) | (0x0011 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), /// Retrieves the length of the specified disk, volume, or partition. /// This operation should be used instead of IOCTL_DISK_GET_PARTITION_INFO_EX for volumes that do not have partition info, such as partition type or number of hidden sectors. - IOCTL_DISK_GET_LENGTH_INFO = (DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0017 << 2) | IoControlMethod.Buffered | (FileAccess.Read << 14), + IOCTL_DISK_GET_LENGTH_INFO = (FILE_DEVICE.DISK << 16) | (0x0017 << 2) | IoControlMethod.Buffered | (FileAccess.Read << 14), ///// Returns version information, a capabilities mask, and a bitmask for the device. This IOCTL must be handled by drivers that support Self-Monitoring Analysis and Reporting Technology (SMART). - //SMART_GET_VERSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0020 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //SMART_GET_VERSION = (FILE_DEVICE.DISK << 16) | (0x0020 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// @@ -237,141 +237,141 @@ internal enum IoControlCode : uint ///// * Write to SMART log ///// This IOCTL must be handled by drivers that support SMART. ///// - //SMART_SEND_DRIVE_COMMAND = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0021 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //SMART_SEND_DRIVE_COMMAND = (FILE_DEVICE.DISK << 16) | (0x0021 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Returns the ATA-2 identify data, the Self-Monitoring Analysis and Reporting Technology (SMART) thresholds, or the SMART attributes for the device. This IOCTL must be handled by drivers that support SMART. - //SMART_RCV_DRIVE_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0022 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //SMART_RCV_DRIVE_DATA = (FILE_DEVICE.DISK << 16) | (0x0022 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Updates device extension with drive size information for current media. - //IOCTL_DISK_UPDATE_DRIVE_SIZE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0032 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_DISK_UPDATE_DRIVE_SIZE = (FILE_DEVICE.DISK << 16) | (0x0032 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Increases the size of an existing partition. It is used in conjunction with IOCTL_DISK_UPDATE_DRIVE_SIZE to extend a disk, so that it will contain a new free space area, and then to extend an existing partition on the disk into the newly attached free space. It takes a DISK_GROW_PARTITION structure as the only parameter. For this operation to work, the space after the specified partition must be free. A partition cannot be extended over another existing partition. - //IOCTL_DISK_GROW_PARTITION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0034 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_DISK_GROW_PARTITION = (FILE_DEVICE.DISK << 16) | (0x0034 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Returns disk cache configuration data. - //IOCTL_DISK_GET_CACHE_INFORMATION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0035 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_DISK_GET_CACHE_INFORMATION = (FILE_DEVICE.DISK << 16) | (0x0035 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Sets disk cache configuration data. - //IOCTL_DISK_SET_CACHE_INFORMATION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0036 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_DISK_SET_CACHE_INFORMATION = (FILE_DEVICE.DISK << 16) | (0x0036 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Removes partition information from the disk. If the partition style of the disk is Master Boot Record (MBR), sector 0 of the disk is wiped clean except for the bootstrap code. All signatures, such as the AA55 boot signature and the NTFT disk signature, will be removed. If the partition style of the disk is GUID Partition Table (GPT), the primary partition table header in sector 1 and the backup partition table in the last sector of the disk are wiped clean. This operation can be used to generate so-called "superfloppies" that contain a file system starting at the first sector of the disk rather than in a partition on the disk. - //IOCTL_DISK_DELETE_DRIVE_LAYOUT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0040 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_DISK_DELETE_DRIVE_LAYOUT = (FILE_DEVICE.DISK << 16) | (0x0040 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// - //DiskSenseDevice = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x00f8 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //DiskSenseDevice = (FILE_DEVICE.DISK << 16) | (0x00f8 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// In Microsoft Windows 2000 and later operating systems, this IOCTL is replaced by IOCTL_STORAGE_CHECK_VERIFY. The only difference between the two IOCTLs is the base value. - //IOCTL_DISK_CHECK_VERIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0200 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_DISK_CHECK_VERIFY = (FILE_DEVICE.DISK << 16) | (0x0200 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// In Microsoft Windows 2000 and later operating systems, this IOCTL is replaced by IOCTL_STORAGE_FIND_NEW_DEVICES. The only difference between the two IOCTLs is the base value. - //IOCTL_DISK_FIND_NEW_DEVICES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0206 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_DISK_FIND_NEW_DEVICES = (FILE_DEVICE.DISK << 16) | (0x0206 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// In Microsoft Windows 2000 and later operating systems, this IOCTL is replaced by IOCTL_STORAGE_GET_MEDIA_TYPES. The only difference between the two IOCTLs is the base value. - //IOCTL_DISK_GET_MEDIA_TYPES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_DISK << 16) | (0x0300 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //IOCTL_DISK_GET_MEDIA_TYPES = (FILE_DEVICE.DISK << 16) | (0x0300 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), - #endregion // FILE_DEVICE_DISK + #endregion // DISK - #region FILE_DEVICE_CHANGER + #region CHANGER ///// Retrieves the parameters of the specified device. - //IOCTL_CHANGER_GET_PARAMETERS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0000 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_CHANGER_GET_PARAMETERS = (FILE_DEVICE.CHANGER << 16) | (0x0000 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Retrieves the current status of the specified device. - //IOCTL_CHANGER_GET_STATUS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0001 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_CHANGER_GET_STATUS = (FILE_DEVICE.CHANGER << 16) | (0x0001 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Retrieves the product data for the specified device. - //IOCTL_CHANGER_GET_PRODUCT_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0002 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_CHANGER_GET_PRODUCT_DATA = (FILE_DEVICE.CHANGER << 16) | (0x0002 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Sets the state of the device's insert/eject port, door, or keypad. - //IOCTL_CHANGER_SET_ACCESS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0004 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_CHANGER_SET_ACCESS = (FILE_DEVICE.CHANGER << 16) | (0x0004 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Retrieves the status of all elements or a specified number of elements of a particular type. - //IOCTL_CHANGER_GET_ELEMENT_STATUS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0005 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_CHANGER_GET_ELEMENT_STATUS = (FILE_DEVICE.CHANGER << 16) | (0x0005 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// Initializes the status of all elements or the specified elements of a particular type. - //IOCTL_CHANGER_INITIALIZE_ELEMENT_STATUS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0006 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_CHANGER_INITIALIZE_ELEMENT_STATUS = (FILE_DEVICE.CHANGER << 16) | (0x0006 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Sets the changer's robotic transport mechanism to the specified element address. This optimizes moving or exchanging media by positioning the transport beforehand. - //IOCTL_CHANGER_SET_POSITION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0007 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_CHANGER_SET_POSITION = (FILE_DEVICE.CHANGER << 16) | (0x0007 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Moves a piece of media from a source element to one destination, and the piece of media originally in the first destination to a second destination. - //IOCTL_CHANGER_EXCHANGE_MEDIUM = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0008 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_CHANGER_EXCHANGE_MEDIUM = (FILE_DEVICE.CHANGER << 16) | (0x0008 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Moves a piece of media to a destination. - //IOCTL_CHANGER_MOVE_MEDIUM = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x0009 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_CHANGER_MOVE_MEDIUM = (FILE_DEVICE.CHANGER << 16) | (0x0009 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Physically recalibrates a transport element. Recalibration may involve returning the transport to its home position. - //IOCTL_CHANGER_REINITIALIZE_TRANSPORT = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x000A << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //IOCTL_CHANGER_REINITIALIZE_TRANSPORT = (FILE_DEVICE.CHANGER << 16) | (0x000A << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// Retrieves the volume tag information for the specified elements. - //IOCTL_CHANGER_QUERY_VOLUME_TAGS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_CHANGER << 16) | (0x000B << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //IOCTL_CHANGER_QUERY_VOLUME_TAGS = (FILE_DEVICE.CHANGER << 16) | (0x000B << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), - #endregion // FILE_DEVICE_CHANGER + #endregion // CHANGER - #region FILE_DEVICE_FILE_SYSTEM + #region FILE_SYSTEM ///// Requests a level 1 opportunistic lock on a file. - //FSCTL_REQUEST_OPLOCK_LEVEL_1 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (0 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_REQUEST_OPLOCK_LEVEL_1 = (FILE_DEVICE.FILE_SYSTEM << 16) | (0 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Requests a level 2 opportunistic lock on a file. - //FSCTL_REQUEST_OPLOCK_LEVEL_2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (1 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_REQUEST_OPLOCK_LEVEL_2 = (FILE_DEVICE.FILE_SYSTEM << 16) | (1 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Requests a batch opportunistic lock on a file. - //FSCTL_REQUEST_BATCH_OPLOCK = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (2 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_REQUEST_BATCH_OPLOCK = (FILE_DEVICE.FILE_SYSTEM << 16) | (2 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Responds to notification that an exclusive opportunistic lock on a file is about to be broken. Use this operation to indicate that the file should receive a level 2 opportunistic lock. - //FSCTL_OPLOCK_BREAK_ACKNOWLEDGE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (3 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_OPLOCK_BREAK_ACKNOWLEDGE = (FILE_DEVICE.FILE_SYSTEM << 16) | (3 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Notifies a server that a client application is ready to close a file. Use this operation after notification that an opportunistic lock on a file is ready to be broken. - //FSCTL_OPBATCH_ACK_CLOSE_PENDING = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (4 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_OPBATCH_ACK_CLOSE_PENDING = (FILE_DEVICE.FILE_SYSTEM << 16) | (4 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// ///// Enables the calling application to wait for completion of an opportunistic lock break. ///// This operation is not useful to application developers and is documented here only for completeness. CreateFile handles the problem that this operation was designed to handle. ///// - //FSCTL_OPLOCK_BREAK_NOTIFY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (5 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_OPLOCK_BREAK_NOTIFY = (FILE_DEVICE.FILE_SYSTEM << 16) | (5 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Locks a volume if it is not in use. A locked volume can be accessed only through handles to the file object (*hDevice) that locks the volume. For more information, see the Remarks section. - //FSCTL_LOCK_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (6 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_LOCK_VOLUME = (FILE_DEVICE.FILE_SYSTEM << 16) | (6 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Unlocks a volume. - //FSCTL_UNLOCK_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (7 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_UNLOCK_VOLUME = (FILE_DEVICE.FILE_SYSTEM << 16) | (7 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Dismounts a volume regardless of whether or not the volume is currently in use. For more information, see the Remarks section. - //FSCTL_DISMOUNT_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (8 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_DISMOUNT_VOLUME = (FILE_DEVICE.FILE_SYSTEM << 16) | (8 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Determines whether the specified volume is mounted, or if the specified file or directory is on a mounted volume. - //FSCTL_IS_VOLUME_MOUNTED = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (10 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_IS_VOLUME_MOUNTED = (FILE_DEVICE.FILE_SYSTEM << 16) | (10 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -382,11 +382,11 @@ internal enum IoControlCode : uint ///// This control code is not supported with fast FAT file systems, and it is not a meaningful operation in NTFS or UDFS. NTFS and UDFS support ///// such a wide variety of codesets that any string is potentially a valid pathname. ///// - //FSCTL_IS_PATHNAME_VALID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (11 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_IS_PATHNAME_VALID = (FILE_DEVICE.FILE_SYSTEM << 16) | (11 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// The FSCTL_MARK_VOLUME_DIRTY control code marks a specified volume as dirty, which triggers Autochk.exe to run on the volume during the next system restart. - //FSCTL_MARK_VOLUME_DIRTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (12 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_MARK_VOLUME_DIRTY = (FILE_DEVICE.FILE_SYSTEM << 16) | (12 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -398,15 +398,15 @@ internal enum IoControlCode : uint ///// LCN that refer more directly to the underlying physical storage. You must not use FSCTL_QUERY_RETRIEVAL_POINTERS with files other than ///// the page file, because they might reside on volumes, such as mirrored volumes, that have one-to-many mappings of VCNs to LCNs. ///// - //FSCTL_QUERY_RETRIEVAL_POINTERS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (14 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_QUERY_RETRIEVAL_POINTERS = (FILE_DEVICE.FILE_SYSTEM << 16) | (14 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Retrieves the current compression state of a file or directory on a volume whose file system supports per-stream compression. - //FSCTL_GET_COMPRESSION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (15 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_GET_COMPRESSION = (FILE_DEVICE.FILE_SYSTEM << 16) | (15 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), /// Sets the compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. You can use FSCTL_SET_COMPRESSION to compress or uncompress a file or directory on such a volume. - FSCTL_SET_COMPRESSION = (DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (16 << 2) | IoControlMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + FSCTL_SET_COMPRESSION = (FILE_DEVICE.FILE_SYSTEM << 16) | (16 << 2) | IoControlMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// @@ -416,7 +416,7 @@ internal enum IoControlCode : uint ///// directory or volume handle. File system redirectors that access files on remote machines treat this control code as a no-op. ///// Only kernel-level components can use this filesystem control code. ///// - //FSCTL_MARK_AS_SYSTEM_HIVE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (19 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_MARK_AS_SYSTEM_HIVE = (FILE_DEVICE.FILE_SYSTEM << 16) | (19 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// @@ -429,7 +429,7 @@ internal enum IoControlCode : uint ///// For more information about opportunistic locking and about the FSCTL_OPLOCK_BREAK_ACK_NO_2 control code, see the Microsoft Windows SDK ///// documentation. ///// - //FSCTL_OPLOCK_BREAK_ACK_NO_2 = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (20 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_OPLOCK_BREAK_ACK_NO_2 = (FILE_DEVICE.FILE_SYSTEM << 16) | (20 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -438,11 +438,11 @@ internal enum IoControlCode : uint ///// To perform this operation, minifilter drivers call FltFsControlFile, and file systems, redirectors, and legacy file system filter drivers ///// call ZwFsControlFile, using the following parameters. ///// - //FSCTL_INVALIDATE_VOLUMES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (21 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_INVALIDATE_VOLUMES = (FILE_DEVICE.FILE_SYSTEM << 16) | (21 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// - //FSCTL_QUERY_FAT_BPB = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (22 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_QUERY_FAT_BPB = (FILE_DEVICE.FILE_SYSTEM << 16) | (22 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -452,31 +452,31 @@ internal enum IoControlCode : uint ///// For more information about opportunistic locking and about the FSCTL_REQUEST_FILTER_OPLOCK control code, see the Microsoft Windows SDK ///// documentation. ///// - //FSCTL_REQUEST_FILTER_OPLOCK = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (23 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_REQUEST_FILTER_OPLOCK = (FILE_DEVICE.FILE_SYSTEM << 16) | (23 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves the information from various file system performance counters. - //FSCTL_FILESYSTEM_GET_STATISTICS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (24 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_FILESYSTEM_GET_STATISTICS = (FILE_DEVICE.FILE_SYSTEM << 16) | (24 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves information about the specified NTFS file system volume. - //FSCTL_GET_NTFS_VOLUME_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (25 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_GET_NTFS_VOLUME_DATA = (FILE_DEVICE.FILE_SYSTEM << 16) | (25 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves the first file record that is in use and is of a lesser than or equal ordinal value to the requested file reference number. - //FSCTL_GET_NTFS_FILE_RECORD = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (26 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_GET_NTFS_FILE_RECORD = (FILE_DEVICE.FILE_SYSTEM << 16) | (26 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves a bitmap of occupied and available clusters on a volume. - //FSCTL_GET_VOLUME_BITMAP = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (27 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_GET_VOLUME_BITMAP = (FILE_DEVICE.FILE_SYSTEM << 16) | (27 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Given a file handle, retrieves a data structure that describes the allocation and location on disk of a specific file, or, given a volume handle, the locations of bad clusters on a volume. - //FSCTL_GET_RETRIEVAL_POINTERS = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (28 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_GET_RETRIEVAL_POINTERS = (FILE_DEVICE.FILE_SYSTEM << 16) | (28 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Relocates one or more virtual clusters of a file from one logical cluster to another within the same volume. This operation is used during defragmentation. - //FSCTL_MOVE_FILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (29 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_MOVE_FILE = (FILE_DEVICE.FILE_SYSTEM << 16) | (29 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -485,43 +485,43 @@ internal enum IoControlCode : uint ///// To perform this operation, minifilter drivers call FltFsControlFile with the following parameters, and file systems, redirectors, and ///// legacy file system filter drivers call ZwFsControlFile with the following parameters. ///// - //FSCTL_IS_VOLUME_DIRTY = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (30 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_IS_VOLUME_DIRTY = (FILE_DEVICE.FILE_SYSTEM << 16) | (30 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// - //FsctlGetHfsInformation = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (31 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FsctlGetHfsInformation = (FILE_DEVICE.FILE_SYSTEM << 16) | (31 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Signals the file system driver not to perform any I/O boundary checks on partition read or write calls. Instead, boundary checks are performed by the device driver. - //FSCTL_ALLOW_EXTENDED_DASD_IO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (32 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_ALLOW_EXTENDED_DASD_IO = (FILE_DEVICE.FILE_SYSTEM << 16) | (32 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlReadPropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (33 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FsctlReadPropertyData = (FILE_DEVICE.FILE_SYSTEM << 16) | (33 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlWritePropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (34 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FsctlWritePropertyData = (FILE_DEVICE.FILE_SYSTEM << 16) | (34 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlDumpPropertyData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (37 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FsctlDumpPropertyData = (FILE_DEVICE.FILE_SYSTEM << 16) | (37 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Searches a directory for a file whose creator owner matches the specified SID. - //FSCTL_FIND_FILES_BY_SID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (35 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_FIND_FILES_BY_SID = (FILE_DEVICE.FILE_SYSTEM << 16) | (35 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Sets the object identifier for the specified file or directory. - //FSCTL_SET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (38 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_SET_OBJECT_ID = (FILE_DEVICE.FILE_SYSTEM << 16) | (38 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves the object identifier for the specified file or directory. - //FSCTL_GET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (39 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_GET_OBJECT_ID = (FILE_DEVICE.FILE_SYSTEM << 16) | (39 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Removes the object identifier from a specified file or directory. The underlying object is not deleted. - //FSCTL_DELETE_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (40 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_DELETE_OBJECT_ID = (FILE_DEVICE.FILE_SYSTEM << 16) | (40 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), /// @@ -530,7 +530,7 @@ internal enum IoControlCode : uint /// Minifilters should use FltTagFile instead of FSCTL_SET_REPARSE_POINT to set a reparse point. /// For more information about reparse points and the FSCTL_SET_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_SET_REPARSE_POINT = (DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (41 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + FSCTL_SET_REPARSE_POINT = (FILE_DEVICE.FILE_SYSTEM << 16) | (41 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// @@ -538,7 +538,7 @@ internal enum IoControlCode : uint /// To perform this operation, call FltFsControlFile or ZwFsControlFile with the following parameters. /// For more information about reparse points and the FSCTL_GET_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_GET_REPARSE_POINT = (DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (42 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + FSCTL_GET_REPARSE_POINT = (FILE_DEVICE.FILE_SYSTEM << 16) | (42 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), /// @@ -548,92 +548,92 @@ internal enum IoControlCode : uint /// Minifilters should use FltUntagFile instead of FSCTL_DELETE_REPARSE_POINT to delete a reparse point. /// For more information about reparse points and the FSCTL_DELETE_REPARSE_POINT control code, see the Microsoft Windows SDK documentation. /// - FSCTL_DELETE_REPARSE_POINT = (DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (43 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), + FSCTL_DELETE_REPARSE_POINT = (FILE_DEVICE.FILE_SYSTEM << 16) | (43 << 2) | IoControlMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// ///// Enumerates the update sequence number (USN) data between two specified boundaries to obtain master file table (MFT) records. ///// - //FSCTL_ENUM_USN_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (44 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_ENUM_USN_DATA = (FILE_DEVICE.FILE_SYSTEM << 16) | (44 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// The FSCTL_SECURITY_ID_CHECK control code performs a bulk security check of the security identifiers exposed through USN records. - //FSCTL_SECURITY_ID_CHECK = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (45 << 2) | IoMethod.Neither | (FileAccess.Read << 14), + //FSCTL_SECURITY_ID_CHECK = (FILE_DEVICE.FILE_SYSTEM << 16) | (45 << 2) | IoMethod.Neither | (FileAccess.Read << 14), ///// Retrieves the set of update sequence number (USN) change journal records between two specified USN values. - //FSCTL_READ_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (46 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_READ_USN_JOURNAL = (FILE_DEVICE.FILE_SYSTEM << 16) | (46 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Modifies user data associated with the object identifier for the specified file or directory. - //FSCTL_SET_OBJECT_ID_EXTENDED = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (47 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_SET_OBJECT_ID_EXTENDED = (FILE_DEVICE.FILE_SYSTEM << 16) | (47 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Retrieves the object identifier for the specified file or directory. If no object identifier exists, using FSCTL_CREATE_OR_GET_OBJECT_ID creates one. - //FSCTL_CREATE_OR_GET_OBJECT_ID = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (48 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_CREATE_OR_GET_OBJECT_ID = (FILE_DEVICE.FILE_SYSTEM << 16) | (48 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Marks the indicated file as sparse or not sparse. In a sparse file, large ranges of zeros may not require disk allocation. Space for nonzero data will be allocated as needed as the file is written. - //FSCTL_SET_SPARSE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (49 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_SET_SPARSE = (FILE_DEVICE.FILE_SYSTEM << 16) | (49 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Fills a specified range of a file with zeros (0). If the file is sparse or compressed, the NTFS file system may deallocate disk space in the file. This sets the range of bytes to zeros (0) without extending the file size. - //FSCTL_SET_ZERO_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (50 << 2) | IoMethod.Buffered | (FileAccess.Write << 14), + //FSCTL_SET_ZERO_DATA = (FILE_DEVICE.FILE_SYSTEM << 16) | (50 << 2) | IoMethod.Buffered | (FileAccess.Write << 14), ///// Scans a file or alternate stream looking for ranges that may contain nonzero data. Only compressed or sparse files can have zeroed ranges known to the operating system. For other files, the output buffer will contain only a single entry that contains the starting point and the length requested. - //FSCTL_QUERY_ALLOCATED_RANGES = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (51 << 2) | IoMethod.Neither | (FileAccess.Read << 14), + //FSCTL_QUERY_ALLOCATED_RANGES = (FILE_DEVICE.FILE_SYSTEM << 16) | (51 << 2) | IoMethod.Neither | (FileAccess.Read << 14), ///// - //FsctlEnableUpgrade = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (52 << 2) | IoMethod.Buffered | (FileAccess.Write << 14), + //FsctlEnableUpgrade = (FILE_DEVICE.FILE_SYSTEM << 16) | (52 << 2) | IoMethod.Buffered | (FileAccess.Write << 14), ///// ///// The FSCTL_SET_ENCRYPTION request sets the encryption for the file or directory associated with the given handle. ///// The message contains an ENCRYPTION_BUFFER structure that indicates whether to encrypt/decrypt a file or an individual stream. ///// - //FSCTL_SET_ENCRYPTION = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (53 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_SET_ENCRYPTION = (FILE_DEVICE.FILE_SYSTEM << 16) | (53 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlEncryptionFsctlIo = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (54 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FsctlEncryptionFsctlIo = (FILE_DEVICE.FILE_SYSTEM << 16) | (54 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlWriteRawEncrypted = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (55 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FsctlWriteRawEncrypted = (FILE_DEVICE.FILE_SYSTEM << 16) | (55 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// - //FsctlReadRawEncrypted = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (56 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FsctlReadRawEncrypted = (FILE_DEVICE.FILE_SYSTEM << 16) | (56 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Creates an update sequence number (USN) change journal stream on a target volume, or modifies an existing change journal stream. - //FSCTL_CREATE_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (57 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_CREATE_USN_JOURNAL = (FILE_DEVICE.FILE_SYSTEM << 16) | (57 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Retrieves the update sequence number (USN) change-journal information for the specified file or directory. - //FSCTL_READ_FILE_USN_DATA = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (58 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_READ_FILE_USN_DATA = (FILE_DEVICE.FILE_SYSTEM << 16) | (58 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Generates a record in the update sequence number (USN) change journal stream for the input file. This record will have the USN_REASON_CLOSE flag. - //FSCTL_WRITE_USN_CLOSE_RECORD = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (59 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_WRITE_USN_CLOSE_RECORD = (FILE_DEVICE.FILE_SYSTEM << 16) | (59 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// Increases the size of a mounted volume. - //FSCTL_EXTEND_VOLUME = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (60 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_EXTEND_VOLUME = (FILE_DEVICE.FILE_SYSTEM << 16) | (60 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Queries for information on the current update sequence number (USN) change journal, its records, and its capacity. - //FSCTL_QUERY_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (61 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_QUERY_USN_JOURNAL = (FILE_DEVICE.FILE_SYSTEM << 16) | (61 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Deletes the update sequence number (USN) change journal on a volume, or waits for notification of change journal deletion. - //FSCTL_DELETE_USN_JOURNAL = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (62 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_DELETE_USN_JOURNAL = (FILE_DEVICE.FILE_SYSTEM << 16) | (62 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// Marks a specified file or directory and its change journal record with information about changes to that file or directory. - //FSCTL_MARK_HANDLE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (63 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_MARK_HANDLE = (FILE_DEVICE.FILE_SYSTEM << 16) | (63 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// @@ -645,37 +645,37 @@ internal enum IoControlCode : uint ///// This FSCTL can be issued against either a file or directory handle. The source and destination files MUST reside on the volume ///// associated with the given handle. ///// - //FSCTL_SIS_COPYFILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (64 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_SIS_COPYFILE = (FILE_DEVICE.FILE_SYSTEM << 16) | (64 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), ///// - //FsctlSisLinkFiles = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (65 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //FsctlSisLinkFiles = (FILE_DEVICE.FILE_SYSTEM << 16) | (65 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// - //FsctlHsmMsg = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (66 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), + //FsctlHsmMsg = (FILE_DEVICE.FILE_SYSTEM << 16) | (66 << 2) | IoMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14), ///// - //FsctlNssControl = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (67 << 2) | IoMethod.Buffered | (FileAccess.Write << 14), + //FsctlNssControl = (FILE_DEVICE.FILE_SYSTEM << 16) | (67 << 2) | IoMethod.Buffered | (FileAccess.Write << 14), ///// - //FsctlNssRcontrol = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (70 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), + //FsctlNssRcontrol = (FILE_DEVICE.FILE_SYSTEM << 16) | (70 << 2) | IoMethod.Buffered | (FileAccess.Read << 14), ///// - //FsctlHsmData = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (68 << 2) | IoMethod.Neither | ((FileAccess.Read | FileAccess.Write) << 14), + //FsctlHsmData = (FILE_DEVICE.FILE_SYSTEM << 16) | (68 << 2) | IoMethod.Neither | ((FileAccess.Read | FileAccess.Write) << 14), ///// Recalls a file from storage media that Remote Storage manages, which is the hierarchical storage management software. - //FSCTL_RECALL_FILE = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (69 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), + //FSCTL_RECALL_FILE = (FILE_DEVICE.FILE_SYSTEM << 16) | (69 << 2) | IoMethod.Neither | (FILE_ANY_ACCESS << 14), ///// The FSCTL_GET_BOOT_AREA_INFO control code retrieves the locations of boot sectors for a volume. - //FSCTL_GET_BOOT_AREA_INFO = (STORAGE_DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM << 16) | (140 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), + //FSCTL_GET_BOOT_AREA_INFO = (FILE_DEVICE.FILE_SYSTEM << 16) | (140 << 2) | IoMethod.Buffered | (FILE_ANY_ACCESS << 14), - #endregion // FILE_DEVICE_FILE_SYSTEM + #endregion // FILE_SYSTEM } } } diff --git a/AlphaFS/Device/Native Other/STORAGE_DEVICE_NUMBER.cs b/AlphaFS/Device/Native Other/STORAGE_DEVICE_NUMBER.cs index 175246d62..0a4b59065 100644 --- a/AlphaFS/Device/Native Other/STORAGE_DEVICE_NUMBER.cs +++ b/AlphaFS/Device/Native Other/STORAGE_DEVICE_NUMBER.cs @@ -33,8 +33,8 @@ internal static partial class NativeMethods [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct STORAGE_DEVICE_NUMBER { - /// Specifies one of the system-defined FILE_DEVICE_XXX constants indicating the type of device (such as FILE_DEVICE_DISK, FILE_DEVICE_KEYBOARD, and so forth) or a vendor-defined value for a new type of device. - [MarshalAs(UnmanagedType.U4)] internal readonly DeviceType DeviceType; + /// Specifies one of the system-defined XXX constants indicating the type of device (such as DISK, KEYBOARD, and so forth) or a vendor-defined value for a new type of device. + [MarshalAs(UnmanagedType.U4)] internal readonly FILE_DEVICE DeviceType; /// Indicates the number of this device. This value is set to 0xFFFFFFFF (-1) for the disks that represent the physical paths of an MPIO disk. [MarshalAs(UnmanagedType.U4)] diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs index cdb071e43..bf9b5c951 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs @@ -35,6 +35,7 @@ private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, { var isElevated = ProcessContext.IsElevatedProcess; var getByDeviceNumber = deviceNumber > -1; + string physicalDriveNumberPath = null; bool isDrive; bool isVolume; @@ -47,8 +48,7 @@ private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, localDevicePath = FileSystemHelper.GetLocalDevicePath(localDevicePath); - string physicalDriveNumberPath = null; - + // The StorageDeviceInfo is always needed as it contains the device- and partition number. StorageDeviceInfo = storageDeviceInfo ?? Local.GetStorageDeviceInfo(isElevated, isDevice, deviceNumber, localDevicePath, out physicalDriveNumberPath); @@ -68,15 +68,11 @@ private void CreatePhysicalDiskInfoInstance(int deviceNumber, string devicePath, localDevicePath = FileSystemHelper.GetValidatedDevicePath(physicalDriveNumberPath ?? localDevicePath, out isDrive, out isVolume, out isDevice); - AddDeviceInfoData(isElevated, deviceNumber, localDevicePath); - - UpdateDeviceInfodata(isElevated, isDevice, localDevicePath); - - PopulatePhysicalDisk(isElevated); + AddDeviceInfoData(isElevated, isDevice, deviceNumber, localDevicePath); } - private void AddDeviceInfoData(bool isElevated, int deviceNumber, string localDevicePath) + private void AddDeviceInfoData(bool isElevated, bool isDevice, int deviceNumber, string localDevicePath) { DosDeviceName = Volume.QueryDosDevice(Path.GetRegularPathCore(localDevicePath, GetFullPathOptions.None, false)); @@ -87,6 +83,11 @@ private void AddDeviceInfoData(bool isElevated, int deviceNumber, string localDe StoragePartitionInfo = Local.GetStoragePartitionInfo(safeFileHandle, deviceNumber, localDevicePath); } + + + UpdateDevicePartitionData(isElevated, isDevice, localDevicePath); + + PopulatePhysicalDisk(isElevated); } @@ -161,12 +162,12 @@ private bool SetDeviceInfoDataFromDeviceNumber(bool isElevated, int deviceNumber [SecurityCritical] - private void UpdateDeviceInfodata(bool isElevated, bool isDevice, string localDevicePath) + private void UpdateDevicePartitionData(bool isElevated, bool isDevice, string localDevicePath) { if (StoragePartitionInfo.OnDynamicDisk) { - // At this point, PartitionNumber is 0 which points to the device. - // Get the user data partition information. + // At this point, PartitionNumber = 0 which points to the device. + // Get the user data partition; the partition that normally occupies most of the disk space. foreach (var partition in StoragePartitionInfo.GptPartitionInfo) { diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs index c4e9e36c1..0f66d1721 100644 --- a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs +++ b/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs @@ -131,6 +131,14 @@ public string PhysicalDeviceObjectName } + /// Retrieves the current power state of the device. + /// This property is not cached. + public bool PowerStateEnabled + { + get { return !Utils.IsNullOrWhiteSpace(DevicePath) && Local.GetDevicePowerState(DevicePath); } + } + + /// The storage device adapter information. public StorageAdapterInfo StorageAdapterInfo { get; private set; } diff --git a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs index 0d9906335..02b61caa3 100644 --- a/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageAdapterInfo.cs @@ -49,7 +49,7 @@ internal StorageAdapterInfo(int diskNumber, NativeMethods.STORAGE_ADAPTER_DESCRI BusType = (StorageBusType) adapter.BusType; AcceleratedTransfer = adapter.AcceleratedTransfer; - + AdapterScansDown = adapter.AdapterScansDown; AdapterUsesPio = adapter.AdapterUsesPio; diff --git a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs index 87451f743..10f0c06a9 100644 --- a/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs +++ b/AlphaFS/Device/Storage/Device.StorageDeviceInfo.cs @@ -42,7 +42,7 @@ public sealed class StorageDeviceInfo /// [AlphaFS] Initializes an empty StorageDeviceInfo instance. public StorageDeviceInfo() { - DeviceType = Device.DeviceType.Unknown; + DeviceType = DeviceType.Unknown; DeviceNumber = -1; @@ -52,7 +52,7 @@ public StorageDeviceInfo() internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() { - DeviceType = device.DeviceType; + DeviceType = (DeviceType) device.DeviceType; DeviceNumber = device.DeviceNumber; @@ -112,8 +112,6 @@ internal StorageDeviceInfo(NativeMethods.STORAGE_DEVICE_NUMBER device) : this() public string SerialNumber { get; internal set; } - // /// The total size of the physical disk or 0 if the process is not elevated or the device is a controller. - /// The total size of the physical disk. public long TotalSize { get; internal set; } diff --git a/AlphaFS/Device/Structures, Enumerations/DeviceType.cs b/AlphaFS/Device/Structures, Enumerations/DeviceType.cs index b2a3a22a6..2de95cf40 100644 --- a/AlphaFS/Device/Structures, Enumerations/DeviceType.cs +++ b/AlphaFS/Device/Structures, Enumerations/DeviceType.cs @@ -31,250 +31,250 @@ public enum DeviceType /// Indicates an unknown storage device type. None = 0, - /// FILE_DEVICE_BEEP parameter. - Beep = NativeMethods.DEVICE_TYPE.FILE_DEVICE_BEEP, + /// BEEP parameter. + Beep = NativeMethods.FILE_DEVICE.BEEP, - /// FILE_DEVICE_CD_ROM parameter. - CDRom = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CD_ROM, // .NET DriveInfo.DriveType property also uses "CDRom" instead of "CdRom". + /// CD_ROM parameter. + CDRom = NativeMethods.FILE_DEVICE.CD_ROM, // .NET DriveInfo.DriveType property also uses "CDRom" instead of "CdRom". - /// FILE_DEVICE_CD_ROM_FILE_SYSTEM parameter. - CDRomFileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CD_ROM_FILE_SYSTEM, + /// CD_ROM_FILE_SYSTEM parameter. + CDRomFileSystem = NativeMethods.FILE_DEVICE.CD_ROM_FILE_SYSTEM, - /// FILE_DEVICE_CONTROLLER parameter. - Controller = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CONTROLLER, + /// CONTROLLER parameter. + Controller = NativeMethods.FILE_DEVICE.CONTROLLER, - /// FILE_DEVICE_DATALINK parameter. - DataLink = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DATALINK, + /// DATALINK parameter. + DataLink = NativeMethods.FILE_DEVICE.DATALINK, - /// FILE_DEVICE_DFS parameter. + /// DFS parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] - Dfs = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DFS, + Dfs = NativeMethods.FILE_DEVICE.DFS, - /// FILE_DEVICE_DISK parameter. - Disk = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DISK, + /// DISK parameter. + Disk = NativeMethods.FILE_DEVICE.DISK, - /// FILE_DEVICE_DISK_FILE_SYSTEM parameter. - DiskFileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DISK_FILE_SYSTEM, + /// DISK_FILE_SYSTEM parameter. + DiskFileSystem = NativeMethods.FILE_DEVICE.DISK_FILE_SYSTEM, - /// FILE_DEVICE_FILE_SYSTEM parameter. - FileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_FILE_SYSTEM, + /// FILE_SYSTEM parameter. + FileSystem = NativeMethods.FILE_DEVICE.FILE_SYSTEM, - /// FILE_DEVICE_INPORT_PORT parameter. - InPort = NativeMethods.DEVICE_TYPE.FILE_DEVICE_INPORT_PORT, + /// INPORT_PORT parameter. + InPort = NativeMethods.FILE_DEVICE.INPORT_PORT, - /// FILE_DEVICE_KEYBOARD parameter. - Keyboard = NativeMethods.DEVICE_TYPE.FILE_DEVICE_KEYBOARD, + /// KEYBOARD parameter. + Keyboard = NativeMethods.FILE_DEVICE.KEYBOARD, - /// FILE_DEVICE_MAILSLOT parameter. - MailSlot = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MAILSLOT, + /// MAILSLOT parameter. + MailSlot = NativeMethods.FILE_DEVICE.MAILSLOT, - /// FILE_DEVICE_MIDI_IN parameter. - MidiIn = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MIDI_IN, + /// MIDI_IN parameter. + MidiIn = NativeMethods.FILE_DEVICE.MIDI_IN, - /// FILE_DEVICE_MIDI_OUT parameter. - MidiOut = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MIDI_OUT, + /// MIDI_OUT parameter. + MidiOut = NativeMethods.FILE_DEVICE.MIDI_OUT, - /// FILE_DEVICE_MOUSE parameter. - Mouse = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MOUSE, + /// MOUSE parameter. + Mouse = NativeMethods.FILE_DEVICE.MOUSE, - /// FILE_DEVICE_MULTI_UNC_PROVIDER parameter. + /// MULTI_UNC_PROVIDER parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi")] - MultiUncProvider = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MULTI_UNC_PROVIDER, + MultiUncProvider = NativeMethods.FILE_DEVICE.MULTI_UNC_PROVIDER, - /// FILE_DEVICE_NAMED_PIPE parameter. - NamedPipe = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NAMED_PIPE, + /// NAMED_PIPE parameter. + NamedPipe = NativeMethods.FILE_DEVICE.NAMED_PIPE, - /// FILE_DEVICE_NETWORK parameter. - Network = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NETWORK, + /// NETWORK parameter. + Network = NativeMethods.FILE_DEVICE.NETWORK, - /// FILE_DEVICE_NETWORK_BROWSER parameter. - NetworkBrowser = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NETWORK_BROWSER, + /// NETWORK_BROWSER parameter. + NetworkBrowser = NativeMethods.FILE_DEVICE.NETWORK_BROWSER, - /// FILE_DEVICE_NETWORK_FILE_SYSTEM parameter. - NetworkFileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NETWORK_FILE_SYSTEM, + /// NETWORK_FILE_SYSTEM parameter. + NetworkFileSystem = NativeMethods.FILE_DEVICE.NETWORK_FILE_SYSTEM, - /// FILE_DEVICE_NULL parameter. - NullDevice = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NULL, + /// NULL parameter. + NullDevice = NativeMethods.FILE_DEVICE.NULL, - /// FILE_DEVICE_PARALLEL_PORT parameter. - ParallelPort = NativeMethods.DEVICE_TYPE.FILE_DEVICE_PARALLEL_PORT, + /// PARALLEL_PORT parameter. + ParallelPort = NativeMethods.FILE_DEVICE.PARALLEL_PORT, - /// FILE_DEVICE_PHYSICAL_NETCARD parameter. - PhysicalNetCard = NativeMethods.DEVICE_TYPE.FILE_DEVICE_PHYSICAL_NETCARD, + /// PHYSICAL_NETCARD parameter. + PhysicalNetCard = NativeMethods.FILE_DEVICE.PHYSICAL_NETCARD, - /// FILE_DEVICE_PRINTER parameter. - Printer = NativeMethods.DEVICE_TYPE.FILE_DEVICE_PRINTER, + /// PRINTER parameter. + Printer = NativeMethods.FILE_DEVICE.PRINTER, - /// FILE_DEVICE_SCANNER parameter. - Scanner = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SCANNER, + /// SCANNER parameter. + Scanner = NativeMethods.FILE_DEVICE.SCANNER, - /// FILE_DEVICE_SERIAL_MOUSE_PORT parameter. - SerialMousePort = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SERIAL_MOUSE_PORT, + /// SERIAL_MOUSE_PORT parameter. + SerialMousePort = NativeMethods.FILE_DEVICE.SERIAL_MOUSE_PORT, - /// FILE_DEVICE_SERIAL_PORT parameter. - SerialPort = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SERIAL_PORT, + /// SERIAL_PORT parameter. + SerialPort = NativeMethods.FILE_DEVICE.SERIAL_PORT, - /// FILE_DEVICE_SCREEN parameter. - Screen = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SCREEN, + /// SCREEN parameter. + Screen = NativeMethods.FILE_DEVICE.SCREEN, - /// FILE_DEVICE_SOUND parameter. - Sound = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SOUND, + /// SOUND parameter. + Sound = NativeMethods.FILE_DEVICE.SOUND, - /// FILE_DEVICE_STREAMS parameter. - Streams = NativeMethods.DEVICE_TYPE.FILE_DEVICE_STREAMS, + /// STREAMS parameter. + Streams = NativeMethods.FILE_DEVICE.STREAMS, - /// FILE_DEVICE_TAPE parameter. - Tape = NativeMethods.DEVICE_TYPE.FILE_DEVICE_TAPE, + /// TAPE parameter. + Tape = NativeMethods.FILE_DEVICE.TAPE, - /// FILE_DEVICE_TAPE_FILE_SYSTEM parameter. - TapeFileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_TAPE_FILE_SYSTEM, + /// TAPE_FILE_SYSTEM parameter. + TapeFileSystem = NativeMethods.FILE_DEVICE.TAPE_FILE_SYSTEM, - /// FILE_DEVICE_TRANSPORT parameter. - Transport = NativeMethods.DEVICE_TYPE.FILE_DEVICE_TRANSPORT, + /// TRANSPORT parameter. + Transport = NativeMethods.FILE_DEVICE.TRANSPORT, - /// FILE_DEVICE_UNKNOWN parameter. - Unknown = NativeMethods.DEVICE_TYPE.FILE_DEVICE_UNKNOWN, + /// UNKNOWN parameter. + Unknown = NativeMethods.FILE_DEVICE.UNKNOWN, - /// FILE_DEVICE_VIDEO parameter. - Video = NativeMethods.DEVICE_TYPE.FILE_DEVICE_VIDEO, + /// VIDEO parameter. + Video = NativeMethods.FILE_DEVICE.VIDEO, - /// FILE_DEVICE_VIRTUAL_DISK parameter. - VirtualDisk = NativeMethods.DEVICE_TYPE.FILE_DEVICE_VIRTUAL_DISK, + /// VIRTUAL_DISK parameter. + VirtualDisk = NativeMethods.FILE_DEVICE.VIRTUAL_DISK, - /// FILE_DEVICE_WAVE_IN parameter. - WaveIn = NativeMethods.DEVICE_TYPE.FILE_DEVICE_WAVE_IN, + /// WAVE_IN parameter. + WaveIn = NativeMethods.FILE_DEVICE.WAVE_IN, - /// FILE_DEVICE_WAVE_OUT parameter. - WaveOut = NativeMethods.DEVICE_TYPE.FILE_DEVICE_WAVE_OUT, + /// WAVE_OUT parameter. + WaveOut = NativeMethods.FILE_DEVICE.WAVE_OUT, - /// FILE_DEVICE_8042_PORT parameter. - Port8042 = NativeMethods.DEVICE_TYPE.FILE_DEVICE_8042_PORT, + /// 8042_PORT parameter. + Port8042 = NativeMethods.FILE_DEVICE.PORT_8042, - /// FILE_DEVICE_NETWORK_REDIRECTOR parameter. - NetworkRedirector = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NETWORK_REDIRECTOR, + /// NETWORK_REDIRECTOR parameter. + NetworkRedirector = NativeMethods.FILE_DEVICE.NETWORK_REDIRECTOR, - /// FILE_DEVICE_BATTERY parameter. - Battery = NativeMethods.DEVICE_TYPE.FILE_DEVICE_BATTERY, + /// BATTERY parameter. + Battery = NativeMethods.FILE_DEVICE.BATTERY, - /// FILE_DEVICE_BUS_EXTENDER parameter. - BusExtender = NativeMethods.DEVICE_TYPE.FILE_DEVICE_BUS_EXTENDER, + /// BUS_EXTENDER parameter. + BusExtender = NativeMethods.FILE_DEVICE.BUS_EXTENDER, - /// FILE_DEVICE_MODEM parameter. - Modem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MODEM, + /// MODEM parameter. + Modem = NativeMethods.FILE_DEVICE.MODEM, - /// FILE_DEVICE_VDM parameter. + /// VDM parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vdm")] - Vdm = NativeMethods.DEVICE_TYPE.FILE_DEVICE_VDM, + Vdm = NativeMethods.FILE_DEVICE.VDM, - /// FILE_DEVICE_MASS_STORAGE parameter. - MassStorage = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MASS_STORAGE, + /// MASS_STORAGE parameter. + MassStorage = NativeMethods.FILE_DEVICE.MASS_STORAGE, - /// FILE_DEVICE_SMB parameter. + /// SMB parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smb")] - Smb = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SMB, + Smb = NativeMethods.FILE_DEVICE.SMB, - /// FILE_DEVICE_KS parameter. - KS = NativeMethods.DEVICE_TYPE.FILE_DEVICE_KS, + /// KS parameter. + KS = NativeMethods.FILE_DEVICE.KS, - /// FILE_DEVICE_CHANGER parameter. - Changer = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CHANGER, + /// CHANGER parameter. + Changer = NativeMethods.FILE_DEVICE.CHANGER, - /// FILE_DEVICE_SMARTCARD parameter. - Smartcard = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SMARTCARD, + /// SMARTCARD parameter. + Smartcard = NativeMethods.FILE_DEVICE.SMARTCARD, - /// FILE_DEVICE_ACPI parameter. + /// ACPI parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Acpi")] - Acpi = NativeMethods.DEVICE_TYPE.FILE_DEVICE_ACPI, + Acpi = NativeMethods.FILE_DEVICE.ACPI, - /// FILE_DEVICE_DVD parameter. + /// DVD parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dvd")] - Dvd = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DVD, + Dvd = NativeMethods.FILE_DEVICE.DVD, - /// FILE_DEVICE_FULLSCREEN_VIDEO parameter. + /// FULLSCREEN_VIDEO parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fullscreen")] - FullscreenVideo = NativeMethods.DEVICE_TYPE.FILE_DEVICE_FULLSCREEN_VIDEO, + FullscreenVideo = NativeMethods.FILE_DEVICE.FULLSCREEN_VIDEO, - /// FILE_DEVICE_DFS_FILE_SYSTEM parameter. + /// DFS_FILE_SYSTEM parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] - DfsFileSystem = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DFS_FILE_SYSTEM, + DfsFileSystem = NativeMethods.FILE_DEVICE.DFS_FILE_SYSTEM, - /// FILE_DEVICE_DFS_VOLUME parameter. + /// DFS_VOLUME parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dfs")] - DfsVolume = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DFS_VOLUME, + DfsVolume = NativeMethods.FILE_DEVICE.DFS_VOLUME, - /// FILE_DEVICE_SERENUM parameter. + /// SERENUM parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Serenum")] - Serenum = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SERENUM, + Serenum = NativeMethods.FILE_DEVICE.SERENUM, - /// FILE_DEVICE_TERMSRV parameter. + /// TERMSRV parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Termsrv")] - Termsrv = NativeMethods.DEVICE_TYPE.FILE_DEVICE_TERMSRV, + Termsrv = NativeMethods.FILE_DEVICE.TERMSRV, - /// FILE_DEVICE_KSEC parameter. - KSec = NativeMethods.DEVICE_TYPE.FILE_DEVICE_KSEC, + /// KSEC parameter. + KSec = NativeMethods.FILE_DEVICE.KSEC, - /// FILE_DEVICE_FIPS parameter. + /// FIPS parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fips")] - Fips = NativeMethods.DEVICE_TYPE.FILE_DEVICE_FIPS, + Fips = NativeMethods.FILE_DEVICE.FIPS, - /// FILE_DEVICE_INFINIBAND parameter. + /// INFINIBAND parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infiniband")] - Infiniband = NativeMethods.DEVICE_TYPE.FILE_DEVICE_INFINIBAND, + Infiniband = NativeMethods.FILE_DEVICE.INFINIBAND, - /// FILE_DEVICE_VMBUS parameter. + /// VMBUS parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Vm")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vm")] - VmBus = NativeMethods.DEVICE_TYPE.FILE_DEVICE_VMBUS, + VmBus = NativeMethods.FILE_DEVICE.VMBUS, - /// FILE_DEVICE_CRYPT_PROVIDER parameter. - CryptProvider = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CRYPT_PROVIDER, + /// CRYPT_PROVIDER parameter. + CryptProvider = NativeMethods.FILE_DEVICE.CRYPT_PROVIDER, - /// FILE_DEVICE_WPD parameter. + /// WPD parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wpd")] - Wpd = NativeMethods.DEVICE_TYPE.FILE_DEVICE_WPD, + Wpd = NativeMethods.FILE_DEVICE.WPD, - /// FILE_DEVICE_BLUETOOTH parameter. - Bluetooth = NativeMethods.DEVICE_TYPE.FILE_DEVICE_BLUETOOTH, + /// BLUETOOTH parameter. + Bluetooth = NativeMethods.FILE_DEVICE.BLUETOOTH, - /// FILE_DEVICE_MT_COMPOSITE parameter. + /// MT_COMPOSITE parameter. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Mt")] - MtComposite = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MT_COMPOSITE, + MtComposite = NativeMethods.FILE_DEVICE.MT_COMPOSITE, - /// FILE_DEVICE_MT_TRANSPORT parameter. - MTTransport = NativeMethods.DEVICE_TYPE.FILE_DEVICE_MT_TRANSPORT, + /// MT_TRANSPORT parameter. + MTTransport = NativeMethods.FILE_DEVICE.MT_TRANSPORT, - /// FILE_DEVICE_BIOMETRIC parameter. - Biometric = NativeMethods.DEVICE_TYPE.FILE_DEVICE_BIOMETRIC, + /// BIOMETRIC parameter. + Biometric = NativeMethods.FILE_DEVICE.BIOMETRIC, - /// FILE_DEVICE_PMI parameter. + /// PMI parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pmi")] - Pmi = NativeMethods.DEVICE_TYPE.FILE_DEVICE_PMI, + Pmi = NativeMethods.FILE_DEVICE.PMI, - /// FILE_DEVICE_EHSTOR parameter. + /// EHSTOR parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ehstor")] - Ehstor = NativeMethods.DEVICE_TYPE.FILE_DEVICE_EHSTOR, + Ehstor = NativeMethods.FILE_DEVICE.EHSTOR, - /// FILE_DEVICE_DEVAPI parameter. + /// DEVAPI parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Devapi")] - Devapi = NativeMethods.DEVICE_TYPE.FILE_DEVICE_DEVAPI, + Devapi = NativeMethods.FILE_DEVICE.DEVAPI, - /// FILE_DEVICE_GPIO parameter. + /// GPIO parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpio")] - Gpio = NativeMethods.DEVICE_TYPE.FILE_DEVICE_GPIO, + Gpio = NativeMethods.FILE_DEVICE.GPIO, - /// FILE_DEVICE_USBEX parameter. + /// USBEX parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Usbex")] - Usbex = NativeMethods.DEVICE_TYPE.FILE_DEVICE_USBEX, + Usbex = NativeMethods.FILE_DEVICE.USBEX, - /// FILE_DEVICE_CONSOLE parameter. - Console = NativeMethods.DEVICE_TYPE.FILE_DEVICE_CONSOLE, + /// CONSOLE parameter. + Console = NativeMethods.FILE_DEVICE.CONSOLE, - /// FILE_DEVICE_NFP parameter. + /// NFP parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nfp")] - Nfp = NativeMethods.DEVICE_TYPE.FILE_DEVICE_NFP, + Nfp = NativeMethods.FILE_DEVICE.NFP, - /// FILE_DEVICE_SYSENV parameter. + /// SYSENV parameter. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sysenv")] - Sysenv = NativeMethods.DEVICE_TYPE.FILE_DEVICE_SYSENV + Sysenv = NativeMethods.FILE_DEVICE.SYSENV } } diff --git a/AlphaFS/Filesystem/File Class/File.Create.cs b/AlphaFS/Filesystem/File Class/File.Create.cs index 67bbfeb71..a89c20db0 100644 --- a/AlphaFS/Filesystem/File Class/File.Create.cs +++ b/AlphaFS/Filesystem/File Class/File.Create.cs @@ -366,72 +366,6 @@ internal static SafeFileHandle CreateFileCore(KernelTransaction transaction, str } } - - - internal static SafeFileHandle CreateFileCore2(KernelTransaction transaction, 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.NtCreateFile(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(); - - Utils.IsValidHandle(safeHandle, lastError, pathLp, !continueOnException); - - - if (isAppend) - { - var success = NativeMethods.SetFilePointerEx(safeHandle, 0, IntPtr.Zero, SeekOrigin.End); - - lastError = Marshal.GetLastWin32Error(); - - if (!success) - { - if (!safeHandle.IsClosed) - safeHandle.Close(); - - NativeError.ThrowException(lastError, path); - } - } - - return safeHandle; - } - } - #endregion // CreateFileCore } } diff --git a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs index f68cd6f4d..4e24a7af1 100644 --- a/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs +++ b/AlphaFS/Filesystem/Native Methods/NativeMethods.FileManagement.cs @@ -102,11 +102,6 @@ internal static partial class NativeMethods internal static extern SafeFileHandle CreateFile([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] FileSystemRights dwDesiredAccess, [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, [MarshalAs(UnmanagedType.LPStruct)] Security.NativeMethods.SecurityAttributes lpSecurityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, [MarshalAs(UnmanagedType.U4)] ExtendedFileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile); - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] - [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern SafeFileHandle NtCreateFile([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [MarshalAs(UnmanagedType.U4)] FileSystemRights dwDesiredAccess, [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, [MarshalAs(UnmanagedType.LPStruct)] Security.NativeMethods.SecurityAttributes lpSecurityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, [MarshalAs(UnmanagedType.U4)] ExtendedFileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile); - - /// /// Creates or opens a file or I/O device. 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. diff --git a/AlphaFS/Utils.cs b/AlphaFS/Utils.cs index c2b6c8c69..0ce236b9c 100644 --- a/AlphaFS/Utils.cs +++ b/AlphaFS/Utils.cs @@ -30,20 +30,19 @@ using Alphaleonis.Win32; using Alphaleonis.Win32.Device; using Alphaleonis.Win32.Security; -using NativeMethods = Alphaleonis.Win32.Filesystem.NativeMethods; namespace Alphaleonis { internal static class Utils { - internal static T CopyFrom(T source) where T : new() - { - var destination = new T(); + //internal static T CopyFrom(T source) where T : new() + //{ + // var destination = new T(); - CopyTo(source, destination); + // CopyTo(source, destination); - return destination; - } + // return destination; + //} internal static void CopyTo(T source, T destination) @@ -81,7 +80,7 @@ internal static int GetDoubledBufferSizeOrThrowException(SafeHandle safeBuffer, case Win32Errors.ERROR_INSUFFICIENT_BUFFER: if (bufferSize == 0) - bufferSize = NativeMethods.DefaultFileBufferSize / 32; // 128 + bufferSize = Win32.Filesystem.NativeMethods.DefaultFileBufferSize / 32; // 128 bufferSize *= 2; break; @@ -306,34 +305,34 @@ internal static string UnitSizeToText(T numberOfBytes, CultureInfo cultureInf internal static uint GetHighOrderDword(long highPart) { - return (uint)((highPart >> 32) & 0xFFFFFFFF); + return (uint) ((highPart >> 32) & 0xFFFFFFFF); } internal static uint GetLowOrderDword(long lowPart) { - return (uint)(lowPart & 0xFFFFFFFF); + return (uint) (lowPart & 0xFFFFFFFF); } internal static long LuidToLong(LUID luid) { - var high = (ulong)luid.HighPart << 32; - var low = (ulong)luid.LowPart & 0x00000000FFFFFFFF; + var high = (ulong) luid.HighPart << 32; + var low = (ulong) luid.LowPart & 0x00000000FFFFFFFF; - return unchecked((long)(high | low)); + return unchecked((long) (high | low)); } internal static LUID LongToLuid(long lluid) { - return new LUID { HighPart = (uint)(lluid >> 32), LowPart = (uint)(lluid & 0xFFFFFFFF) }; + 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); + return ((long) highPart << 32) | ((long) lowPart & 0xFFFFFFFF); } #endregion // Bitmasking From 298ec8c9c36eef5228e6741f86668f337f9782a9 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 28 Jun 2018 14:28:46 +0200 Subject: [PATCH 129/133] Update CHANGELOG.md --- CHANGELOG.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 53fba3da5..56db947c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,12 +8,11 @@ Version 2.3 (2018-XX-XX) - Issue #451: Add overloaded method for `File.GetSize` to retrieve the size of all streams. - Issue #454: Add method `Directory.GetSize` to return the size of all alternate data streams of the specified directory and its files. -- Issue #459: Modify method `Directory.CreateDirectoryCore` to return `null` as well as `DirectoryInfo` instance. -- Issue #461: Remove text `:$DATA` from `AlternateDataStream.FullPath property`. ### Improvements - Issue #426: Correct casing of enum `STREAM_ATTRIBUTES` +- Issue #459: Modify method `Directory.CreateDirectoryCore` to return `null` as well as `DirectoryInfo` instance. - Issue #461: Remove text `:$DATA` from `AlternateDataStream.FullPath` property. - Issue #462: Add `IEquatable` to applicable info classes. - Issue #463: Add `[Serializable]` attribute to applicable info classes. From e9234dc0d254a0f500574f396fc819d2fc9af100 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 9 Jul 2018 14:48:47 +0200 Subject: [PATCH 130/133] Correct isFolder usage in method GetFileIdInfoCore. --- AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs b/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs index 8f733b437..65bca909f 100644 --- a/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs +++ b/AlphaFS/Filesystem/File Class/File.GetFileIdInfo.cs @@ -81,7 +81,7 @@ public static FileIdInfo GetFileIdInfo(SafeFileHandle handle) [SecurityCritical] internal static FileIdInfo GetFileIdInfoCore(KernelTransaction transaction, bool isFolder, string path, PathFormat pathFormat) { - using (var handle = CreateFileCore(transaction, false, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.ReadData, FileShare.ReadWrite, true, false, pathFormat)) + using (var handle = CreateFileCore(transaction, isFolder, path, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.ReadData, FileShare.ReadWrite, true, false, pathFormat)) { if (NativeMethods.IsAtLeastWindows8) { From 83ad24818573be2a306003e46b2bbf11d2824f17 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Mon, 9 Jul 2018 17:03:28 +0200 Subject: [PATCH 131/133] Removed obsolete file. --- AlphaFS/AlphaFS.csproj | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 502ae9f98..941d33331 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -282,7 +282,6 @@ - @@ -821,7 +820,7 @@ --> - + \ No newline at end of file From 9b22cdd1bf279e286a84d6e35d47c3c716283e4a Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Tue, 10 Jul 2018 19:38:14 +0200 Subject: [PATCH 132/133] Renamed some solution folders. --- AlphaFS/AlphaFS.csproj | 104 ++-- AlphaFS/Device/Device.cs | 523 ------------------ .../DriveInfo.EnumerateLogicalDrives.cs | 0 .../DriveInfo.GetDeviceInfo.cs | 0 .../DriveInfo.GetFreeDriveLetter.cs | 0 .../DriveInfo.cs | 0 .../Device.FilesystemHelper.cs} | 0 .../FilesystemHelper.Compression.cs | 0 ...ilesystemHelper.CreateDirectoryJunction.cs | 0 ...ilesystemHelper.DeleteDirectoryJunction.cs | 0 .../FilesystemHelper.GetLinkTarget.cs | 0 .../FilesystemHelper.GetLocalDevicePath.cs} | 0 ...ilesystemHelper.GetValidatedDevicePath.cs} | 0 .../{Local => Local Class}/Device.Local.cs | 0 .../Local.EnumerateDevices.cs | 0 .../Local.EnumeratePhysicalDisks.cs | 0 .../Local.GetDeviceIoData.cs | 0 .../Local.GetDevicePowerState.cs | 0 .../Local.GetDiskGeometryEx.cs | 0 .../Local.GetStorageAdapterInfo.cs | 0 .../Local.GetStorageDeviceInfo.cs | 0 .../Local.GetStoragePartitionInfo.cs | 0 .../Local.GetVolumeDiskExtents.cs | 0 .../Local.InvokeDeviceIoData.cs | 0 .../Local.OpenDevice.cs | 0 .../Local.SetStorageDeviceInfoData.cs | 0 .../PhysicalDiskInfo.ContainsVolume.cs | 0 ...DiskInfo.CreatePhysicalDiskInfoInstance.cs | 0 .../PhysicalDiskInfo.cs | 0 .../Volume.DefineDosDevice.cs | 0 .../Volume.DeleteDosDevice.cs | 0 .../Volume.DeleteVolumeMountPoint.cs | 0 .../Volume.DiskFreeSpace.cs | 0 .../Volume.DriveType.cs | 0 .../Volume.EnumerateVolumeMountPoints.cs | 0 .../Volume.EnumerateVolumePathNames.cs | 0 .../Volume.EnumerateVolumes.cs | 0 .../Volume.GetDriveFormat.cs | 0 .../Volume.GetDriveNameForNtDeviceName.cs | 0 .../Volume.GetUniqueVolumeNameForPath.cs | 0 .../Volume.GetVolumeDeviceName.cs | 0 .../Volume.GetVolumeDisplayName.cs | 0 .../Volume.GetVolumeGuid.cs | 0 .../Volume.GetVolumeGuidForNtDeviceName.cs | 0 .../Volume.GetVolumeInfo.cs | 0 .../Volume.GetVolumePathName.cs | 0 .../Volume.IsReady.cs | 0 .../Volume.IsSameVolume.cs | 0 .../Volume.IsVolume.cs | 0 .../Volume.QueryDosDevice.cs | 0 .../Volume.SetVolumeMountPoint.cs | 0 .../Volume.VolumeLabel.cs | 0 .../Device/{Volume => Volume Class}/Volume.cs | 0 .../{Volume => Volume Class}/VolumeInfo.cs | 0 54 files changed, 52 insertions(+), 575 deletions(-) delete mode 100644 AlphaFS/Device/Device.cs rename AlphaFS/Device/{DriveInfo => DriveInfo Class}/DriveInfo.EnumerateLogicalDrives.cs (100%) rename AlphaFS/Device/{DriveInfo => DriveInfo Class}/DriveInfo.GetDeviceInfo.cs (100%) rename AlphaFS/Device/{DriveInfo => DriveInfo Class}/DriveInfo.GetFreeDriveLetter.cs (100%) rename AlphaFS/Device/{DriveInfo => DriveInfo Class}/DriveInfo.cs (100%) rename AlphaFS/Device/{FileSystemHelper/Device.FileSystemHelper.cs => FilesystemHelper Class/Device.FilesystemHelper.cs} (100%) rename AlphaFS/Device/{FileSystemHelper => FilesystemHelper Class}/FilesystemHelper.Compression.cs (100%) rename AlphaFS/Device/{FileSystemHelper => FilesystemHelper Class}/FilesystemHelper.CreateDirectoryJunction.cs (100%) rename AlphaFS/Device/{FileSystemHelper => FilesystemHelper Class}/FilesystemHelper.DeleteDirectoryJunction.cs (100%) rename AlphaFS/Device/{FileSystemHelper => FilesystemHelper Class}/FilesystemHelper.GetLinkTarget.cs (100%) rename AlphaFS/Device/{FileSystemHelper/FileSystemHelper.GetLocalDevicePath.cs => FilesystemHelper Class/FilesystemHelper.GetLocalDevicePath.cs} (100%) rename AlphaFS/Device/{FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs => FilesystemHelper Class/FilesystemHelper.GetValidatedDevicePath.cs} (100%) rename AlphaFS/Device/{Local => Local Class}/Device.Local.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.EnumerateDevices.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.EnumeratePhysicalDisks.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.GetDeviceIoData.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.GetDevicePowerState.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.GetDiskGeometryEx.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.GetStorageAdapterInfo.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.GetStorageDeviceInfo.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.GetStoragePartitionInfo.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.GetVolumeDiskExtents.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.InvokeDeviceIoData.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.OpenDevice.cs (100%) rename AlphaFS/Device/{Local => Local Class}/Local.SetStorageDeviceInfoData.cs (100%) rename AlphaFS/Device/{PhysicalDisk => PhysicalDisk Class}/PhysicalDiskInfo.ContainsVolume.cs (100%) rename AlphaFS/Device/{PhysicalDisk => PhysicalDisk Class}/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs (100%) rename AlphaFS/Device/{PhysicalDisk => PhysicalDisk Class}/PhysicalDiskInfo.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.DefineDosDevice.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.DeleteDosDevice.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.DeleteVolumeMountPoint.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.DiskFreeSpace.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.DriveType.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.EnumerateVolumeMountPoints.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.EnumerateVolumePathNames.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.EnumerateVolumes.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.GetDriveFormat.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.GetDriveNameForNtDeviceName.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.GetUniqueVolumeNameForPath.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.GetVolumeDeviceName.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.GetVolumeDisplayName.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.GetVolumeGuid.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.GetVolumeGuidForNtDeviceName.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.GetVolumeInfo.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.GetVolumePathName.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.IsReady.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.IsSameVolume.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.IsVolume.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.QueryDosDevice.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.SetVolumeMountPoint.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.VolumeLabel.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/Volume.cs (100%) rename AlphaFS/Device/{Volume => Volume Class}/VolumeInfo.cs (100%) diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 9c9c832a9..1d6288b82 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -196,59 +196,59 @@ True - - - - - + + + + + - - - - + + + + - - - - - + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -308,7 +308,7 @@ - + @@ -591,8 +591,8 @@ - - + + @@ -860,8 +860,8 @@ - - + + diff --git a/AlphaFS/Device/Device.cs b/AlphaFS/Device/Device.cs deleted file mode 100644 index 48fc880f6..000000000 --- a/AlphaFS/Device/Device.cs +++ /dev/null @@ -1,523 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 -{ - /// Provides static methods to retrieve device resource information from a local or remote host. - public static class Device - { - #region Enumerate Devices - - /// [AlphaFS] Enumerates all available devices on the local host. - /// instances of type from the local host. - /// One of the devices. - [SecurityCritical] - public static IEnumerable EnumerateDevices(DeviceGuid deviceGuid) - { - return EnumerateDevicesCore(null, deviceGuid, true); - } - - - /// [AlphaFS] Enumerates all available devices of type on the local or remote host. - /// instances of type for the specified . - /// The name of the local or remote host on which the device resides. null refers to the local host. - /// One of the devices. - [SecurityCritical] - public static IEnumerable EnumerateDevices(string hostName, DeviceGuid deviceGuid) - { - return EnumerateDevicesCore(hostName, deviceGuid, true); - } - - - - - /// [AlphaFS] Enumerates all available devices on the local or remote host. - [SecurityCritical] - internal static IEnumerable 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(); - } - } - - - /// Builds a Device Interface Detail Data structure. - /// An initialized NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA instance. - [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; - } - - - /// Repeatedly invokes InvokeIoControl with the specified input until enough memory has been allocated. - [SecurityCritical] - private static void InvokeIoControlUnknownSize(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 - - /// [AlphaFS] Sets the NTFS compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. - /// The transaction. - /// Specifies that is a file or directory. - /// A path that describes a folder or file to compress or decompress. - /// true = compress, false = decompress - /// Indicates the format of the path parameter(s). - [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 - - /// [AlphaFS] Creates an NTFS directory junction (similar to CMD command: "MKLINK /J"). - 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); - } - } - - - /// [AlphaFS] Deletes an NTFS directory junction. - 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); - } - } - - - /// [AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system. - /// - /// - [SecurityCritical] - internal static LinkTargetInfo GetLinkTargetInfo(SafeFileHandle safeHandle, string reparsePath) - { - using (var safeBuffer = GetLinkTargetData(safeHandle, reparsePath)) - { - var header = safeBuffer.PtrToStructure(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(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(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); - } - } - } - - - /// [AlphaFS] Get information about the target of a mount point or symbolic link on an NTFS file system. - /// - /// - [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 - } -} diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs b/AlphaFS/Device/DriveInfo Class/DriveInfo.EnumerateLogicalDrives.cs similarity index 100% rename from AlphaFS/Device/DriveInfo/DriveInfo.EnumerateLogicalDrives.cs rename to AlphaFS/Device/DriveInfo Class/DriveInfo.EnumerateLogicalDrives.cs diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs b/AlphaFS/Device/DriveInfo Class/DriveInfo.GetDeviceInfo.cs similarity index 100% rename from AlphaFS/Device/DriveInfo/DriveInfo.GetDeviceInfo.cs rename to AlphaFS/Device/DriveInfo Class/DriveInfo.GetDeviceInfo.cs diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs b/AlphaFS/Device/DriveInfo Class/DriveInfo.GetFreeDriveLetter.cs similarity index 100% rename from AlphaFS/Device/DriveInfo/DriveInfo.GetFreeDriveLetter.cs rename to AlphaFS/Device/DriveInfo Class/DriveInfo.GetFreeDriveLetter.cs diff --git a/AlphaFS/Device/DriveInfo/DriveInfo.cs b/AlphaFS/Device/DriveInfo Class/DriveInfo.cs similarity index 100% rename from AlphaFS/Device/DriveInfo/DriveInfo.cs rename to AlphaFS/Device/DriveInfo Class/DriveInfo.cs diff --git a/AlphaFS/Device/FileSystemHelper/Device.FileSystemHelper.cs b/AlphaFS/Device/FilesystemHelper Class/Device.FilesystemHelper.cs similarity index 100% rename from AlphaFS/Device/FileSystemHelper/Device.FileSystemHelper.cs rename to AlphaFS/Device/FilesystemHelper Class/Device.FilesystemHelper.cs diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.Compression.cs b/AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.Compression.cs similarity index 100% rename from AlphaFS/Device/FileSystemHelper/FilesystemHelper.Compression.cs rename to AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.Compression.cs diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs b/AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.CreateDirectoryJunction.cs similarity index 100% rename from AlphaFS/Device/FileSystemHelper/FilesystemHelper.CreateDirectoryJunction.cs rename to AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.CreateDirectoryJunction.cs diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs b/AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.DeleteDirectoryJunction.cs similarity index 100% rename from AlphaFS/Device/FileSystemHelper/FilesystemHelper.DeleteDirectoryJunction.cs rename to AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.DeleteDirectoryJunction.cs diff --git a/AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs b/AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.GetLinkTarget.cs similarity index 100% rename from AlphaFS/Device/FileSystemHelper/FilesystemHelper.GetLinkTarget.cs rename to AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.GetLinkTarget.cs diff --git a/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetLocalDevicePath.cs b/AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.GetLocalDevicePath.cs similarity index 100% rename from AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetLocalDevicePath.cs rename to AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.GetLocalDevicePath.cs diff --git a/AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs b/AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.GetValidatedDevicePath.cs similarity index 100% rename from AlphaFS/Device/FileSystemHelper/FileSystemHelper.GetValidatedDevicePath.cs rename to AlphaFS/Device/FilesystemHelper Class/FilesystemHelper.GetValidatedDevicePath.cs diff --git a/AlphaFS/Device/Local/Device.Local.cs b/AlphaFS/Device/Local Class/Device.Local.cs similarity index 100% rename from AlphaFS/Device/Local/Device.Local.cs rename to AlphaFS/Device/Local Class/Device.Local.cs diff --git a/AlphaFS/Device/Local/Local.EnumerateDevices.cs b/AlphaFS/Device/Local Class/Local.EnumerateDevices.cs similarity index 100% rename from AlphaFS/Device/Local/Local.EnumerateDevices.cs rename to AlphaFS/Device/Local Class/Local.EnumerateDevices.cs diff --git a/AlphaFS/Device/Local/Local.EnumeratePhysicalDisks.cs b/AlphaFS/Device/Local Class/Local.EnumeratePhysicalDisks.cs similarity index 100% rename from AlphaFS/Device/Local/Local.EnumeratePhysicalDisks.cs rename to AlphaFS/Device/Local Class/Local.EnumeratePhysicalDisks.cs diff --git a/AlphaFS/Device/Local/Local.GetDeviceIoData.cs b/AlphaFS/Device/Local Class/Local.GetDeviceIoData.cs similarity index 100% rename from AlphaFS/Device/Local/Local.GetDeviceIoData.cs rename to AlphaFS/Device/Local Class/Local.GetDeviceIoData.cs diff --git a/AlphaFS/Device/Local/Local.GetDevicePowerState.cs b/AlphaFS/Device/Local Class/Local.GetDevicePowerState.cs similarity index 100% rename from AlphaFS/Device/Local/Local.GetDevicePowerState.cs rename to AlphaFS/Device/Local Class/Local.GetDevicePowerState.cs diff --git a/AlphaFS/Device/Local/Local.GetDiskGeometryEx.cs b/AlphaFS/Device/Local Class/Local.GetDiskGeometryEx.cs similarity index 100% rename from AlphaFS/Device/Local/Local.GetDiskGeometryEx.cs rename to AlphaFS/Device/Local Class/Local.GetDiskGeometryEx.cs diff --git a/AlphaFS/Device/Local/Local.GetStorageAdapterInfo.cs b/AlphaFS/Device/Local Class/Local.GetStorageAdapterInfo.cs similarity index 100% rename from AlphaFS/Device/Local/Local.GetStorageAdapterInfo.cs rename to AlphaFS/Device/Local Class/Local.GetStorageAdapterInfo.cs diff --git a/AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs b/AlphaFS/Device/Local Class/Local.GetStorageDeviceInfo.cs similarity index 100% rename from AlphaFS/Device/Local/Local.GetStorageDeviceInfo.cs rename to AlphaFS/Device/Local Class/Local.GetStorageDeviceInfo.cs diff --git a/AlphaFS/Device/Local/Local.GetStoragePartitionInfo.cs b/AlphaFS/Device/Local Class/Local.GetStoragePartitionInfo.cs similarity index 100% rename from AlphaFS/Device/Local/Local.GetStoragePartitionInfo.cs rename to AlphaFS/Device/Local Class/Local.GetStoragePartitionInfo.cs diff --git a/AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs b/AlphaFS/Device/Local Class/Local.GetVolumeDiskExtents.cs similarity index 100% rename from AlphaFS/Device/Local/Local.GetVolumeDiskExtents.cs rename to AlphaFS/Device/Local Class/Local.GetVolumeDiskExtents.cs diff --git a/AlphaFS/Device/Local/Local.InvokeDeviceIoData.cs b/AlphaFS/Device/Local Class/Local.InvokeDeviceIoData.cs similarity index 100% rename from AlphaFS/Device/Local/Local.InvokeDeviceIoData.cs rename to AlphaFS/Device/Local Class/Local.InvokeDeviceIoData.cs diff --git a/AlphaFS/Device/Local/Local.OpenDevice.cs b/AlphaFS/Device/Local Class/Local.OpenDevice.cs similarity index 100% rename from AlphaFS/Device/Local/Local.OpenDevice.cs rename to AlphaFS/Device/Local Class/Local.OpenDevice.cs diff --git a/AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs b/AlphaFS/Device/Local Class/Local.SetStorageDeviceInfoData.cs similarity index 100% rename from AlphaFS/Device/Local/Local.SetStorageDeviceInfoData.cs rename to AlphaFS/Device/Local Class/Local.SetStorageDeviceInfoData.cs diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.ContainsVolume.cs b/AlphaFS/Device/PhysicalDisk Class/PhysicalDiskInfo.ContainsVolume.cs similarity index 100% rename from AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.ContainsVolume.cs rename to AlphaFS/Device/PhysicalDisk Class/PhysicalDiskInfo.ContainsVolume.cs diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs b/AlphaFS/Device/PhysicalDisk Class/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs similarity index 100% rename from AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs rename to AlphaFS/Device/PhysicalDisk Class/PhysicalDiskInfo.CreatePhysicalDiskInfoInstance.cs diff --git a/AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs b/AlphaFS/Device/PhysicalDisk Class/PhysicalDiskInfo.cs similarity index 100% rename from AlphaFS/Device/PhysicalDisk/PhysicalDiskInfo.cs rename to AlphaFS/Device/PhysicalDisk Class/PhysicalDiskInfo.cs diff --git a/AlphaFS/Device/Volume/Volume.DefineDosDevice.cs b/AlphaFS/Device/Volume Class/Volume.DefineDosDevice.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.DefineDosDevice.cs rename to AlphaFS/Device/Volume Class/Volume.DefineDosDevice.cs diff --git a/AlphaFS/Device/Volume/Volume.DeleteDosDevice.cs b/AlphaFS/Device/Volume Class/Volume.DeleteDosDevice.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.DeleteDosDevice.cs rename to AlphaFS/Device/Volume Class/Volume.DeleteDosDevice.cs diff --git a/AlphaFS/Device/Volume/Volume.DeleteVolumeMountPoint.cs b/AlphaFS/Device/Volume Class/Volume.DeleteVolumeMountPoint.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.DeleteVolumeMountPoint.cs rename to AlphaFS/Device/Volume Class/Volume.DeleteVolumeMountPoint.cs diff --git a/AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs b/AlphaFS/Device/Volume Class/Volume.DiskFreeSpace.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.DiskFreeSpace.cs rename to AlphaFS/Device/Volume Class/Volume.DiskFreeSpace.cs diff --git a/AlphaFS/Device/Volume/Volume.DriveType.cs b/AlphaFS/Device/Volume Class/Volume.DriveType.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.DriveType.cs rename to AlphaFS/Device/Volume Class/Volume.DriveType.cs diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs b/AlphaFS/Device/Volume Class/Volume.EnumerateVolumeMountPoints.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.EnumerateVolumeMountPoints.cs rename to AlphaFS/Device/Volume Class/Volume.EnumerateVolumeMountPoints.cs diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs b/AlphaFS/Device/Volume Class/Volume.EnumerateVolumePathNames.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.EnumerateVolumePathNames.cs rename to AlphaFS/Device/Volume Class/Volume.EnumerateVolumePathNames.cs diff --git a/AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs b/AlphaFS/Device/Volume Class/Volume.EnumerateVolumes.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.EnumerateVolumes.cs rename to AlphaFS/Device/Volume Class/Volume.EnumerateVolumes.cs diff --git a/AlphaFS/Device/Volume/Volume.GetDriveFormat.cs b/AlphaFS/Device/Volume Class/Volume.GetDriveFormat.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.GetDriveFormat.cs rename to AlphaFS/Device/Volume Class/Volume.GetDriveFormat.cs diff --git a/AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs b/AlphaFS/Device/Volume Class/Volume.GetDriveNameForNtDeviceName.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.GetDriveNameForNtDeviceName.cs rename to AlphaFS/Device/Volume Class/Volume.GetDriveNameForNtDeviceName.cs diff --git a/AlphaFS/Device/Volume/Volume.GetUniqueVolumeNameForPath.cs b/AlphaFS/Device/Volume Class/Volume.GetUniqueVolumeNameForPath.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.GetUniqueVolumeNameForPath.cs rename to AlphaFS/Device/Volume Class/Volume.GetUniqueVolumeNameForPath.cs diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs b/AlphaFS/Device/Volume Class/Volume.GetVolumeDeviceName.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.GetVolumeDeviceName.cs rename to AlphaFS/Device/Volume Class/Volume.GetVolumeDeviceName.cs diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs b/AlphaFS/Device/Volume Class/Volume.GetVolumeDisplayName.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.GetVolumeDisplayName.cs rename to AlphaFS/Device/Volume Class/Volume.GetVolumeDisplayName.cs diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs b/AlphaFS/Device/Volume Class/Volume.GetVolumeGuid.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.GetVolumeGuid.cs rename to AlphaFS/Device/Volume Class/Volume.GetVolumeGuid.cs diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeGuidForNtDeviceName.cs b/AlphaFS/Device/Volume Class/Volume.GetVolumeGuidForNtDeviceName.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.GetVolumeGuidForNtDeviceName.cs rename to AlphaFS/Device/Volume Class/Volume.GetVolumeGuidForNtDeviceName.cs diff --git a/AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs b/AlphaFS/Device/Volume Class/Volume.GetVolumeInfo.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.GetVolumeInfo.cs rename to AlphaFS/Device/Volume Class/Volume.GetVolumeInfo.cs diff --git a/AlphaFS/Device/Volume/Volume.GetVolumePathName.cs b/AlphaFS/Device/Volume Class/Volume.GetVolumePathName.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.GetVolumePathName.cs rename to AlphaFS/Device/Volume Class/Volume.GetVolumePathName.cs diff --git a/AlphaFS/Device/Volume/Volume.IsReady.cs b/AlphaFS/Device/Volume Class/Volume.IsReady.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.IsReady.cs rename to AlphaFS/Device/Volume Class/Volume.IsReady.cs diff --git a/AlphaFS/Device/Volume/Volume.IsSameVolume.cs b/AlphaFS/Device/Volume Class/Volume.IsSameVolume.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.IsSameVolume.cs rename to AlphaFS/Device/Volume Class/Volume.IsSameVolume.cs diff --git a/AlphaFS/Device/Volume/Volume.IsVolume.cs b/AlphaFS/Device/Volume Class/Volume.IsVolume.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.IsVolume.cs rename to AlphaFS/Device/Volume Class/Volume.IsVolume.cs diff --git a/AlphaFS/Device/Volume/Volume.QueryDosDevice.cs b/AlphaFS/Device/Volume Class/Volume.QueryDosDevice.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.QueryDosDevice.cs rename to AlphaFS/Device/Volume Class/Volume.QueryDosDevice.cs diff --git a/AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs b/AlphaFS/Device/Volume Class/Volume.SetVolumeMountPoint.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.SetVolumeMountPoint.cs rename to AlphaFS/Device/Volume Class/Volume.SetVolumeMountPoint.cs diff --git a/AlphaFS/Device/Volume/Volume.VolumeLabel.cs b/AlphaFS/Device/Volume Class/Volume.VolumeLabel.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.VolumeLabel.cs rename to AlphaFS/Device/Volume Class/Volume.VolumeLabel.cs diff --git a/AlphaFS/Device/Volume/Volume.cs b/AlphaFS/Device/Volume Class/Volume.cs similarity index 100% rename from AlphaFS/Device/Volume/Volume.cs rename to AlphaFS/Device/Volume Class/Volume.cs diff --git a/AlphaFS/Device/Volume/VolumeInfo.cs b/AlphaFS/Device/Volume Class/VolumeInfo.cs similarity index 100% rename from AlphaFS/Device/Volume/VolumeInfo.cs rename to AlphaFS/Device/Volume Class/VolumeInfo.cs From e5301dc1042ec7bcdf380186f1cf242b4312cdd0 Mon Sep 17 00:00:00 2001 From: Jeffrey Jangli Date: Thu, 12 Jul 2018 14:18:36 +0200 Subject: [PATCH 133/133] -Improved methods Directory.DeleteDirectoryCore and File.DeleteFileCore; -Moved some files around, code improvement, work in progress; --- ...phaFS_Volume.EnumerateVolumeMountPoints.cs | 2 +- .../AlphaFS_Volume.EnumerateVolumes.cs | 2 +- ...haFS_Volume.GetDriveNameForNtDeviceName.cs | 2 +- ...phaFS_Volume.GetUniqueVolumeNameForPath.cs | 2 +- .../AlphaFS_Volume.GetXxx.cs | 2 +- .../AlphaFS_Device.EnumerateDevices.cs | 2 +- .../AlphaFS_Directory_Encrypt_And_Decrypt.cs | 4 +- ...Directory_Encrypt_And_Decrypt_Recursive.cs | 4 +- .../AlphaFS_Host.EnumerateDfsLinks.cs | 2 +- .../AlphaFS_Host.EnumerateDfsRoot.cs | 4 +- .../AlphaFS_Host.EnumerateDomainDfsRoot.cs | 2 +- ...lphaFS_Host.EnumerateNetworkConnections.cs | 2 +- .../AlphaFS_Host.EnumerateNetworks.cs | 2 +- .../AlphaFS_Host.EnumerateOpenConnections.cs | 2 +- .../AlphaFS_Host.EnumerateOpenResources.cs | 2 +- .../AlphaFS_Host.EnumerateSessions.cs | 2 +- .../AlphaFS_Host.EnumerateShares.cs | 2 +- .../UnitTest Utility/UnitTestAssert.cs | 4 +- .../UnitTests/AlphaFS_DfsInfoTest.cs | 4 +- AlphaFS/AlphaFS.csproj | 62 ++++----- .../Directory.CopyMoveDirectoryCore.cs | 3 +- .../Directory.DeleteDirectoryCore.cs | 106 ++------------- .../Directory.DeleteDirectoryNative.cs | 127 ++++++++++++++++++ .../{UTC => }/Directory.GetChangeTimeUtc.cs | 0 .../Directory.GetChangeTimeUtcTransacted.cs | 0 .../{UTC => }/Directory.GetCreationTimeUtc.cs | 0 .../Directory.GetCreationTimeUtcTransacted.cs | 0 .../Directory.GetLastAccessTimeUtc.cs | 0 ...irectory.GetLastAccessTimeUtcTransacted.cs | 0 .../Directory.GetLastWriteTimeUtc.cs | 0 ...Directory.GetLastWriteTimeUtcTransacted.cs | 0 .../{UTC => }/Directory.SetCreationTimeUtc.cs | 0 .../Directory.SetCreationTimeUtcTransacted.cs | 0 .../Directory.SetLastAccessTimeUtc.cs | 0 .../Directory.SetLastWriteTimeUtc.cs | 0 ...Directory.SetLastWriteTimeUtcTransacted.cs | 0 ...irectory.SetLastAccessTimeUtcTransacted.cs | 76 ----------- .../File Core Methods/File.DeleteFileCore.cs | 45 +++++-- .../File.EncryptDecryptFileCore.cs | 25 ++-- .../File.SetFsoDateTimeCore.cs | 15 +-- .../{UTC => }/File.GetChangeTimeUtc.cs | 0 .../File.GetChangeTimeUtcTransacted.cs | 0 .../{UTC => }/File.GetCreationTimeUtc.cs | 0 .../File.GetCreationTimeUtcTransacted.cs | 0 .../{UTC => }/File.GetLastAccessTimeUtc.cs | 0 .../File.GetLastAccessTimeUtcTransacted.cs | 0 .../{UTC => }/File.GetLastWriteTimeUtc.cs | 0 .../File.GetLastWriteTimeUtcTransacted.cs | 0 .../{UTC => }/File.SetCreationTimeUtc.cs | 0 .../File.SetCreationTimeUtcTransacted.cs | 0 .../{UTC => }/File.SetLastAccessTimeUtc.cs | 0 .../File.SetLastAccessTimeUtcTransacted.cs | 0 .../{UTC => }/File.SetLastWriteTimeUtc.cs | 0 .../File.SetLastWriteTimeUtcTransacted.cs | 0 .../{UTC => }/File.SetTimestampsUtc.cs | 0 .../File.SetTimestampsUtcTransacted.cs | 0 .../File Class/File.AttributeLogic.cs | 6 +- AlphaFS/Filesystem/File Class/File.Delete.cs | 8 +- .../File Class/File.DeleteTransacted.cs | 8 +- .../File Class/File.GetAttributes.cs | 9 +- .../FileInfo Class/FileInfo.Delete.cs | 7 +- AlphaFS/Filesystem/FileSystemInfo.cs | 71 +++++----- AlphaFS/Filesystem/FindFileSystemEntryInfo.cs | 22 +-- CHANGELOG.md | 1 + 64 files changed, 312 insertions(+), 327 deletions(-) create mode 100644 AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryNative.cs rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.GetChangeTimeUtc.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.GetChangeTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.GetCreationTimeUtc.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.GetCreationTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.GetLastAccessTimeUtc.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.GetLastAccessTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.GetLastWriteTimeUtc.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.GetLastWriteTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.SetCreationTimeUtc.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.SetCreationTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.SetLastAccessTimeUtc.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.SetLastWriteTimeUtc.cs (100%) rename AlphaFS/Filesystem/Directory Class/Directory Time/{UTC => }/Directory.SetLastWriteTimeUtcTransacted.cs (100%) delete mode 100644 AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetLastAccessTimeUtcTransacted.cs rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.GetChangeTimeUtc.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.GetChangeTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.GetCreationTimeUtc.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.GetCreationTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.GetLastAccessTimeUtc.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.GetLastAccessTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.GetLastWriteTimeUtc.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.GetLastWriteTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.SetCreationTimeUtc.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.SetCreationTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.SetLastAccessTimeUtc.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.SetLastAccessTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.SetLastWriteTimeUtc.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.SetLastWriteTimeUtcTransacted.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.SetTimestampsUtc.cs (100%) rename AlphaFS/Filesystem/File Class/File Time/{UTC => }/File.SetTimestampsUtcTransacted.cs (100%) diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumeMountPoints.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumeMountPoints.cs index 6883fb167..4a83ece57 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumeMountPoints.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumeMountPoints.cs @@ -70,7 +70,7 @@ public void AlphaFS_Volume_EnumerateVolumeMountPoints_Local_Success() if (cnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumes.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumes.cs index 105541645..27561db57 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumes.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.EnumerateVolumes.cs @@ -57,7 +57,7 @@ public void AlphaFS_Volume_EnumerateVolumes_Local_Success() if (volumeCount == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs index 97b7d4570..e3f6735a7 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetDriveNameForNtDeviceName.cs @@ -75,7 +75,7 @@ public void AlphaFS_Volume_GetDriveNameForNtDeviceName_And_GetVolumeGuidForNtDev if (driveCount == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs index ce16aa589..3ef784495 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetUniqueVolumeNameForPath.cs @@ -91,7 +91,7 @@ public void AlphaFS_Volume_GetUniqueVolumeNameForPath_Local_Success() if (driveCount == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs index 0320302fd..194a98da8 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS Volume Class/AlphaFS_Volume.GetXxx.cs @@ -127,7 +127,7 @@ public void AlphaFS_Volume_GetXxx_Local_Success() } if (driveCount == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs index f199dbc89..4013b9574 100644 --- a/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs +++ b/AlphaFS.UnitTest/AlphaFS Device Class/AlphaFS_Device.EnumerateDevices.cs @@ -59,7 +59,7 @@ private void AlphaFS_Device_EnumerateDevices() } if (classCnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs index 65ed6e0a8..544d96bc8 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt.cs @@ -59,7 +59,7 @@ private void AlphaFS_Directory_EncryptDecrypt(bool isNetwork) } if (cnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); // Encrypt entire folder for decrypt test. @@ -78,7 +78,7 @@ private void AlphaFS_Directory_EncryptDecrypt(bool isNetwork) } if (cnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt_Recursive.cs b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt_Recursive.cs index f7b0314cf..3ccff5a1e 100644 --- a/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt_Recursive.cs +++ b/AlphaFS.UnitTest/AlphaFS Encryption/AlphaFS_Directory_Encrypt_And_Decrypt_Recursive.cs @@ -59,7 +59,7 @@ private void AlphaFS_Directory_EncryptDecrypt_Recursive(bool isNetwork) } if (cnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); @@ -77,7 +77,7 @@ private void AlphaFS_Directory_EncryptDecrypt_Recursive(bool isNetwork) } if (cnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDfsLinks.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDfsLinks.cs index c9ca6105b..5cc76ffa7 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDfsLinks.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDfsLinks.cs @@ -79,7 +79,7 @@ public void AlphaFS_Host_EnumerateDfsLinks_Network_Success() UnitTestAssert.Inconclusive("Test ignored because the computer is either not connected to a domain or no DFS root exists."); else if (cnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDfsRoot.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDfsRoot.cs index de10fd7c8..9fd05f714 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDfsRoot.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDfsRoot.cs @@ -75,7 +75,7 @@ public void AlphaFS_Host_EnumerateDfsRoot_Network_Success() } if (cnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } catch (NetworkInformationException ex) { @@ -91,7 +91,7 @@ public void AlphaFS_Host_EnumerateDfsRoot_Network_Success() UnitTestAssert.Inconclusive("Test ignored because the computer is either not connected to a domain or no DFS root exists."); else if (cnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); Console.WriteLine(); diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDomainDfsRoot.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDomainDfsRoot.cs index e746cbf8d..3386ef964 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDomainDfsRoot.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateDomainDfsRoot.cs @@ -61,7 +61,7 @@ public void AlphaFS_Host_EnumerateDomainDfsRoot_Network_Success() UnitTestAssert.Inconclusive("Test ignored because the computer is either not connected to a domain or no DFS root exists."); else if (cnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); Console.WriteLine(); } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs index 0d33cece7..3a0c3af59 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworkConnections.cs @@ -55,7 +55,7 @@ public void AlphaFS_Host_EnumerateNetworkConnections_Local_Success() if (networkConnectionCount == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs index c850bd98b..2b1e7b4db 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateNetworks.cs @@ -60,7 +60,7 @@ public void AlphaFS_Host_EnumerateNetworks_Local_Success() if (networkCount == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenConnections.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenConnections.cs index de127e567..cf32ec7c8 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenConnections.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenConnections.cs @@ -73,7 +73,7 @@ private void EnumerateOpenConnections(string host, string share) if (count == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenResources.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenResources.cs index ac27051ff..f522cbfc4 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenResources.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateOpenResources.cs @@ -53,7 +53,7 @@ public void AlphaFS_Host_EnumerateOpenResources_Local_Success() if (count == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs index a46c64ffa..5b1e03294 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateSessions.cs @@ -55,7 +55,7 @@ public void AlphaFS_Host_EnumerateSessions_Local_Success() if (sessionCount == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } } } diff --git a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateShares.cs b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateShares.cs index 57e817eea..973c810cf 100644 --- a/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateShares.cs +++ b/AlphaFS.UnitTest/AlphaFS Host Class/AlphaFS_Host.EnumerateShares.cs @@ -51,7 +51,7 @@ public void AlphaFS_Host_EnumerateShares_Local_Success() } if (count == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } } } diff --git a/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs b/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs index 9f62a698f..e1d796db8 100644 --- a/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs +++ b/AlphaFS.UnitTest/UnitTest Utility/UnitTestAssert.cs @@ -44,9 +44,9 @@ public static void Inconclusive(string errorMessage) } - public static void InconclusiveBecauseEnumerationIsEmpty() + public static void InconclusiveBecauseResourcesAreUnavailable() { - Inconclusive("The enumeration returned an empty collection, which is not expected."); + Inconclusive("No resources are available for this unit test."); } diff --git a/AlphaFS.UnitTest/UnitTests/AlphaFS_DfsInfoTest.cs b/AlphaFS.UnitTest/UnitTests/AlphaFS_DfsInfoTest.cs index 31abcea57..5ffef0bc7 100644 --- a/AlphaFS.UnitTest/UnitTests/AlphaFS_DfsInfoTest.cs +++ b/AlphaFS.UnitTest/UnitTests/AlphaFS_DfsInfoTest.cs @@ -70,7 +70,7 @@ public void AlphaFS_DfsInfo() } if (cnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); } catch (NetworkInformationException ex) { @@ -86,7 +86,7 @@ public void AlphaFS_DfsInfo() UnitTestAssert.Inconclusive("Test ignored because the computer is either not connected to a domain or no DFS root exists."); if (cnt == 0) - UnitTestAssert.InconclusiveBecauseEnumerationIsEmpty(); + UnitTestAssert.InconclusiveBecauseResourcesAreUnavailable(); Console.WriteLine(); } diff --git a/AlphaFS/AlphaFS.csproj b/AlphaFS/AlphaFS.csproj index 34d5ca6a1..84d8080ea 100644 --- a/AlphaFS/AlphaFS.csproj +++ b/AlphaFS/AlphaFS.csproj @@ -251,6 +251,20 @@ + + + + + + + + + + + + + + @@ -310,26 +324,12 @@ - - - - - - - - - - - - - - @@ -372,6 +372,22 @@ + + + + + + + + + + + + + + + + @@ -390,36 +406,21 @@ - - - - - - - - - - - - - - - @@ -624,7 +625,6 @@ - @@ -906,7 +906,7 @@ --> - + \ No newline at end of file diff --git a/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CopyMoveDirectoryCore.cs b/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CopyMoveDirectoryCore.cs index a0feb864a..2f9cda50d 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CopyMoveDirectoryCore.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.CopyMoveDirectoryCore.cs @@ -20,6 +20,7 @@ */ using System.Collections.Generic; +using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -81,7 +82,7 @@ internal static void CopyMoveDirectoryCore(bool retry, CopyMoveArguments cma, Co copyMoveResult.TotalBytes += fseiSource.FileSize; if (cma.EmulateMove) - File.DeleteFileCore(cma.Transaction, fseiSourcePath, true, PathFormat.LongFullPath); + File.DeleteFileCore(cma.Transaction, fseiSourcePath, true, fseiSource.Attributes, PathFormat.LongFullPath); } } } diff --git a/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryCore.cs b/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryCore.cs index 0340d6244..418153731 100644 --- a/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryCore.cs +++ b/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryCore.cs @@ -21,10 +21,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; using System.IO; -using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem @@ -73,6 +70,13 @@ internal static void DeleteDirectoryCore(KernelTransaction transaction, FileSyst pathFormat = PathFormat.LongFullPath; + // Reset attributes to Normal if we already know the facts. + + if (ignoreReadOnly && (fsEntryInfo.IsReadOnly || fsEntryInfo.IsHidden)) + + File.SetAttributesCore(transaction, fsEntryInfo.IsDirectory, fsEntryInfo.LongFullPath, FileAttributes.Normal, PathFormat.LongFullPath); + + // Do not follow mount points nor symbolic links, but do delete the reparse point itself. // If directory is reparse point, disable recursion. @@ -93,110 +97,22 @@ internal static void DeleteDirectoryCore(KernelTransaction transaction, FileSyst } else - File.DeleteFileCore(transaction, fsei.LongFullPath, ignoreReadOnly, pathFormat); + File.DeleteFileCore(transaction, fsei.LongFullPath, ignoreReadOnly, fsei.Attributes, pathFormat); } while (dirs.Count > 0) - DeleteDirectoryCore(transaction, dirs.Pop(), ignoreReadOnly, continueOnNotFound); + DeleteDirectoryNative(transaction, dirs.Pop(), ignoreReadOnly, continueOnNotFound, 0); } // Check to see if this is a mount point, and unmount it. // Now it is safe to delete the actual directory. + if (fsEntryInfo.IsMountPoint) DeleteJunctionCore(transaction, fsEntryInfo, null, false, pathFormat); - DeleteDirectoryCore(transaction, fsEntryInfo.LongFullPath, ignoreReadOnly, continueOnNotFound); - } - - - [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - private static void DeleteDirectoryCore(KernelTransaction transaction, string pathLp, bool ignoreReadOnly, bool continueOnNotFound) - { - - 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: - var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); - var dataInitialised = File.FillAttributeInfoCore(transaction, pathLp, ref attrs, false, true); - - - if (File.IsReadOnly(attrs.dwFileAttributes)) - { - // 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 (dataInitialised == Win32Errors.ERROR_SUCCESS) - NativeError.ThrowException(lastError, 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); - } + DeleteDirectoryNative(transaction, fsEntryInfo.LongFullPath, ignoreReadOnly, continueOnNotFound, 0); } } } diff --git a/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryNative.cs b/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryNative.cs new file mode 100644 index 000000000..228fe3d46 --- /dev/null +++ b/AlphaFS/Filesystem/Directory Class/Directory Core Methods/Directory.DeleteDirectoryNative.cs @@ -0,0 +1,127 @@ +/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION 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); + } + } + } +} diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetChangeTimeUtc.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetChangeTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetChangeTimeUtc.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetChangeTimeUtc.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetChangeTimeUtcTransacted.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetChangeTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetChangeTimeUtcTransacted.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetChangeTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetCreationTimeUtc.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetCreationTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetCreationTimeUtc.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetCreationTimeUtc.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetCreationTimeUtcTransacted.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetCreationTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetCreationTimeUtcTransacted.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetCreationTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetLastAccessTimeUtc.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastAccessTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetLastAccessTimeUtc.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastAccessTimeUtc.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetLastAccessTimeUtcTransacted.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastAccessTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetLastAccessTimeUtcTransacted.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastAccessTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetLastWriteTimeUtc.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastWriteTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetLastWriteTimeUtc.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastWriteTimeUtc.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetLastWriteTimeUtcTransacted.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastWriteTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.GetLastWriteTimeUtcTransacted.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.GetLastWriteTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetCreationTimeUtc.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetCreationTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetCreationTimeUtc.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetCreationTimeUtc.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetCreationTimeUtcTransacted.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetCreationTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetCreationTimeUtcTransacted.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetCreationTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetLastAccessTimeUtc.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastAccessTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetLastAccessTimeUtc.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastAccessTimeUtc.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetLastWriteTimeUtc.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastWriteTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetLastWriteTimeUtc.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastWriteTimeUtc.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetLastWriteTimeUtcTransacted.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastWriteTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetLastWriteTimeUtcTransacted.cs rename to AlphaFS/Filesystem/Directory Class/Directory Time/Directory.SetLastWriteTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetLastAccessTimeUtcTransacted.cs b/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetLastAccessTimeUtcTransacted.cs deleted file mode 100644 index 8ebbe3454..000000000 --- a/AlphaFS/Filesystem/Directory Class/Directory Time/UTC/Directory.SetLastAccessTimeUtcTransacted.cs +++ /dev/null @@ -1,76 +0,0 @@ -/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION 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 - { - /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. - /// The transaction. - /// The directory for which to set the access date and time information. - /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. - [SecurityCritical] - public static void SetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastAccessTimeUtc) - { - File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTimeUtc, null, false, PathFormat.RelativePath); - } - - - /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. - /// The transaction. - /// The directory for which to set the access date and time information. - /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. - /// Indicates the format of the path parameter(s). - [SecurityCritical] - public static void SetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastAccessTimeUtc, PathFormat pathFormat) - { - File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTimeUtc, null, false, pathFormat); - } - - - /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. - /// The transaction. - /// The directory for which to set the access date and time information. - /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. - /// If true, 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 does not refer to a reparse point. - [SecurityCritical] - public static void SetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastAccessTimeUtc, bool modifyReparsePoint) - { - File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTimeUtc, null, modifyReparsePoint, PathFormat.RelativePath); - } - - - /// [AlphaFS] Sets the date and time, in coordinated universal time (UTC), that the specified directory was last accessed. - /// The transaction. - /// The directory for which to set the access date and time information. - /// A containing the value to set for the last access date and time of . This value is expressed in UTC time. - /// If true, 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 does not refer to a reparse point. - /// Indicates the format of the path parameter(s). - [SecurityCritical] - public static void SetLastAccessTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastAccessTimeUtc, bool modifyReparsePoint, PathFormat pathFormat) - { - File.SetFsoDateTimeCore(transaction, false, path, null, lastAccessTimeUtc, null, modifyReparsePoint, pathFormat); - } - } -} diff --git a/AlphaFS/Filesystem/File Class/File Core Methods/File.DeleteFileCore.cs b/AlphaFS/Filesystem/File Class/File Core Methods/File.DeleteFileCore.cs index 37739f750..bd57ef194 100644 --- a/AlphaFS/Filesystem/File Class/File Core Methods/File.DeleteFileCore.cs +++ b/AlphaFS/Filesystem/File Class/File Core Methods/File.DeleteFileCore.cs @@ -38,9 +38,10 @@ public static partial class File /// The transaction. /// The name of the file to be deleted. /// true overrides the read only of the file. + /// /// Indicates the format of the path parameter(s). [SecurityCritical] - internal static void DeleteFileCore(KernelTransaction transaction, string path, bool ignoreReadOnly, PathFormat pathFormat) + internal static void DeleteFileCore(KernelTransaction transaction, string path, bool ignoreReadOnly, FileAttributes attributes, PathFormat pathFormat) { if (null == path) throw new ArgumentNullException("path"); @@ -50,49 +51,67 @@ internal static void DeleteFileCore(KernelTransaction transaction, string path, var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator); - // If the path points to a symbolic link, the symbolic link is deleted, not the target. + + // Reset attributes to Normal if we already know the facts. + + if (ignoreReadOnly && IsReadOnlyOrHidden(attributes)) + + SetAttributesCore(transaction, false, pathLp, FileAttributes.Normal, PathFormat.LongFullPath); startDeleteFile: - if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista + 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) + + 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: - var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); - var dataInitialised = FillAttributeInfoCore(transaction, pathLp, ref attrs, false, true); + + 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; + } - if (IsDirectory(attrs.dwFileAttributes)) - // MSDN: .NET 3.5+: UnauthorizedAccessException: Path is a directory. - throw new UnauthorizedAccessException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", - Win32Errors.ERROR_INVALID_PARAMETER, string.Format(CultureInfo.InvariantCulture, Resources.Target_File_Is_A_Directory, pathLp))); + // 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 (IsReadOnly(attrs.dwFileAttributes)) + if (IsReadOnlyOrHidden(attributes)) { if (ignoreReadOnly) { @@ -109,7 +128,7 @@ internal static void DeleteFileCore(KernelTransaction transaction, string path, // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission. - if (dataInitialised == Win32Errors.ERROR_SUCCESS) + if (attributes == 0) NativeError.ThrowException(lastError, pathLp); break; @@ -119,7 +138,7 @@ internal static void DeleteFileCore(KernelTransaction transaction, string path, // 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, pathLp); + NativeError.ThrowException(lastError, IsDirectory(attributes), pathLp); } } } diff --git a/AlphaFS/Filesystem/File Class/File Core Methods/File.EncryptDecryptFileCore.cs b/AlphaFS/Filesystem/File Class/File Core Methods/File.EncryptDecryptFileCore.cs index bc818924e..bca0d6c08 100644 --- a/AlphaFS/Filesystem/File Class/File Core Methods/File.EncryptDecryptFileCore.cs +++ b/AlphaFS/Filesystem/File Class/File Core Methods/File.EncryptDecryptFileCore.cs @@ -55,12 +55,17 @@ internal static void EncryptDecryptFileCore(bool isFolder, string path, bool enc var attrs = GetAttributesExCore(null, path, pathFormat, true); var isReadOnly = IsReadOnly(attrs.dwFileAttributes); + var isHidden = IsHidden(attrs.dwFileAttributes); - if (isReadOnly) + if (isReadOnly || isHidden) { - var fileAttr = attrs.dwFileAttributes &= ~FileAttributes.ReadOnly; // Remove ReadOnly attribute.. + if (isReadOnly) + attrs.dwFileAttributes &= ~FileAttributes.ReadOnly; - SetAttributesCore(null, isFolder, path, fileAttr, pathFormat); + if (isHidden) + attrs.dwFileAttributes &= ~FileAttributes.Hidden; + + SetAttributesCore(null, isFolder, path, attrs.dwFileAttributes, pathFormat); } @@ -68,22 +73,18 @@ internal static void EncryptDecryptFileCore(bool isFolder, string path, bool enc // 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) + if (isReadOnly || isHidden) { - var isHidden = IsHidden(attrs.dwFileAttributes); - - // Get most current attributes. - attrs = GetAttributesExCore(null, path, pathFormat, true); - - attrs.dwFileAttributes |= FileAttributes.ReadOnly; + if (isReadOnly) + attrs.dwFileAttributes |= FileAttributes.ReadOnly; if (isHidden) attrs.dwFileAttributes |= FileAttributes.Hidden; - SetAttributesCore(null, isFolder, path, attrs.dwFileAttributes, pathFormat); } @@ -103,7 +104,7 @@ internal static void EncryptDecryptFileCore(bool isFolder, string path, bool enc case Win32Errors.ERROR_FILE_READ_ONLY: - if (IsDirectory(attrs.dwFileAttributes)) + if (isFolder) throw new DirectoryReadOnlyException(path); else diff --git a/AlphaFS/Filesystem/File Class/File Core Methods/File.SetFsoDateTimeCore.cs b/AlphaFS/Filesystem/File Class/File Core Methods/File.SetFsoDateTimeCore.cs index f07ce13b4..2a1defd72 100644 --- a/AlphaFS/Filesystem/File Class/File Core Methods/File.SetFsoDateTimeCore.cs +++ b/AlphaFS/Filesystem/File Class/File Core Methods/File.SetFsoDateTimeCore.cs @@ -52,15 +52,15 @@ internal static void SetFsoDateTimeCore(KernelTransaction transaction, bool isFo if (modifyReparsePoint) eaAttributes |= ExtendedFileAttributes.OpenReparsePoint; - - // TODO 2018-07-11 - //// Prevent a System.UnauthorizedAccessException from being thrown. + //// 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.Normal, PathFormat.LongFullPath); + // SetAttributesCore(transaction, isFolder, path, fileAttributes, PathFormat.LongFullPath); using (var creationTime = SafeGlobalMemoryBufferHandle.FromLong(creationTimeUtc.HasValue ? creationTimeUtc.Value.ToFileTimeUtc() : (long?) null)) @@ -81,16 +81,15 @@ internal static void SetFsoDateTimeCore(KernelTransaction transaction, bool isFo { //if (isReadOnly || isHidden) //{ - // var fileAttributes = FileAttributes.Normal; - // if (isReadOnly) // fileAttributes |= FileAttributes.ReadOnly; // if (isHidden) // fileAttributes |= FileAttributes.Hidden; - // if (fileAttributes != FileAttributes.Normal) - // SetAttributesCore(transaction, isFolder, path, fileAttributes, PathFormat.LongFullPath); + // fileAttributes &= ~FileAttributes.Normal; + + // SetAttributesCore(transaction, isFolder, path, fileAttributes, PathFormat.LongFullPath); //} } diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.GetChangeTimeUtc.cs b/AlphaFS/Filesystem/File Class/File Time/File.GetChangeTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.GetChangeTimeUtc.cs rename to AlphaFS/Filesystem/File Class/File Time/File.GetChangeTimeUtc.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.GetChangeTimeUtcTransacted.cs b/AlphaFS/Filesystem/File Class/File Time/File.GetChangeTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.GetChangeTimeUtcTransacted.cs rename to AlphaFS/Filesystem/File Class/File Time/File.GetChangeTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.GetCreationTimeUtc.cs b/AlphaFS/Filesystem/File Class/File Time/File.GetCreationTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.GetCreationTimeUtc.cs rename to AlphaFS/Filesystem/File Class/File Time/File.GetCreationTimeUtc.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.GetCreationTimeUtcTransacted.cs b/AlphaFS/Filesystem/File Class/File Time/File.GetCreationTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.GetCreationTimeUtcTransacted.cs rename to AlphaFS/Filesystem/File Class/File Time/File.GetCreationTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.GetLastAccessTimeUtc.cs b/AlphaFS/Filesystem/File Class/File Time/File.GetLastAccessTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.GetLastAccessTimeUtc.cs rename to AlphaFS/Filesystem/File Class/File Time/File.GetLastAccessTimeUtc.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.GetLastAccessTimeUtcTransacted.cs b/AlphaFS/Filesystem/File Class/File Time/File.GetLastAccessTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.GetLastAccessTimeUtcTransacted.cs rename to AlphaFS/Filesystem/File Class/File Time/File.GetLastAccessTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.GetLastWriteTimeUtc.cs b/AlphaFS/Filesystem/File Class/File Time/File.GetLastWriteTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.GetLastWriteTimeUtc.cs rename to AlphaFS/Filesystem/File Class/File Time/File.GetLastWriteTimeUtc.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.GetLastWriteTimeUtcTransacted.cs b/AlphaFS/Filesystem/File Class/File Time/File.GetLastWriteTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.GetLastWriteTimeUtcTransacted.cs rename to AlphaFS/Filesystem/File Class/File Time/File.GetLastWriteTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.SetCreationTimeUtc.cs b/AlphaFS/Filesystem/File Class/File Time/File.SetCreationTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.SetCreationTimeUtc.cs rename to AlphaFS/Filesystem/File Class/File Time/File.SetCreationTimeUtc.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.SetCreationTimeUtcTransacted.cs b/AlphaFS/Filesystem/File Class/File Time/File.SetCreationTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.SetCreationTimeUtcTransacted.cs rename to AlphaFS/Filesystem/File Class/File Time/File.SetCreationTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.SetLastAccessTimeUtc.cs b/AlphaFS/Filesystem/File Class/File Time/File.SetLastAccessTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.SetLastAccessTimeUtc.cs rename to AlphaFS/Filesystem/File Class/File Time/File.SetLastAccessTimeUtc.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.SetLastAccessTimeUtcTransacted.cs b/AlphaFS/Filesystem/File Class/File Time/File.SetLastAccessTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.SetLastAccessTimeUtcTransacted.cs rename to AlphaFS/Filesystem/File Class/File Time/File.SetLastAccessTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.SetLastWriteTimeUtc.cs b/AlphaFS/Filesystem/File Class/File Time/File.SetLastWriteTimeUtc.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.SetLastWriteTimeUtc.cs rename to AlphaFS/Filesystem/File Class/File Time/File.SetLastWriteTimeUtc.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.SetLastWriteTimeUtcTransacted.cs b/AlphaFS/Filesystem/File Class/File Time/File.SetLastWriteTimeUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.SetLastWriteTimeUtcTransacted.cs rename to AlphaFS/Filesystem/File Class/File Time/File.SetLastWriteTimeUtcTransacted.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.SetTimestampsUtc.cs b/AlphaFS/Filesystem/File Class/File Time/File.SetTimestampsUtc.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.SetTimestampsUtc.cs rename to AlphaFS/Filesystem/File Class/File Time/File.SetTimestampsUtc.cs diff --git a/AlphaFS/Filesystem/File Class/File Time/UTC/File.SetTimestampsUtcTransacted.cs b/AlphaFS/Filesystem/File Class/File Time/File.SetTimestampsUtcTransacted.cs similarity index 100% rename from AlphaFS/Filesystem/File Class/File Time/UTC/File.SetTimestampsUtcTransacted.cs rename to AlphaFS/Filesystem/File Class/File Time/File.SetTimestampsUtcTransacted.cs diff --git a/AlphaFS/Filesystem/File Class/File.AttributeLogic.cs b/AlphaFS/Filesystem/File Class/File.AttributeLogic.cs index de09d8401..f3c5143be 100644 --- a/AlphaFS/Filesystem/File Class/File.AttributeLogic.cs +++ b/AlphaFS/Filesystem/File Class/File.AttributeLogic.cs @@ -39,21 +39,21 @@ internal static bool IsDirectory(FileAttributes fileAttributes) } - /// Checks that the file system object is a hidden. + /// Checks that the file system object is hidden. internal static bool IsHidden(FileAttributes fileAttributes) { return HasValidAttributes(fileAttributes) && (fileAttributes & FileAttributes.Hidden) != 0; } - /// Checks that the file system object is a read-only. + /// Checks that the file system object is read-only. internal static bool IsReadOnly(FileAttributes fileAttributes) { return HasValidAttributes(fileAttributes) && (fileAttributes & FileAttributes.ReadOnly) != 0; } - /// Checks that the file system object is a read-only or hidden. + /// Checks that the file system object is read-only or hidden. internal static bool IsReadOnlyOrHidden(FileAttributes fileAttributes) { return IsReadOnly(fileAttributes) || IsHidden(fileAttributes); diff --git a/AlphaFS/Filesystem/File Class/File.Delete.cs b/AlphaFS/Filesystem/File Class/File.Delete.cs index fadc7e6ee..dcf8cb983 100644 --- a/AlphaFS/Filesystem/File Class/File.Delete.cs +++ b/AlphaFS/Filesystem/File Class/File.Delete.cs @@ -37,7 +37,7 @@ public static partial class File [SecurityCritical] public static void Delete(string path) { - DeleteFileCore(null, path, false, PathFormat.RelativePath); + DeleteFileCore(null, path, false, 0, PathFormat.RelativePath); } @@ -52,7 +52,7 @@ public static void Delete(string path) [SecurityCritical] public static void Delete(string path, PathFormat pathFormat) { - DeleteFileCore(null, path, false, pathFormat); + DeleteFileCore(null, path, false, 0, pathFormat); } @@ -67,7 +67,7 @@ public static void Delete(string path, PathFormat pathFormat) [SecurityCritical] public static void Delete(string path, bool ignoreReadOnly) { - DeleteFileCore(null, path, ignoreReadOnly, PathFormat.RelativePath); + DeleteFileCore(null, path, ignoreReadOnly, 0, PathFormat.RelativePath); } @@ -83,7 +83,7 @@ public static void Delete(string path, bool ignoreReadOnly) [SecurityCritical] public static void Delete(string path, bool ignoreReadOnly, PathFormat pathFormat) { - DeleteFileCore(null, path, ignoreReadOnly, pathFormat); + DeleteFileCore(null, path, ignoreReadOnly, 0, pathFormat); } } } diff --git a/AlphaFS/Filesystem/File Class/File.DeleteTransacted.cs b/AlphaFS/Filesystem/File Class/File.DeleteTransacted.cs index 773da55fe..5ea1c1f84 100644 --- a/AlphaFS/Filesystem/File Class/File.DeleteTransacted.cs +++ b/AlphaFS/Filesystem/File Class/File.DeleteTransacted.cs @@ -38,7 +38,7 @@ public static partial class File [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path) { - DeleteFileCore(transaction, path, false, PathFormat.RelativePath); + DeleteFileCore(transaction, path, false, 0, PathFormat.RelativePath); } @@ -54,7 +54,7 @@ public static void DeleteTransacted(KernelTransaction transaction, string path) [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { - DeleteFileCore(transaction, path, false, pathFormat); + DeleteFileCore(transaction, path, false, 0, pathFormat); } @@ -70,7 +70,7 @@ public static void DeleteTransacted(KernelTransaction transaction, string path, [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool ignoreReadOnly) { - DeleteFileCore(transaction, path, ignoreReadOnly, PathFormat.RelativePath); + DeleteFileCore(transaction, path, ignoreReadOnly, 0, PathFormat.RelativePath); } @@ -87,7 +87,7 @@ public static void DeleteTransacted(KernelTransaction transaction, string path, [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool ignoreReadOnly, PathFormat pathFormat) { - DeleteFileCore(transaction, path, ignoreReadOnly, pathFormat); + DeleteFileCore(transaction, path, ignoreReadOnly, 0, pathFormat); } } } diff --git a/AlphaFS/Filesystem/File Class/File.GetAttributes.cs b/AlphaFS/Filesystem/File Class/File.GetAttributes.cs index c913abcbc..5a9000676 100644 --- a/AlphaFS/Filesystem/File Class/File.GetAttributes.cs +++ b/AlphaFS/Filesystem/File Class/File.GetAttributes.cs @@ -104,7 +104,7 @@ internal static T GetAttributesExCore(KernelTransaction transaction, string p /// /// Calls NativeMethods.GetFileAttributesEx to retrieve WIN32_FILE_ATTRIBUTE_DATA. - /// Note that classes should use -1 as the uninitialized state for dataInitialized when relying on this method. + /// Note that classes should use -1 as the uninitialized state for dataInitialized when relying on this method. /// /// No path (null, empty string) checking or normalization is performed. /// . @@ -117,7 +117,7 @@ internal static T GetAttributesExCore(KernelTransaction transaction, string p [SecurityCritical] internal static int FillAttributeInfoCore(KernelTransaction transaction, string pathLp, ref NativeMethods.WIN32_FILE_ATTRIBUTE_DATA win32AttrData, bool tryAgain, bool returnErrorOnNotFound) { - var lastError = (int) Win32Errors.ERROR_SUCCESS; + var lastError = (int) Win32Errors.NO_ERROR; #region Try Again @@ -142,7 +142,7 @@ internal static int FillAttributeInfoCore(KernelTransaction transaction, string if (!returnErrorOnNotFound) { // Return default value for backward compatibility. - lastError = (int) Win32Errors.ERROR_SUCCESS; + lastError = (int) Win32Errors.NO_ERROR; win32AttrData.dwFileAttributes = NativeMethods.InvalidFileAttributes; } @@ -170,6 +170,7 @@ internal static int FillAttributeInfoCore(KernelTransaction transaction, string // 2013-01-13: MSDN confirms LongPath usage. ? NativeMethods.GetFileAttributesEx(pathLp, NativeMethods.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, out win32AttrData) + : NativeMethods.GetFileAttributesTransacted(pathLp, NativeMethods.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, out win32AttrData, transaction.SafeHandle))) { lastError = Marshal.GetLastWin32Error(); @@ -188,7 +189,7 @@ internal static int FillAttributeInfoCore(KernelTransaction transaction, string if (!returnErrorOnNotFound) { // Return default value for backward compatibility. - lastError = (int) Win32Errors.ERROR_SUCCESS; + lastError = (int) Win32Errors.NO_ERROR; win32AttrData.dwFileAttributes = NativeMethods.InvalidFileAttributes; } diff --git a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Delete.cs b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Delete.cs index 1d4cd8f8d..df3278447 100644 --- a/AlphaFS/Filesystem/FileInfo Class/FileInfo.Delete.cs +++ b/AlphaFS/Filesystem/FileInfo Class/FileInfo.Delete.cs @@ -33,21 +33,18 @@ partial class FileInfo /// public override void Delete() { - File.DeleteFileCore(Transaction, LongFullName, false, PathFormat.LongFullPath); + File.DeleteFileCore(Transaction, LongFullName, false, 0, PathFormat.LongFullPath); } #endregion // .NET - #region AlphaFS /// [AlphaFS] Permanently deletes a file. /// If the file does not exist, this method does nothing. /// true overrides the read only of the file. public void Delete(bool ignoreReadOnly) { - File.DeleteFileCore(Transaction, LongFullName, ignoreReadOnly, PathFormat.LongFullPath); + File.DeleteFileCore(Transaction, LongFullName, ignoreReadOnly, 0, PathFormat.LongFullPath); } - - #endregion // AlphaFS } } diff --git a/AlphaFS/Filesystem/FileSystemInfo.cs b/AlphaFS/Filesystem/FileSystemInfo.cs index dd496b8e7..050f3f2f9 100644 --- a/AlphaFS/Filesystem/FileSystemInfo.cs +++ b/AlphaFS/Filesystem/FileSystemInfo.cs @@ -88,12 +88,14 @@ public FileAttributes Attributes } // MSDN: .NET 3.5+: IOException: Refresh cannot initialize the data. + if (DataInitialised != 0) NativeError.ThrowException(DataInitialised, FullPath); return Win32AttributeData.dwFileAttributes; } + [SecurityCritical] set { @@ -120,10 +122,9 @@ public FileAttributes Attributes /// public DateTime CreationTime { - [SecurityCritical] - get { return CreationTimeUtc.ToLocalTime(); } - [SecurityCritical] - set { CreationTimeUtc = value.ToUniversalTime(); } + [SecurityCritical] get { return CreationTimeUtc.ToLocalTime(); } + + [SecurityCritical] set { CreationTimeUtc = value.ToUniversalTime(); } } @@ -163,18 +164,18 @@ public DateTime CreationTimeUtc return DateTime.FromFileTimeUtc(Win32AttributeData.ftCreationTime); } + [SecurityCritical] set { - File.SetFsoDateTimeCore(Transaction, false, LongFullName, value, null, null, false, PathFormat.LongFullPath); + File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, value, null, null, false, PathFormat.LongFullPath); + Reset(); } } - /// - /// Gets a value indicating whether the file or directory exists. - /// + /// Gets a value indicating whether the file or directory exists. /// /// The property returns false if any error occurs while trying to determine if the /// specified file or directory exists. @@ -186,12 +187,10 @@ public DateTime CreationTimeUtc public abstract bool Exists { get; } - /// - /// Gets the string representing the extension part of the file. - /// + /// Gets the string representing the extension part of the file. /// - /// The Extension property returns the extension, including the period (.). - /// For example, for a file c:\NewFile.txt, this property returns ".txt". + /// The Extension property returns the extension, including the period (.). + /// For example, for a file c:\NewFile.txt, this property returns ".txt". /// /// A string containing the extension. public string Extension @@ -200,17 +199,14 @@ public string Extension } - /// - /// Gets the full path of the directory or file. - /// + /// Gets the full path of the directory or file. /// A string containing the full path. public virtual string FullName { - [SecurityCritical] - get { return FullPath; } + [SecurityCritical] get { return FullPath; } } - + /// Gets or sets the time the current file or directory was last accessed. /// /// The value of the LastAccessTime property is pre-cached @@ -225,11 +221,9 @@ public virtual string FullName /// public DateTime LastAccessTime { - [SecurityCritical] - get { return LastAccessTimeUtc.ToLocalTime(); } + [SecurityCritical] get { return LastAccessTimeUtc.ToLocalTime(); } - [SecurityCritical] - set { LastAccessTimeUtc = value.ToUniversalTime(); } + [SecurityCritical] set { LastAccessTimeUtc = value.ToUniversalTime(); } } @@ -264,10 +258,12 @@ public DateTime LastAccessTimeUtc return DateTime.FromFileTimeUtc(Win32AttributeData.ftLastAccessTime); } + [SecurityCritical] set { - File.SetFsoDateTimeCore(Transaction, false, LongFullName, null, value, null, false, PathFormat.LongFullPath); + File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, null, value, null, false, PathFormat.LongFullPath); + Reset(); } } @@ -288,6 +284,7 @@ public DateTime LastAccessTimeUtc public DateTime LastWriteTime { get { return LastWriteTimeUtc.ToLocalTime(); } + set { LastWriteTimeUtc = value.ToUniversalTime(); } } @@ -320,10 +317,12 @@ public DateTime LastWriteTimeUtc return DateTime.FromFileTimeUtc(Win32AttributeData.ftLastWriteTime); } + [SecurityCritical] set { - File.SetFsoDateTimeCore(Transaction, false, LongFullName, null, null, value, false, PathFormat.LongFullPath); + File.SetFsoDateTimeCore(Transaction, IsDirectory, LongFullName, null, null, value, false, PathFormat.LongFullPath); + Reset(); } } @@ -354,6 +353,7 @@ public DateTime LastWriteTimeUtc private FileSystemEntryInfo _entryInfo; + /// [AlphaFS] Gets the instance of the class. public FileSystemEntryInfo EntryInfo { @@ -373,6 +373,7 @@ public FileSystemEntryInfo EntryInfo return _entryInfo; } + internal set { _entryInfo = value; @@ -438,7 +439,7 @@ public override string ToString() // "Alphaleonis.Win32.Filesystem.FileSystemInfo" return GetType().ToString(); } - + /// Serves as a hash function for a particular type. /// A hash code for the current Object. @@ -496,15 +497,15 @@ public override bool Equals(object obj) #endregion // .NET - #region AlphaFS - /// [AlphaFS] Refreshes the current instance ( or ) with a new destination path. 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. @@ -512,7 +513,7 @@ internal void UpdateSourcePath(string destinationPath, string destinationPathLp) } - /// Refreshes the state of the EntryInfo property. + /// [AlphaFS] Refreshes the state of the EntryInfo property. /// /// FileSystemInfo.RefreshEntryInfo() takes a snapshot of the file from the current file system. /// Refresh cannot correct the underlying file system even if the file system returns incorrect or outdated information. @@ -555,31 +556,31 @@ internal void InitializeCore(KernelTransaction transaction, bool isFolder, strin 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; + 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 = transaction == null || !NativeMethods.IsAtLeastWindowsVista + 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(); @@ -591,8 +592,6 @@ internal static SafeFindFileHandle FindFirstFileNative(KernelTransaction transac return safeHandle; } - #endregion // AlphaFS - #endregion // Methods } } diff --git a/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs b/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs index 9c089e5cf..c9ddb3a33 100644 --- a/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs +++ b/AlphaFS/Filesystem/FindFileSystemEntryInfo.cs @@ -312,13 +312,17 @@ private FileSystemEntryInfo NewFilesystemEntry(string pathLp, string fileName, N private T NewFileSystemEntryType(bool isFolder, FileSystemEntryInfo fsei, string fileName, string pathLp, NativeMethods.WIN32_FIND_DATA win32FindData) { - // Determine yield, e.g. do not return files when only folders are requested and vice versa. + // 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; @@ -328,10 +332,7 @@ private T NewFileSystemEntryType(bool isFolder, FileSystemEntryInfo fsei, str // 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 + 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. @@ -410,8 +411,7 @@ private void VerifyInstanceType(NativeMethods.WIN32_FIND_DATA win32FindData) { var regularPath = Path.GetCleanExceptionPath(InputPath); - var isFolder = (win32FindData.dwFileAttributes & FileAttributes.Directory) != 0; - + var isFolder = File.IsDirectory(win32FindData.dwFileAttributes); if (IsDirectory) { @@ -444,8 +444,8 @@ public IEnumerable Enumerate() using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) - while ( - dirs.Count > 0 + + while (dirs.Count > 0 #if !NET35 && !CancellationToken.IsCancellationRequested #endif @@ -499,7 +499,7 @@ public IEnumerable Enumerate() if (Equals(res, default(T))) continue; - + yield return res; @@ -520,7 +520,7 @@ public IEnumerable Enumerate() #endif ) - ThrowPossibleException((uint) lastError, pathLp); + ThrowPossibleException((uint)lastError, pathLp); } } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 4145c77f3..721b33a3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ Version 2.3 (2018-XX-XX) - Issue #471: Add overloaded method `Directory.CountFileSystemObjects` supporting `DirectoryEnumerationFilters`. - Issue #472: Add method `DirectoryInfo.ExistsJunction`. - Issue #473: Change AlphaFS implementations of method `File.Copy` to return `CopyMoveResult` instance instead of `void`. +- Issue #475: Prevent `File.SetFsoDateTimeCore` from throwing `UnauthorizedAccessException`. - Added missing overloaded methods regarding timestamps and symbolic links. - Marked `Directory.Copy`/`DirectoryInfo.Copy` methods using parameters `overwrite` and `preserveDates` as obsolete. Use one of the `CopyOptions`. - Fixed a `Directory.Move` unit test creating endless drive mappings on error.