Пример #1
0
 /// <summary>
 /// Closes a HID device handle.
 /// </summary>
 /// <param name="handle">The handle of the device to be freed.</param>
 /// <remarks></remarks>
 public static void CloseHid(IntPtr handle)
 {
     if (handle != (IntPtr)(-1) && handle != IntPtr.Zero)
     {
         User32.CloseHandle(handle);
     }
 }
Пример #2
0
        /// <summary>
        /// Set the file time stamps to the specified times.
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="CreationTime"></param>
        /// <param name="LastAccessTime"></param>
        /// <param name="LastWriteTime"></param>
        /// <remarks></remarks>
        public static void SetFileTime(string FileName, FILETIME CreationTime, FILETIME LastAccessTime, FILETIME LastWriteTime)
        {
            IntPtr hFile;

            if (Directory.Exists(FileName))
            {
                hFile = IO.CreateFile(FileName, IO.FILE_WRITE_ATTRIBUTES, 0, IntPtr.Zero, IO.OPEN_EXISTING, IO.FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);
            }
            else if (File.Exists(FileName))
            {
                hFile = IO.CreateFile(FileName, IO.FILE_WRITE_ATTRIBUTES, 0, IntPtr.Zero, IO.OPEN_EXISTING, 0, IntPtr.Zero);
            }
            else
            {
                return;
            }

            if ((long)hFile == -1L)
            {
                int g = User32.GetLastError();
                return;
            }

            try
            {
                IO.pSetFileTime2(hFile, ref CreationTime, ref LastAccessTime, ref LastWriteTime);
            }
            catch
            {
                // MsgBox(ex.Message)
            }

            User32.CloseHandle(hFile);
        }
Пример #3
0
 /// <summary>
 /// Internally performs the actions necessary to close the file handle to the associated folder.
 /// </summary>
 /// <remarks></remarks>
 protected void internalCloseFile()
 {
     if (User32.CloseHandle(_hFile))
     {
         _hFile = IntPtr.Zero;
     }
 }
