如果保存在驱动器中,如何检索记事本文件的实际路径。 例如,记事本进程正在运行,它将保存在驱动器中的某个位置。 我该如何检索其完整路径? 使用下面的代码,我可以获得流程详细信息,但不能获取特定文件的实际路径。
Process[] localByName = Process.GetProcessesByName("notepad"); foreach (Process p in localByName) { string path = p.MainModule.FileName.ToString(); }这将返回可执行路径,但我需要实际文件所在的驱动器位置。
How to retrieve the actual path of the notepad file if it is saved in drive. For example a notepad process is running and it is saved somewhere in the drive. How can I retrieve its full path? Using below code I can get the process detail, but not the actual path of particular files.
Process[] localByName = Process.GetProcessesByName("notepad"); foreach (Process p in localByName) { string path = p.MainModule.FileName.ToString(); }this returns executeable path but i need Drive location whre the actual file reside.
最满意答案
这应该这样做:
string wmiQuery = string.Format("select CommandLine from Win32_Process where Name='{0}'", "notepad.exe"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery); ManagementObjectCollection retObjectCollection = searcher.Get(); foreach (ManagementObject retObject in retObjectCollection) { string CommandLine = retObject["CommandLine"].ToString(); string path = CommandLine.Substring(CommandLine.IndexOf(" ") + 1, CommandLine.Length - CommandLine.IndexOf(" ") - 1); }仅当通过双击或通过命令行打开文件时,它才有效。
不要忘记通过右键单击“项目”,“添加引用”,然后选择“程序集”选项卡和“搜索系统管理”来添加对System.Management的引用。
This should do it:
string wmiQuery = string.Format("select CommandLine from Win32_Process where Name='{0}'", "notepad.exe"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery); ManagementObjectCollection retObjectCollection = searcher.Get(); foreach (ManagementObject retObject in retObjectCollection) { string CommandLine = retObject["CommandLine"].ToString(); string path = CommandLine.Substring(CommandLine.IndexOf(" ") + 1, CommandLine.Length - CommandLine.IndexOf(" ") - 1); }It will work only if the file is opened by double click or through command line.
Don't forget to add reference to System.Management by right Click on Project, Add References then select the Assemblies Tab and Search for System.Management.
更多推荐
发布评论