Ejemplo n.º 1
0
        public static bool Delete(string Path)
        {
            try
            {
                if (File.Exists(Path))
                {
                    File.Delete(Path);
                }
                else if (Directory.Exists(Path))
                {
                    Directory.Delete(Path, true);
                }
                else
                {
                    return(false);
                }

                string ExtraInfoFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Path), System.IO.Path.GetFileName(Path).Replace("$R", "$I"));

                if (File.Exists(ExtraInfoFilePath))
                {
                    File.Delete(ExtraInfoFilePath);
                }

                return(true);
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"An exception was threw in {nameof(Delete)}");
                return(false);
            }
        }
Ejemplo n.º 2
0
 public static bool EmptyRecycleBin()
 {
     try
     {
         RecycleBin.Empty(false);
         return(true);
     }
     catch (Exception ex)
     {
         LogTracer.Log(ex, $"An exception was threw in {nameof(EmptyRecycleBin)}");
         return(false);
     }
 }
Ejemplo n.º 3
0
        public static string GetMIMEFromPath(string Path)
        {
            if (!File.Exists(Path))
            {
                throw new FileNotFoundException($"\"{Path}\" not found");
            }

            byte[] Buffer = new byte[256];

            using (FileStream Stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
            {
                Stream.Read(Buffer, 0, 256);
            }

            IntPtr Pointer = Marshal.AllocHGlobal(256);

            try
            {
                Marshal.Copy(Buffer, 0, Pointer, 256);

                if (UrlMon.FindMimeFromData(null, null, Pointer, 256, null, UrlMon.FMFD.FMFD_DEFAULT, out string MIMEResult) == HRESULT.S_OK)
                {
                    return(MIMEResult);
                }
                else
                {
                    MimeType MIME = new MimeTypes().GetMimeTypeFromFile(Path);

                    if (MIME != null)
                    {
                        return(MIME.Name);
                    }
                    else
                    {
                        return("unknown/unknown");
                    }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"An exception was threw in {nameof(GetMIMEFromPath)}");
                return("unknown/unknown");
            }
            finally
            {
                Marshal.FreeHGlobal(Pointer);
            }
        }
Ejemplo n.º 4
0
        public static bool EjectDevice(string Path)
        {
            if (string.IsNullOrEmpty(Path) || string.IsNullOrEmpty(System.IO.Path.GetPathRoot(Path)))
            {
                throw new ArgumentNullException(nameof(Path), "Argument is not legal");
            }

            try
            {
                int DeviceNumber = 0;

                using (Kernel32.SafeHFILE hVolume = Kernel32.CreateFile($@"\\.\{Path.Substring(0, 2)}", 0, FileShare.ReadWrite, null, FileMode.Open, FileFlagsAndAttributes.SECURITY_ANONYMOUS))
                {
                    if (hVolume.IsNull || hVolume.IsInvalid)
                    {
                        return(false);
                    }

                    DeviceNumber = GetDeviceNumber(hVolume);
                }

                if (DeviceNumber >= 0)
                {
                    uint DevInst = GetDrivesDevInstByDeviceNumber(DeviceNumber, Kernel32.GetDriveType(Path));

                    if (DevInst == 0)
                    {
                        return(false);
                    }

                    if (CfgMgr32.CM_Get_Parent(out uint DevInstParent, DevInst) == CfgMgr32.CONFIGRET.CR_SUCCESS)
                    {
                        for (int i = 0; i < 5; i++)
                        {
                            if (CfgMgr32.CM_Request_Device_Eject(DevInstParent, out CfgMgr32.PNP_VETO_TYPE Result, null, 0) == CfgMgr32.CONFIGRET.CR_SUCCESS)
                            {
                                return(true);
                            }
                            else
                            {
                                LogTracer.Log($"Could not reject the USB device, PNP_VETO reason: {Enum.GetName(typeof(CfgMgr32.PNP_VETO_TYPE), Result)}");
                            }

                            Thread.Sleep(300);
                        }
                    }
Ejemplo n.º 5
0
        public static bool CheckQuicklookIsAvaliable()
        {
            try
            {
                NamedPipeClientStream Client = new NamedPipeClientStream(".", PipeName, PipeDirection.Out, PipeOptions.WriteThrough);

                Client.Connect(500);

                using (StreamWriter Writer = new StreamWriter(Client))
                {
                    Writer.WriteLine($"{SwitchCommand}|");
                    Writer.Flush();
                }

                return(true);
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"An exception was threw in {nameof(CheckQuicklookIsAvaliable)}");
                return(false);
            }
        }
Ejemplo n.º 6
0
        public static Task <bool> InvokeVerbAsync(string[] RelatedPath, string Verb, int Id, bool IncludeExtensionItem)
        {
            if (RelatedPath.Length > 0)
            {
                return(Helper.ExecuteOnSTAThreadAsync(() =>
                {
                    try
                    {
                        if (Array.TrueForAll(RelatedPath, (Path) => File.Exists(Path) || Directory.Exists(Path)))
                        {
                            Shell32.IContextMenu ContextObject = GetContextMenuObject(RelatedPath);

                            using (User32.SafeHMENU Menu = User32.CreatePopupMenu())
                            {
                                if (ContextObject.QueryContextMenu(Menu, 0, 0, 0x7FFF, (IncludeExtensionItem ? Shell32.CMF.CMF_EXTENDEDVERBS : Shell32.CMF.CMF_NORMAL) | Shell32.CMF.CMF_SYNCCASCADEMENU).Succeeded)
                                {
                                    if (!string.IsNullOrEmpty(Verb))
                                    {
                                        using (SafeResourceId VerbId = new SafeResourceId(Verb))
                                        {
                                            Shell32.CMINVOKECOMMANDINFOEX VerbInvokeCommand = new Shell32.CMINVOKECOMMANDINFOEX
                                            {
                                                lpVerb = VerbId,
                                                lpVerbW = Verb,
                                                nShow = ShowWindowCommand.SW_SHOWNORMAL,
                                                fMask = Shell32.CMIC.CMIC_MASK_FLAG_NO_UI | Shell32.CMIC.CMIC_MASK_UNICODE | Shell32.CMIC.CMIC_MASK_ASYNCOK,
                                                cbSize = Convert.ToUInt32(Marshal.SizeOf(typeof(Shell32.CMINVOKECOMMANDINFOEX)))
                                            };

                                            if (ContextObject.InvokeCommand(VerbInvokeCommand).Succeeded)
                                            {
                                                return true;
                                            }
                                        }
                                    }

                                    using (SafeResourceId ResSID = new SafeResourceId(Id))
                                    {
                                        Shell32.CMINVOKECOMMANDINFOEX IdInvokeCommand = new Shell32.CMINVOKECOMMANDINFOEX
                                        {
                                            lpVerb = ResSID,
                                            nShow = ShowWindowCommand.SW_SHOWNORMAL,
                                            fMask = Shell32.CMIC.CMIC_MASK_FLAG_NO_UI | Shell32.CMIC.CMIC_MASK_ASYNCOK,
                                            cbSize = Convert.ToUInt32(Marshal.SizeOf(typeof(Shell32.CMINVOKECOMMANDINFOEX)))
                                        };

                                        return ContextObject.InvokeCommand(IdInvokeCommand).Succeeded;
                                    }
                                }
                                else
                                {
                                    return false;
                                }
                            }
                        }
                        else
                        {
                            return false;
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Exception was threw when invoke the context menu item");
                        return false;
                    }
                }));
            }
            else
            {
                return(Task.FromResult(false));
            }
        }
Ejemplo n.º 7
0
        private static ContextMenuPackage[] FetchContextMenuCore(Shell32.IContextMenu Context, HMENU Menu, string[] RelatedPath, bool IncludeExtensionItem)
        {
            int MenuItemNum = User32.GetMenuItemCount(Menu);

            List <ContextMenuPackage> MenuItems = new List <ContextMenuPackage>(MenuItemNum);

            for (uint i = 0; i < MenuItemNum; i++)
            {
                IntPtr DataHandle = Marshal.AllocCoTaskMem(BufferSize);

                try
                {
                    User32.MENUITEMINFO Info = new User32.MENUITEMINFO
                    {
                        cbSize     = Convert.ToUInt32(Marshal.SizeOf(typeof(User32.MENUITEMINFO))),
                        fMask      = User32.MenuItemInfoMask.MIIM_ID | User32.MenuItemInfoMask.MIIM_SUBMENU | User32.MenuItemInfoMask.MIIM_FTYPE | User32.MenuItemInfoMask.MIIM_STRING | User32.MenuItemInfoMask.MIIM_STATE | User32.MenuItemInfoMask.MIIM_BITMAP,
                        dwTypeData = DataHandle,
                        cch        = CchMax
                    };

                    if (User32.GetMenuItemInfo(Menu, i, true, ref Info))
                    {
                        if (Info.fType.IsFlagSet(User32.MenuItemType.MFT_STRING) && !Info.fState.IsFlagSet(User32.MenuItemState.MFS_DISABLED))
                        {
                            IntPtr VerbWHandle = IntPtr.Zero;
                            IntPtr VerbAHandle = IntPtr.Zero;

                            string Verb = null;

                            try
                            {
                                VerbWHandle = Marshal.AllocCoTaskMem(BufferSize);

                                if (Context.GetCommandString(new IntPtr(Info.wID), Shell32.GCS.GCS_VERBW, IntPtr.Zero, VerbWHandle, CchMax).Succeeded)
                                {
                                    Verb = Marshal.PtrToStringUni(VerbWHandle);
                                }

                                if (string.IsNullOrEmpty(Verb))
                                {
                                    VerbAHandle = Marshal.AllocCoTaskMem(BufferSize);

                                    if (Context.GetCommandString(new IntPtr(Info.wID), Shell32.GCS.GCS_VERBA, IntPtr.Zero, VerbAHandle, CchMax).Succeeded)
                                    {
                                        Verb = Marshal.PtrToStringAnsi(VerbAHandle);
                                    }
                                }
                            }
                            catch (AccessViolationException AVE)
                            {
                                Verb = null;
                                LogTracer.Log(AVE, "Could not get verb from context menu item");
                            }
                            finally
                            {
                                if (VerbAHandle != IntPtr.Zero)
                                {
                                    Marshal.FreeCoTaskMem(VerbAHandle);
                                }

                                if (VerbWHandle != IntPtr.Zero)
                                {
                                    Marshal.FreeCoTaskMem(VerbWHandle);
                                }
                            }

                            Verb ??= string.Empty;

                            if (!VerbFilterHashSet.Contains(Verb.ToLower()))
                            {
                                try
                                {
                                    string Name = Marshal.PtrToStringUni(DataHandle);

                                    if (!string.IsNullOrEmpty(Name) && !NameFilterHashSet.Contains(Name))
                                    {
                                        ContextMenuPackage Package = new ContextMenuPackage
                                        {
                                            Name = Regex.Replace(Name, @"\(&\S*\)|&", string.Empty),
                                            Id   = Convert.ToInt32(Info.wID),
                                            Verb = Verb,
                                            IncludeExtensionItem = IncludeExtensionItem,
                                            RelatedPath          = RelatedPath
                                        };

                                        if (Info.hbmpItem != HBITMAP.NULL && ((IntPtr)Info.hbmpItem).ToInt64() != -1)
                                        {
                                            using (Bitmap OriginBitmap = Info.hbmpItem.ToBitmap())
                                            {
                                                BitmapData OriginData = OriginBitmap.LockBits(new Rectangle(0, 0, OriginBitmap.Width, OriginBitmap.Height), ImageLockMode.ReadOnly, OriginBitmap.PixelFormat);

                                                try
                                                {
                                                    using (Bitmap ArgbBitmap = new Bitmap(OriginBitmap.Width, OriginBitmap.Height, OriginData.Stride, PixelFormat.Format32bppArgb, OriginData.Scan0))
                                                        using (MemoryStream Stream = new MemoryStream())
                                                        {
                                                            ArgbBitmap.Save(Stream, ImageFormat.Png);

                                                            Package.IconData = Stream.ToArray();
                                                        }
                                                }
                                                finally
                                                {
                                                    OriginBitmap.UnlockBits(OriginData);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Package.IconData = Array.Empty <byte>();
                                        }

                                        if (Info.hSubMenu != HMENU.NULL)
                                        {
                                            Package.SubMenus = FetchContextMenuCore(Context, Info.hSubMenu, RelatedPath, IncludeExtensionItem);
                                        }
                                        else
                                        {
                                            Package.SubMenus = Array.Empty <ContextMenuPackage>();
                                        }

                                        MenuItems.Add(Package);
                                    }
                                }
                                catch
                                {
                                    continue;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "Exception was threw when fetching the context menu item");
                }
                finally
                {
                    Marshal.FreeCoTaskMem(DataHandle);
                }
            }

            return(MenuItems.ToArray());
        }
Ejemplo n.º 8
0
        private static Shell32.IContextMenu GetContextMenuObject(params string[] PathArray)
        {
            try
            {
                if (PathArray.Count() > 1)
                {
                    ShellItem[]   Items         = PathArray.Select((Path) => new ShellItem(Path)).ToArray();
                    ShellFolder[] ParentFolders = Items.Select((Item) => Item.Parent).ToArray();

                    try
                    {
                        if (ParentFolders.Skip(1).All((Folder) => Folder == ParentFolders[0]))
                        {
                            return(ParentFolders[0].GetChildrenUIObjects <Shell32.IContextMenu>(null, Items));
                        }
                        else
                        {
                            throw new ArgumentException("All items must have the same parent");
                        }
                    }
                    finally
                    {
                        Array.ForEach(Items, (It) => It.Dispose());
                        Array.ForEach(ParentFolders, (It) => It.Dispose());
                    }
                }
                else
                {
                    using (ShellItem Item = new ShellItem(PathArray.First()))
                    {
                        if (Item is ShellFolder Folder)
                        {
                            return(Folder.IShellFolder.CreateViewObject <Shell32.IContextMenu>(HWND.NULL));
                        }
                        else
                        {
                            if (Item.Parent is ShellFolder ParentFolder)
                            {
                                try
                                {
                                    return(ParentFolder.GetChildrenUIObjects <Shell32.IContextMenu>(null, Item));
                                }
                                finally
                                {
                                    ParentFolder?.Dispose();
                                }
                            }
                            else
                            {
                                return(Item.GetHandler <Shell32.IContextMenu>(Shell32.BHID.BHID_SFUIObject));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "Exception was threw when getting the context menu COM object");
                return(null);
            }
        }
Ejemplo n.º 9
0
        public static bool Restore(params string[] OriginPathList)
        {
            Dictionary <string, ShellItem> PathDic = new Dictionary <string, ShellItem>();

            try
            {
                foreach (ShellItem Item in RecycleBin.GetItems())
                {
                    if (File.Exists(Item.FileSystemPath))
                    {
                        if (Path.GetExtension(Item.Name).Equals(Item.FileInfo.Extension, StringComparison.OrdinalIgnoreCase))
                        {
                            PathDic.TryAdd(Item.Name, Item);
                        }
                        else
                        {
                            PathDic.TryAdd(Item.Name + Item.FileInfo.Extension, Item);
                        }
                    }
                    else if (Directory.Exists(Item.FileSystemPath))
                    {
                        PathDic.TryAdd(Item.Name, Item);
                    }
                }

                bool HasError = false;

                foreach (string OriginPath in OriginPathList)
                {
                    if (PathDic.TryGetValue(OriginPath, out ShellItem SourceItem))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(SourceItem.Name));

                        if (File.Exists(SourceItem.FileSystemPath))
                        {
                            File.Move(SourceItem.FileSystemPath, StorageController.GenerateUniquePath(OriginPath));
                        }
                        else if (Directory.Exists(SourceItem.FileSystemPath))
                        {
                            Directory.Move(SourceItem.FileSystemPath, StorageController.GenerateUniquePath(OriginPath));
                        }

                        string ExtraInfoPath = Path.Combine(Path.GetDirectoryName(SourceItem.FileSystemPath), Path.GetFileName(SourceItem.FileSystemPath).Replace("$R", "$I"));

                        if (File.Exists(ExtraInfoPath))
                        {
                            File.Delete(ExtraInfoPath);
                        }
                    }
                    else
                    {
                        HasError = true;
                    }
                }

                return(!HasError);
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"An exception was threw in {nameof(Restore)}");
                return(false);
            }
            finally
            {
                foreach (ShellItem Item in PathDic.Values)
                {
                    Item.Dispose();
                }
            }
        }
Ejemplo n.º 10
0
        public static string GenerateRecycleItemsByJson()
        {
            try
            {
                List <Dictionary <string, string> > RecycleItemList = new List <Dictionary <string, string> >();

                foreach (ShellItem Item in RecycleBin.GetItems())
                {
                    try
                    {
                        Dictionary <string, string> PropertyDic = new Dictionary <string, string>
                        {
                            { "ActualPath", Item.FileSystemPath }
                        };

                        try
                        {
                            PropertyDic.Add("DeleteTime", (Item.IShellItem as Shell32.IShellItem2).GetFileTime(Ole32.PROPERTYKEY.System.Recycle.DateDeleted).ToInt64().ToString());
                        }
                        catch
                        {
                            PropertyDic.Add("DeleteTime", default(FILETIME).ToInt64().ToString());
                        }

                        if (File.Exists(Item.FileSystemPath))
                        {
                            PropertyDic.Add("StorageType", Enum.GetName(typeof(StorageItemTypes), StorageItemTypes.File));

                            if (Path.GetExtension(Item.Name).Equals(Item.FileInfo.Extension, StringComparison.OrdinalIgnoreCase))
                            {
                                PropertyDic.Add("OriginPath", Item.Name);
                            }
                            else
                            {
                                PropertyDic.Add("OriginPath", Item.Name + Item.FileInfo.Extension);
                            }
                        }
                        else if (Directory.Exists(Item.FileSystemPath))
                        {
                            PropertyDic.Add("OriginPath", Item.Name);
                            PropertyDic.Add("StorageType", Enum.GetName(typeof(StorageItemTypes), StorageItemTypes.Folder));
                        }
                        else
                        {
                            continue;
                        }

                        RecycleItemList.Add(PropertyDic);
                    }
                    finally
                    {
                        Item.Dispose();
                    }
                }

                return(JsonSerializer.Serialize(RecycleItemList));
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"An exception was threw in {nameof(GenerateRecycleItemsByJson)}");
                return(string.Empty);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Find out what process(es) have a lock on the specified file.
        /// </summary>
        /// <param name="path">Path of the file.</param>
        /// <returns>Processes locking the file</returns>
        public static IReadOnlyList <Process> GetLockingProcesses(string path)
        {
            StringBuilder SessionKey = new StringBuilder(Guid.NewGuid().ToString());

            if (RstrtMgr.RmStartSession(out uint SessionHandle, 0, SessionKey).Succeeded)
            {
                try
                {
                    string[] ResourcesFileName = new string[] { path };

                    if (RstrtMgr.RmRegisterResources(SessionHandle, (uint)ResourcesFileName.Length, ResourcesFileName, 0, null, 0, null).Succeeded)
                    {
                        uint pnProcInfo = 0;

                        //Note: there's a race condition here -- the first call to RmGetList() returns
                        //      the total number of process. However, when we call RmGetList() again to get
                        //      the actual processes this number may have increased.
                        Win32Error Error = RstrtMgr.RmGetList(SessionHandle, out uint pnProcInfoNeeded, ref pnProcInfo, null, out _);

                        if (Error == Win32Error.ERROR_MORE_DATA)
                        {
                            // Create an array to store the process results
                            RstrtMgr.RM_PROCESS_INFO[] ProcessInfo = new RstrtMgr.RM_PROCESS_INFO[pnProcInfoNeeded];

                            pnProcInfo = pnProcInfoNeeded;

                            // Get the list
                            if (RstrtMgr.RmGetList(SessionHandle, out pnProcInfoNeeded, ref pnProcInfo, ProcessInfo, out _).Succeeded)
                            {
                                List <Process> LockProcesses = new List <Process>((int)pnProcInfo);

                                // Enumerate all of the results and add them to the
                                // list to be returned
                                for (int i = 0; i < pnProcInfo; i++)
                                {
                                    try
                                    {
                                        LockProcesses.Add(Process.GetProcessById(Convert.ToInt32(ProcessInfo[i].Process.dwProcessId)));
                                    }
                                    catch (Exception ex)
                                    {
                                        // catch the error -- in case the process is no longer running
                                        LogTracer.Log(ex, "Process is no longer running");
                                    }
                                }

                                return(LockProcesses);
                            }
                            else
                            {
                                LogTracer.Log("Could not list processes locking resource");
                                return(new List <Process>(0));
                            }
                        }
                        else if (Error != Win32Error.ERROR_SUCCESS)
                        {
                            LogTracer.Log("Could not list processes locking resource. Failed to get size of result.");
                            return(new List <Process>(0));
                        }
                        else
                        {
                            LogTracer.Log("Unknown error");
                            return(new List <Process>(0));
                        }
                    }
                    else
                    {
                        LogTracer.Log("Could not register resource");
                        return(new List <Process>(0));
                    }
                }
                finally
                {
                    RstrtMgr.RmEndSession(SessionHandle);
                }
            }