Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filename by process

Tags:

c#

kernel32

ntdll

I'm trying to retrieve the filename of a current process.

ie: If i have the file "test.txt" opened in Notepad, I need to get something like "c:\folder\test.txt"

The code below returns process informations, including the software path. (ie: "c:\windows\system32\notepad.exe").

[DllImport("user32.dll", EntryPoint = "GetForegroundWindow", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int GetForegroundWindow();

[...]

public static string GetFilePathName()
{
    uint procId = 0;
    int hWnd = GetForegroundWindow();
    GetWindowThreadProcessId(hWnd, out procId);
    var proc = Process.GetProcessById((int)procId);
}

Is it possible to use this Process Class to achieve the opened filename/path the the current process is handling?

like image 642
Andre Felipe Avatar asked Nov 27 '25 16:11

Andre Felipe


1 Answers

In C#, I have the following solution. I wrote this to identify opened files in Notepad.exe to call Kill() on.

Your solution will depend on the window title, in this case I could expect formatting in Notepad to be "Untitled - Notepad", "config.ini - Notepad", "readme.txt - Notepad", etc. where I would split on the char '-' and trim the white space.

public static void getFileNameByProcess(string process)
{
    foreach (Process p in Process.GetProcessesByName(process))
    {
        string[] split = p.MainWindowTitle.Split('-');
        if (split.Length > 0)
            Console.WriteLine("\"" + split[0].Trim() + "\"");
    }
}

Use it like this: getFileNameByProcess("Notepad");

Example filenames:

  1. "config.ini"
  2. "readme.txt"
  3. "Untitled"

Using those file names, you could recursively search a directory if you had a general idea of where it is located however I would caution expensive calls like that

like image 124
Tyler V Avatar answered Nov 29 '25 05:11

Tyler V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!