コード例 #1
0
ファイル: NativeMethods.cs プロジェクト: campbeb/DeadLock
        /// <summary>
        /// Find the processes that are locking a file.
        /// </summary>
        /// <param name="path">Path to the file.</param>
        /// <param name="language">Current language to implement localized messages</param>
        /// <returns>A collection of processes that are locking a file.</returns>
        internal static IEnumerable <Process> FindLockingProcesses(string path, Language language)
        {
            uint           handle;
            string         key       = Guid.NewGuid().ToString();
            List <Process> processes = new List <Process>();

            int res = RmStartSession(out handle, 0, key);

            if (res != 0)
            {
                throw new Exception(language.MsgCouldNotRestart);
            }

            try
            {
                const int errorMoreData = 234;
                uint      pnProcInfoNeeded;
                uint      pnProcInfo        = 0;
                uint      lpdwRebootReasons = RmRebootReasonNone;

                string[] resources = { path };
                res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);

                if (res != 0)
                {
                    throw new Exception(language.MsgCouldNotRegister);
                }
                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);

                if (res == errorMoreData)
                {
                    RmProcessInfo[] processInfo = new RmProcessInfo[pnProcInfoNeeded];
                    pnProcInfo = pnProcInfoNeeded;

                    res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
                    if (res == 0)
                    {
                        processes = new List <Process>((int)pnProcInfo);

                        for (int i = 0; i < pnProcInfo; i++)
                        {
                            try
                            {
                                processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                            }
                            catch (ArgumentException) { }
                        }
                    }
                    else
                    {
                        throw new Exception(language.MsgCouldNotList);
                    }
                }
                else if (res != 0)
                {
                    throw new UnauthorizedAccessException(language.MsgCouldNotListResult);
                }
            }
            finally
            {
                RmEndSession(handle);
            }
            return(processes);
        }
コード例 #2
0
ファイル: NativeMethods.cs プロジェクト: campbeb/DeadLock
        /// <summary>
        /// Find the processes that are locking a file.
        /// </summary>
        /// <param name="path">Path to the file.</param>
        /// <param name="language">Current language to implement localized messages</param>
        /// <returns>A collection of processes that are locking a file.</returns>
        internal static IEnumerable<Process> FindLockingProcesses(string path, Language language)
        {
            uint handle;
            string key = Guid.NewGuid().ToString();
            List<Process> processes = new List<Process>();

            int res = RmStartSession(out handle, 0, key);
            if (res != 0) throw new Exception(language.MsgCouldNotRestart);

            try
            {
                const int errorMoreData = 234;
                uint pnProcInfoNeeded;
                uint pnProcInfo = 0;
                uint lpdwRebootReasons = RmRebootReasonNone;

                string[] resources = { path };
                res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);

                if (res != 0) throw new Exception(language.MsgCouldNotRegister);
                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);

                if (res == errorMoreData)
                {
                    RmProcessInfo[] processInfo = new RmProcessInfo[pnProcInfoNeeded];
                    pnProcInfo = pnProcInfoNeeded;

                    res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
                    if (res == 0)
                    {
                        processes = new List<Process>((int)pnProcInfo);

                        for (int i = 0; i < pnProcInfo; i++)
                        {
                            try
                            {
                                processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                            }
                            catch (ArgumentException) { }
                        }
                    }
                    else throw new Exception(language.MsgCouldNotList);
                }
                else if (res != 0) throw new UnauthorizedAccessException(language.MsgCouldNotListResult);
            }
            finally
            {
                RmEndSession(handle);
            }
            return processes;
        }
コード例 #3
0
ファイル: FileUtil.cs プロジェクト: HyperBlazt/Bachelor2017
        /// <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>
        /// <remarks>See also:
        /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
        /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
        /// </remarks>
        public static IEnumerable <Process> WhoIsLocking(string path)
        {
            uint   handle;
            string key       = Guid.NewGuid().ToString();
            var    processes = new List <Process>();

            int res = RmStartSession(out handle, 0, key);

            if (res != 0)
            {
                throw new Exception("Could not begin restart session.  Unable to determine file locker.");
            }

            try
            {
                const int ERROR_MORE_DATA   = 234;
                uint      pnProcInfoNeeded  = 0,
                          pnProcInfo        = 0,
                          lpdwRebootReasons = RmRebootReasonNone;

                var resources = new string[] { path }; // Just checking on one resource.

                res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);

                if (res != 0)
                {
                    throw new Exception("Could not register resource.");
                }

                //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.
                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);

                if (res == ERROR_MORE_DATA)
                {
                    // Create an array to store the process results
                    var processInfo = new RmProcessInfo[pnProcInfoNeeded];
                    pnProcInfo = pnProcInfoNeeded;

                    // Get the list
                    res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
                    if (res == 0)
                    {
                        processes = 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
                            {
                                processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                            }
                            // catch the error -- in case the process is no longer running
                            catch (ArgumentException)
                            {
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("Could not list processes locking resource.");
                    }
                }
                else if (res != 0)
                {
                    throw new Exception("Could not list processes locking resource. Failed to get size of result.");
                }
            }
            finally
            {
                RmEndSession(handle);
            }

            return(processes);
        }
コード例 #4
0
        public static string LockCheck(string filename)
        {
            var handle     = default(uint);
            var sessionkey = Guid.NewGuid().ToString();
            var result     = new System.Text.StringBuilder();
            var res        = Interop.RmStartSession(ref handle, 0, sessionkey);

            if (res != 0)
            {
                throw new Exception("Could not begin restart session.");
            }

            try
            {
                var  pnProcInfoNeeded  = 0U;
                var  pnProcInfo        = 100U;
                uint lpdwRebootReasons = RmRebootReasonNone;
                var  resources         = new string[] { filename };

                // Create an array to store the process results.
                var processInfo = new RmProcessInfo[(int)(pnProcInfo - 1L + 1)];
                res = Interop.RmRegisterResources(handle, (uint)resources.Length, resources, 0U, null, 0U, null);
                if (res != 0)
                {
                    throw new Exception("Could not register resource.");
                }

                res = Interop.RmGetList(handle, ref pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
                if (res == 0)
                {
                    // The function completed successfully.

                    if (pnProcInfo != 0L)
                    {
                        for (int i = 0, loopTo = (int)(pnProcInfo - 1L); i <= loopTo; i++)
                        {
                            // Console.WriteLine("File Name :" + resources(0))
                            result.Append("File Name :").AppendLine(resources[0]);
                            // Console.WriteLine("Application locking the file :" + processInfo(i).strAppName)
                            result.Append("Application locking the file : ").AppendLine(processInfo[i].strAppName);
                            result.Append("PID of process locking the file: ").AppendLine(processInfo[i].Process.dwProcessId.ToString());
                        }
                    }
                    else
                    {
                        // Console.WriteLine("The specified file '{0}' is not locked by any process", resources(0))
                        result.AppendLine("No locks");
                    }
                }
                else
                {
                    throw new Exception("Could not list processes locking resource.");
                }

                if (res != 0)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            catch (Exception exception)
            {
                // Console.WriteLine(exception.Message)
                result.AppendLine(exception.Message);
            }
            finally
            {
                Interop.RmEndSession(handle);
            }

            return(result.ToString());
        }