Пример #4
0
        /// <summary>
        /// Get volume disk extents for volumes that may or may not span more than one physical drive.
        /// </summary>
        /// <param name="devicePath">The device path of the volume.</param>
        /// <returns>An array of DiskExtent structures.</returns>
        /// <remarks></remarks>
        public static DiskExtent[] GetDiskExtentsFor(string devicePath)
        {
            DiskExtent[] deOut  = null;
            MemPtr       inBuff = new MemPtr();
            int          inSize;
            IntPtr       file;
            int          h  = 0;
            var          de = new DISK_EXTENT();
            var          ve = new VOLUME_DISK_EXTENTS();
            bool         r;

            file = IO.CreateFile(devicePath, IO.GENERIC_READ, IO.FILE_SHARE_READ | IO.FILE_SHARE_WRITE, IntPtr.Zero, IO.OPEN_EXISTING, IO.FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
            if (file == DevProp.INVALID_HANDLE_VALUE)
            {
                return(null);
            }

            uint arb = 0;

            inSize        = Marshal.SizeOf(de) + Marshal.SizeOf(ve);
            inBuff.Length = inSize;
            r             = DeviceIoControl(file, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, inBuff, (uint)inSize, ref arb, IntPtr.Zero);

            if (!r && User32.GetLastError() == ERROR_MORE_DATA)
            {
                inBuff.Length = inSize * inBuff.IntAt(0L);
                r             = DeviceIoControl(file, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, inBuff, (uint)inSize, ref arb, IntPtr.Zero);
            }

            if (!r)
            {
                inBuff.Free();
                User32.CloseHandle(file);
                return(null);
            }

            User32.CloseHandle(file);
            ve = VOLUME_DISK_EXTENTS.FromPtr(inBuff);
            inBuff.Free();
            h     = 0;
            deOut = new DiskExtent[ve.Extents.Length];
            foreach (var currentDe in ve.Extents)
            {
                de = currentDe;
                deOut[h].PhysicalDevice = de.DiskNumber;
                deOut[h].Space          = de.Space;
                deOut[h].Size           = de.ExtentLength;
                deOut[h].Offset         = de.StartingOffset;
                h += 1;
            }

            return(deOut);
        }
Пример #5
0
        /// <summary>
        /// Retrieves a feature from the device.
        /// </summary>
        /// <param name="device"></param>
        /// <param name="code"></param>
        /// <param name="datalen"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static HIDFeatureResult GetHIDFeature(HidDeviceInfo device, int code, int datalen = 16)
        {
            HIDFeatureResult GetHIDFeatureRet = default;
            IntPtr           hFile;

            hFile = IO.CreateFile(device.DevicePath, IO.GENERIC_READ, IO.FILE_SHARE_READ | IO.FILE_SHARE_WRITE, IntPtr.Zero, IO.OPEN_EXISTING, IO.FILE_ATTRIBUTE_NORMAL, default);
            if (hFile == IntPtr.Zero)
            {
                return(null);
            }
            GetHIDFeatureRet = GetHIDFeature(hFile, code, datalen);
            User32.CloseHandle(hFile);
            return(GetHIDFeatureRet);
        }
Пример #6
0
        /// <summary>
        /// Close the disk instance.
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        public bool Close()
        {
            if (_Handle == IntPtr.Zero)
            {
                return(false);
            }

            bool r = User32.CloseHandle(_Handle);

            if (r)
            {
                _Handle = IntPtr.Zero;
            }

            return(r);
        }
Пример #7
0
        // Get the size of a file

        /// <summary>
        /// Returns the file size in the style of the native function, with a high DWORD and a low DWORD.
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="lpSizeHigh"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static uint GetFileSize(string FileName, ref uint lpSizeHigh)
        {
            IntPtr hFile;
            uint   SL;
            var    lpSh = default(uint);

            if (!FileExists(FileName))
            {
                return(0U);
            }
            hFile = IO.CreateFile(FileName, IO.GENERIC_READ, 0, IntPtr.Zero, IO.OPEN_EXISTING, 0, IntPtr.Zero);
            if ((long)hFile == -1L)
            {
                return(0U);
            }
            SL         = IO.pGetFileSize(hFile, ref lpSh);
            lpSizeHigh = lpSh;
            User32.CloseHandle(hFile);
            return(SL);
        }
Пример #8
0
        private bool IsPathOfExileRunAsAdmin()
        {
            var result = false;

            try
            {
                User32.GetWindowThreadProcessId(User32.GetForegroundWindow(), out var processID);
                var proc = Process.GetProcessById(processID);

                User32.OpenProcessToken(proc.Handle, TOKEN_ALL_ACCESS, out var ph);
                using (var iden = new WindowsIdentity(ph))
                {
                    foreach (var role in iden.Groups)
                    {
                        if (role.IsValidTargetType(typeof(SecurityIdentifier)))
                        {
                            var sid = role as SecurityIdentifier;

                            if (sid.IsWellKnown(WellKnownSidType.AccountAdministratorSid) || sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid))
                            {
                                result = true;
                                break;
                            }
                        }
                    }

                    User32.CloseHandle(ph);
                }

                return(result);
            }
            catch (Exception e)
            {
                logger.LogWarning(e, e.Message);
            }

            return(result);
        }
