Esempio n. 1
0
        /// <summary>
        /// Tries to delete the file "the hard way". At first this method determines which process(es) has the
        /// file in use and closes the file handle of the file within the determined process(es). If this has
        /// been done, the file is deleted using File.Delete().
        /// </summary>
        /// <param name="absoluteFileName">Absolute name of the file to be deleted.</param>
        /// <returns>true if and only if the file has been deleted.</returns>
        private bool TryHarderDelete(string absoluteFileName)
        {
            // Windows Vista provides a new API which can be used to determine which process
            // has a file opened. This API is nor available on Windows XP so we have check
            // all processes on those legacy systems.
            bool       isVistaOrNewer = SystemHelper.IsWindowsVistaOrNewer();
            List <int> processIds     = isVistaOrNewer ? UsedFileDetector.GetProcesses(absoluteFileName) : SystemHelper.GetProcesses();

            foreach (int pid in processIds)
            {
                Logger.Log(LogLevel.Debug, "Checking all file handles of process " + pid);

                foreach (IntPtr handle in this.snapshot.GetHandles(pid))
                {
                    Logger.Log(LogLevel.Debug, string.Empty);

                    string fileName = LowLevelHandleHelper.GetFileNameFromHandle(handle, pid);

                    if (absoluteFileName.Equals(fileName, StringComparison.OrdinalIgnoreCase))
                    {
                        Logger.Log(LogLevel.Verbose, "File " + absoluteFileName + " is in use by process with PID " + pid);
                        this.CloseHandleInRemoteProcess(pid, handle);
                        break;
                    }
                }
            }

            File.Delete(absoluteFileName);
            return(true);
        }