示例#1
0
        /// <summary>
        /// Return the username for the current user
        /// </summary>
        /// <returns></returns>
        public static string CurrentUserName()
        {
            string CurrentUserNameRet = default;
            MemPtr lps = new MemPtr();
            int    cb  = 10240;

            lps.ReAlloc(10240L);
            lps.ZeroMemory();
            if (GetUserName(lps.Handle, ref cb))
            {
                CurrentUserNameRet = lps.ToString();
            }
            else
            {
                CurrentUserNameRet = null;
            }

            lps.Free();
            return(CurrentUserNameRet);
        }
示例#2
0
        /// <summary>
        /// Return the current user's full display name
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string CurrentUserFullName(ExtendedNameFormat type = ExtendedNameFormat.NameDisplay)
        {
            string CurrentUserFullNameRet = default;
            MemPtr lps;
            int    cb = 10240;

            lps = new MemPtr(10240L);
            lps.ZeroMemory();

            if (GetUserNameEx(type, lps.Handle, ref cb))
            {
                CurrentUserFullNameRet = lps.ToString();
            }
            else
            {
                CurrentUserFullNameRet = null;
            }

            lps.Free();
            return(CurrentUserFullNameRet);
        }
示例#3
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);
        }
示例#4
0
        /// <summary>
        /// Refresh the contents of the directory.
        /// </summary>
        public void Refresh(StandardIcons?iconSize = default)
        {
            if (iconSize is null)
            {
                iconSize = _IconSize;
            }

            _Children.Clear();
            _Folders.Clear();

            FileObject      fobj;
            DirectoryObject dobj;
            IShellItem      shitem = null;
            IShellFolder    shfld;
            IEnumIDList     enumer;

            MemPtr mm;
            var    mm2 = new MemPtr();

            string fp;

            string pname = ParsingName;

            if (pname is object && pname.LastIndexOf(@"\") == pname.Length - 1)
            {
                pname = pname.Substring(0, pname.Length - 1);
            }

            var argriid = Guid.Parse(ShellIIDGuid.IShellItem);
            var res     = NativeShell.SHCreateItemFromParsingName(ParsingName, IntPtr.Zero, ref argriid, ref shitem);

            _IconSize = (StandardIcons)iconSize;

            int?argiIndex = null;

            _Icon      = Resources.GetFileIcon(ParsingName, FileObject.StandardToSystem(_IconSize), iIndex: ref argiIndex);
            _IconImage = Resources.GetFileIconWPF(ParsingName, FileObject.StandardToSystem(_IconSize));

            if (res == HResult.Ok)
            {
                var argbhid  = Guid.Parse(ShellBHIDGuid.ShellFolderObject);
                var argriid1 = Guid.Parse(ShellIIDGuid.IShellFolder2);

                shitem.BindToHandler(IntPtr.Zero, ref argbhid, ref argriid1, out shfld);
                _SysInterface = shfld;

                shfld.EnumObjects(IntPtr.Zero, ShellFolderEnumerationOptions.Folders | ShellFolderEnumerationOptions.IncludeHidden | ShellFolderEnumerationOptions.NonFolders | ShellFolderEnumerationOptions.InitializeOnFirstNext, out enumer);

                if (enumer != null)
                {
                    var    glist = new List <string>();
                    uint   cf;
                    var    x = IntPtr.Zero;
                    string pout;

                    // mm.AllocCoTaskMem((MAX_PATH * 2) + 8)

                    mm2.Alloc(NativeShell.MAX_PATH * 2 + 8);

                    do
                    {
                        cf = 0U;
                        mm2.ZeroMemory(0L, NativeShell.MAX_PATH * 2 + 8);
                        res = enumer.Next(1U, out x, out cf);
                        mm  = x;

                        if (cf == 0L)
                        {
                            break;
                        }

                        if (res != HResult.Ok)
                        {
                            break;
                        }

                        mm2.IntAt(0L) = 2;

                        // shfld.GetAttributesOf(1, mm, attr)
                        shfld.GetDisplayNameOf(mm, (uint)ShellItemDesignNameOptions.ParentRelativeParsing, mm2.handle);
                        MemPtr inv;

                        if (IntPtr.Size == 4)
                        {
                            inv = (IntPtr)mm2.IntAt(1L);
                        }
                        else
                        {
                            inv = (IntPtr)mm2.LongAt(1L);
                        }

                        if (inv.Handle != IntPtr.Zero)
                        {
                            if (inv.CharAt(0L) != '\0')
                            {
                                fp = (string)inv;
                                var lpInfo = new SHFILEINFO();

                                // Dim sgfin As ShellFileGetAttributesOptions = 0,
                                // sgfout As ShellFileGetAttributesOptions = 0

                                int iFlags = User32.SHGFI_PIDL | User32.SHGFI_ATTRIBUTES;
                                lpInfo.dwAttributes = 0;
                                x = User32.SHGetItemInfo(mm.Handle, 0, ref lpInfo, Marshal.SizeOf(lpInfo), iFlags);
                                if (ParsingName is object)
                                {
                                    if (pname.LastIndexOf(@"\") == pname.Length - 1)
                                    {
                                        pname = pname.Substring(0, pname.Length - 1);
                                    }
                                    pout = $@"{pname}\{fp}";
                                }
                                else
                                {
                                    pout = fp;
                                }

                                if (lpInfo.dwAttributes == 0)
                                {
                                    lpInfo.dwAttributes = (int)FileTools.GetFileAttributes(pout);
                                }

                                FileAttributes drat = (FileAttributes)(int)(lpInfo.dwAttributes);
                                if ((lpInfo.dwAttributes & (int)FileAttributes.Directory) == (int)FileAttributes.Directory && !File.Exists(pout))
                                {
                                    dobj          = new DirectoryObject(pout, _IsSpecial, false);
                                    dobj.Parent   = this;
                                    dobj.IconSize = _IconSize;
                                    _Children.Add(dobj);
                                    _Folders.Add(dobj);
                                }
                                else
                                {
                                    fobj          = new FileObject(pout, _IsSpecial, true, _IconSize);
                                    fobj.Parent   = this;
                                    fobj.IconSize = _IconSize;
                                    _Children.Add(fobj);
                                }
                            }

                            inv.CoTaskMemFree();
                        }

                        mm.CoTaskMemFree();
                    }while (res == HResult.Ok);
                    mm2.Free();
                }
            }

            OnPropertyChanged(nameof(Folders));
            OnPropertyChanged(nameof(Icon));
            OnPropertyChanged(nameof(IconImage));
            OnPropertyChanged(nameof(IconSize));
            OnPropertyChanged(nameof(ParsingName));
            OnPropertyChanged(nameof(DisplayName));
        }
示例#5
0
        /// <summary>
        /// Internally creates and starts the monitor thread.
        /// </summary>
        /// <returns>
        /// True if the thread was successfully created.
        /// To ensure the monitor was successfully activated, handle the MonitorOpened event.
        /// </returns>
        /// <remarks></remarks>
        protected bool internalWatch()
        {
            int blen    = 0;
            int bufflen = (int)_Buff.Size;
            var tbuff   = _Buff.Handle;

            if (_thread is object)
            {
                return(false);
            }
            if (!internalOpenFile())
            {
                return(false);
            }
            FILE_NOTIFY_INFORMATION fn;

            fn.ptr  = _Buff;
            _thread = new System.Threading.Thread(() =>
            {
                var notice = IntPtr.Zero;
                User32.PostMessage(Handle, FileSystemMonitor.WM_SIGNAL_OPEN, IntPtr.Zero, IntPtr.Zero);
                do
                {
                    try
                    {
                        // let's clean up the memory before the next execute.
                        if (blen > 0)
                        {
                            _Buff.ZeroMemory(0L, blen);
                            blen = 0;
                        }

                        if (!FileSystemMonitor.ReadDirectoryChangesW(_hFile, tbuff, bufflen, true, _Filter, ref blen, IntPtr.Zero, IntPtr.Zero))
                        {
                            notice = (IntPtr)User32.GetLastError();
                            break;
                        }
                    }
                    catch (System.Threading.ThreadAbortException)
                    {
                        break;
                    }
                    catch (Exception)
                    {
                        notice = (IntPtr)1;
                        break;
                    }

                    // block until the lock is acquired.  Hopefully the
                    // UI thread will not take that long to clean the list.
                    System.Threading.Monitor.Enter(_WaitList);
                    _WaitList.Add(FSMonitorEventArgs.FromPtr(fn, this));
                    // and we're done ...
                    System.Threading.Monitor.Exit(_WaitList);

                    // post to the UI thread that there are items to dequeue and continue!
                    User32.PostMessage(Handle, FileSystemMonitor.WM_SIGNAL, IntPtr.Zero, IntPtr.Zero);
                }while (true);
                _thread = null;
                User32.PostMessage(Handle, FileSystemMonitor.WM_SIGNAL_CLOSE, IntPtr.Zero, IntPtr.Zero);
            });

            _thread.SetApartmentState(System.Threading.ApartmentState.STA);
            _thread.IsBackground = true;

            _thread.Start();

            return(true);
        }