Пример #9
0
        /// <summary>
        /// Retrieve the partition table of a GPT-layout disk, manually.
        /// Must be Administrator.
        /// </summary>
        /// <param name="inf">DiskDeviceInfo object to the physical disk to read.</param>
        /// <param name="gptInfo">Receives the drive layout information.</param>
        /// <returns>True if successful.</returns>
        /// <remarks></remarks>
        public static bool ReadRawGptDisk(string devicePath, ref RAW_GPT_DISK gptInfo)
        {
            // Demand Administrator for accessing a raw disk.
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            // Dim principalPerm As New PrincipalPermission(Nothing, "Administrators")
            // principalPerm.Demand()


            var hfile = IO.CreateFile(devicePath, IO.GENERIC_READ | IO.GENERIC_WRITE, IO.FILE_SHARE_READ | IO.FILE_SHARE_WRITE, IntPtr.Zero, IO.OPEN_EXISTING, IO.FILE_FLAG_NO_BUFFERING | IO.FILE_FLAG_RANDOM_ACCESS, IntPtr.Zero);

            if (hfile == DevProp.INVALID_HANDLE_VALUE)
            {
                return(false);
            }
            DISK_GEOMETRY_EX geo = default;

            // get the disk geometry to retrieve the sector (LBA) size.
            if (!DiskGeometry(hfile, ref geo))
            {
                User32.CloseHandle(hfile);
                return(false);
            }

            // sector size (usually 512 bytes)
            uint bps = geo.Geometry.BytesPerSector;
            uint br  = 0U;
            long lp  = 0L;
            long lp2 = 0L;
            var  mm  = new MemPtr(bps * 2L);

            IO.SetFilePointerEx(hfile, 0L, ref lp, IO.FilePointerMoveMethod.Begin);
            IO.ReadFile(hfile, mm.Handle, bps * 2, ref br, IntPtr.Zero);
            var mbr = new RAW_MBR();
            var gpt = new RAW_GPT_HEADER();

            RAW_GPT_PARTITION[] gpp = null;

            // read the master boot record.
            mbr = mm.ToStructAt <RAW_MBR>(446L);

            // read the GPT structure header.
            gpt = mm.ToStructAt <RAW_GPT_HEADER>(bps);

            // check the partition header CRC.
            if (gpt.IsValid)
            {
                long lr = br;

                // seek to the LBA of the partition information.
                IO.SetFilePointerEx(hfile, (uint)(bps * gpt.PartitionEntryLBA), ref lr, IO.FilePointerMoveMethod.Begin);
                br = (uint)lr;

                // calculate the size of the partition table buffer.
                lp = gpt.NumberOfPartitions * gpt.PartitionEntryLength;

                // byte align to the sector size.
                if (lp % bps != 0L)
                {
                    lp += bps - lp % bps;
                }

                // bump up the memory pointer.
                mm.ReAlloc(lp);
                mm.ZeroMemory();

                // read the partition information into the pointer.
                IO.ReadFile(hfile, mm.Handle, (uint)lp, ref br, IntPtr.Zero);

                // check the partition table CRC.
                if (mm.CalculateCrc32() == gpt.PartitionArrayCRC32)
                {
                    // disk is valid.

                    lp = (uint)Marshal.SizeOf <RAW_GPT_PARTITION>();
                    br = 0U;
                    int i;
                    int c = (int)gpt.NumberOfPartitions;

                    gpp = new RAW_GPT_PARTITION[c + 1];

                    // populate the drive information.
                    for (i = 0; i < c; i++)
                    {
                        gpp[i] = mm.ToStructAt <RAW_GPT_PARTITION>(lp2);

                        // break on empty GUID, we are past the last partition.
                        if (gpp[i].PartitionTypeGuid == Guid.Empty)
                        {
                            break;
                        }
                        lp2 += lp;
                    }

                    // trim off excess records from the array.
                    if (i < c)
                    {
                        if (i == 0)
                        {
                            gpp = Array.Empty <RAW_GPT_PARTITION>();
                        }
                        else
                        {
                            Array.Resize(ref gpp, i);
                        }
                    }
                }
            }

            // free the resources.
            mm.Free();
            User32.CloseHandle(hfile);

            // if gpp is nothing then some error occurred somewhere and we did not succeed.
            if (gpp is null)
            {
                return(false);
            }

            // create a new RAW_GPT_DISK structure.
            gptInfo            = new RAW_GPT_DISK();
            gptInfo.Header     = gpt;
            gptInfo.Partitions = gpp;

            // we have succeeded.
            return(true);
        }