c# - 如何获取记事本文件保存位置

标签 c# wpf winforms notepad win32-process

如果保存在驱动器中,如何检索记事本文件的实际路径。例如,一个记事本进程正在运行,它被保存在驱动器的某个地方。我怎样才能检索它的完整路径?使用下面的代码我可以获得过程细节,但不是特定文件的实际路径。

Process[] localByName = Process.GetProcessesByName("notepad");
foreach (Process p in localByName)
    {
      string path  =  p.MainModule.FileName.ToString();
    }

这会返回可执行路径,但我需要实际文件所在的驱动器位置。

最佳答案

应该这样做:

        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 的引用,方法是右键单击项目,添加引用,然后选择程序集选项卡并搜索 System.Management。

Step 1

Step 2

关于c# - 如何获取记事本文件保存位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34932301/

相关文章:

c# - HttpWebRequest resp.Headers ["Set-Cookie"] 为空

c# - 在运行时添加图像

C# 验证 : IDataErrorInfo without hard-coded strings of property name?

c# - 如何让 '&' 在 MenuItem 中显示为文本

c# - Winform,带有图像和文本但没有控制按钮的自定义标题栏?

c# - 局部变量和从方法调用的变量之间的区别? C#

c# - 找不到方法 : AcquireToken(System. 字符串,Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate)

Unix/Linux 上的 C# 开发(有人用过 CoreFX 吗?)

.net - WPF 中复选框左侧的文本?

c# - 再次加载 Form1 的可视化 C# 代码