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?
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With