c#+handle.exe实现升级程序在运行时自动解除文件被占用的问题
发布日期:2021-05-09 09:35:23 浏览次数:16 分类:博客文章

本文共 11854 字,大约阅读时间需要 39 分钟。

������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������handle.exe������������������������������������������������������������������������KILL���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

IsFileUsing������������������������������

[DllImport("kernel32.dll")]        public static extern IntPtr _lopen(string lpPathName, int iReadWrite);        [DllImport("kernel32.dll")]        public static extern bool CloseHandle(IntPtr hObject);        public const int OF_READWRITE = 2;        public const int OF_SHARE_DENY_NONE = 0x40;        public readonly IntPtr HFILE_ERROR = new IntPtr(-1);        private bool IsFileUsing(string filePath)        {            if (!File.Exists(filePath))            {                return false;            }            IntPtr vHandle = _lopen(filePath, OF_READWRITE | OF_SHARE_DENY_NONE);            if (vHandle == HFILE_ERROR)            {                return true;            }            CloseHandle(vHandle);            return false;        }

GetRunProcessInfos������������������������������������������(���������)���������������������������������������������������

///         /// ���������������������������������������(���������)���������������������������������������������������        ///         ///         /// 
private Dictionary
GetRunProcessInfos(string filePath) { Dictionary
runProcInfos = new Dictionary
(); string fileName = Path.GetFileName(filePath); var fileRunProcs = Process.GetProcessesByName(fileName); if (fileRunProcs != null && fileRunProcs.Count() > 0) { runProcInfos = fileRunProcs.ToDictionary(p => p.Id, p => p.ProcessName); return runProcInfos; } string fileDirName = Path.GetDirectoryName(filePath); //��������������������������������������� Process startProcess = new Process(); startProcess.StartInfo.FileName = RelaseAndGetHandleExePath(); startProcess.StartInfo.Arguments = string.Format("\"{0}\"", fileDirName); startProcess.StartInfo.UseShellExecute = false; startProcess.StartInfo.RedirectStandardInput = false; startProcess.StartInfo.RedirectStandardOutput = true; startProcess.StartInfo.CreateNoWindow = true; startProcess.StartInfo.StandardOutputEncoding = ASCIIEncoding.UTF8; startProcess.OutputDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data) && e.Data.IndexOf("pid:", StringComparison.OrdinalIgnoreCase) > 0) { //var regex = new System.Text.RegularExpressions.Regex(@"(^[\w\.\?\u4E00-\u9FA5]+)\s+pid:\s*(\d+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); var regex = new System.Text.RegularExpressions.Regex(@"(^.+(?=pid:))\bpid:\s+(\d+)\s+", System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (regex.IsMatch(e.Data)) { var mathedResult = regex.Match(e.Data); int procId = int.Parse(mathedResult.Groups[2].Value); string procFileName = mathedResult.Groups[1].Value.Trim(); if ("explorer.exe".Equals(procFileName, StringComparison.OrdinalIgnoreCase)) { return; } //var regex2 = new System.Text.RegularExpressions.Regex(string.Format(@"\b{0}.*$", fileDirName.Replace(@"\", @"\\").Replace("?",@"\?")), System.Text.RegularExpressions.RegexOptions.IgnoreCase); var regex2 = new System.Text.RegularExpressions.Regex(@"\b\w{1}:.+$", System.Text.RegularExpressions.RegexOptions.IgnoreCase); string procFilePath = (regex2.Match(e.Data).Value ?? "").Trim(); if (filePath.Equals(procFilePath, StringComparison.OrdinalIgnoreCase) || filePath.Equals(PathJoin(procFilePath, procFileName), StringComparison.OrdinalIgnoreCase)) { runProcInfos[procId] = procFileName; } else //��������������������������������������� { if (procFilePath.Contains("?") || procFileName.Contains("?")) //?������������������ { var regex3 = new System.Text.RegularExpressions.Regex(procFilePath.Replace(@"\", @"\\").Replace(".", @"\.").Replace("?", ".{1}"), System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (regex3.IsMatch(filePath)) { runProcInfos[procId] = procFileName; } else { string tempProcFilePath = PathJoin(procFilePath, procFileName); regex3 = new System.Text.RegularExpressions.Regex(tempProcFilePath.Replace(@"\", @"\\").Replace(".", @"\.").Replace("?", ".{1}"), System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (regex3.IsMatch(filePath)) { runProcInfos[procId] = procFileName; } } } else if (procFilePath.Length == filePath.Length || PathJoin(procFilePath, procFileName).Length == filePath.Length) //��������������������������������������������������������������������������� { if (MessageBox.Show(string.Format("������������:{0}���������������������({1})������,\n������������������������������������?", filePath, procFileName), "���������������������������", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { runProcInfos[procId] = procFileName; } } } } } }; startProcess.Start(); startProcess.BeginOutputReadLine(); startProcess.WaitForExit(); return runProcInfos; }

������������������������������������������������������������handle.exe���������������������������������������������������������������������������������������������������������������������������������������handle.exe���������������������������������������������������������������������������������������������������������������������������������������������

RelaseAndGetHandleExePath���������������������handle.exe���������������������APPData������������������������������������������������������������handle.exe������������������������������������������������������������������������������handle.exe���������������������������������������������Agree���������������������������������������������������������������������������������������������������������������������������������������������������������handle.exe������������������������������������������������

private string RelaseAndGetHandleExePath()        {            var handleInfo = new FileInfo(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\SysUpdate\\handle.exe");            if (!File.Exists(handleInfo.FullName))            {                if (!Directory.Exists(handleInfo.DirectoryName))                {                    Directory.CreateDirectory(handleInfo.DirectoryName);                }                byte[] handleExeData = Properties.Resources.handle;                File.WriteAllBytes(handleInfo.FullName, handleExeData);                var handleProc = Process.Start(handleInfo.FullName);//������������������������������������������������agree������������                handleProc.WaitForExit();            }            return handleInfo.FullName;        }

PathJoin���������������������������������������������������handle.exe������������������������������������������������������������������������������������������������������������Path.Combine���������������������������������������������������������������������������

///         /// ������������������������������������        ///         ///         /// 
private string PathJoin(params string[] paths) { if (paths == null || paths.Length <= 0) { return string.Empty; } string newPath = paths[0]; for (int i = 1; i < paths.Length; i++) { if (!newPath.EndsWith("\\")) { newPath += "\\"; } if (paths[i].StartsWith("\\")) { paths[i] = paths[i].Substring(1); } newPath += paths[i]; } return newPath; }

CloseProcessWithFile������������������������������������������������������������������������������������������������������������������

private void CloseProcessWithFile(string filePath)        {            if (!IsFileUsing(filePath)) return;            ShowDownInfo(string.Format("������������������������������ {0}", _FilePaths[_FileIndex]));            var runProcInfos = GetRunProcessInfos(filePath); //������������������������            System.IO.File.WriteAllText(Path.Combine(Application.StartupPath, "runProcInfos.txt"), string.Join("\r\n", runProcInfos.Select(p => string.Format("ProdId:{0},ProcName:{1}", p.Key, p.Value)).ToArray()));//DEBUG���������������������������������            var localProcesses = Process.GetProcesses();            bool hasKilled = false;            foreach (var item in runProcInfos)            {                if (item.Key != currentProcessId) //������������������                {                    var runProcess = localProcesses.SingleOrDefault(p => p.Id == item.Key);                    //var runProcess = Process.GetProcessById(item.Key);                    if (runProcess != null)                    {                        try                        {                            runProcess.Kill(); //������������������������������                            hasKilled = true;                        }                        catch                        { }                    }                }            }            if (hasKilled)            {                Thread.Sleep(500);            }        }

������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ID���������������������������������������������ID���currentProcessId = Process.GetCurrentProcess().Id���������������������������������������������������������������������������������������������������������������

���������KILL������������������������������������������������������������������������������������������������������������������������������������������������������������������������KILL������������������������500MS���������������������������������������

上一篇:分享两种实现Winform程序的多语言支持的解决方案
下一篇:利用WCF的双工通讯实现一个简单的心跳监控系统

发表评论

最新留言

表示我来过!
[***.240.166.169]2025年04月24日 03时08分21秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

python 文件操作 open()与with open() as的区别(打开文件) 2021-05-10
pycharm新建文件夹时新建python package和新建directory有什么区别? 2021-05-10
Git中pull,commit和push的概念 2021-05-10
python中列表 元组 字典 集合的区别 2021-05-10
python struct 官方文档 2021-05-10
中级软考 计算机指令执行过程(取指、分析、执行)计算机重叠流水线问题 2021-05-10
opencv cv::BorderTypes 像素外推方法(Pixel extrapolation method) 2021-05-10
摄像头捕获视频流软件AMCAP使用教程(视频采集捕获处理媒体制作微型软件) 2021-05-10
pytorch torch.item()(返回此张量的值作为标准Python数字。 这仅适用于具有一个元素的张量。) 2021-05-10
python 如何计算平方、次方?平方根、方根?(math.pow()、math.sqrt()) 2021-05-10
Docker镜像加速 2021-05-10
x射线和γ射线区别?α射线、β射线 2021-05-10
python 虚拟环境 virtualenv virtualenvwrapper的使用方法、命令 2021-05-10
jinja2 {{}} href 双大括号 2021-05-10
ubuntu无法安装vscode(visual studio code)如何卸载snap? 2021-05-10
VMware虚拟机:桥接、NAT、Host-only(仅主机)上网方式的区别 2021-05-10
python numpy.arange() 函数的使用方法 (在给定间隔内返回均匀间隔的值) 2021-05-10
Unity3D的InputField输入框控件按下Tab键光标自动切换 2021-05-10
C#实现对象为Json嵌套数组文件的创建 2021-05-10
静态数组类的封装(泛型) 2021-05-10