Catch the file path opened by the process name in C #

3

I have an application that works based on the current client process. I need to get the filename and its absolute path when opened. That is:

If for example the client opens the file "test.txt", I need to get the path "c: \ project \ test.txt" instead of "c: \ windows \ system32 \ notepad.exe". The same goes for .DOC, .XLS, etc ...

The code snippet below returns the process-related information, which includes the software path (... \ 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);
}

Through the class of the Process is it possible to acquire the path of the file being worked?

    
asked by anonymous 08.05.2015 / 14:39

1 answer

1

Is it possible to acquire the path of the file being worked through the Process class?

No. For this case, the approach needs to be another one, using a .NET class called FileSystemWatcher ". I will remove the example below :

m_starting_path.Text = "C:\
watcher = new FileSystemWatcher();

//---------------------------------------------------------------
// Suponho que seja uma aplicação que tenha um botão
// Aqui ocorre o acionamento do FileSystemWatcher, que 
// funciona basicamente com eventos. 

private void MeuBotaoClick(object sender, System.EventArgs e)
{
    if (watcher.EnableRaisingEvents == true) {
        MessageBeep(100);
        return
    }

    watcher.Path         = m_starting_path.Text;
    watcher.Filter       = m_filter.Text;
    watcher.NotifyFilter = NotifyFilters.FileName |
                           NotifyFilters.Attributes |
                           NotifyFilters.LastAccess |
                           NotifyFilters.LastWrite |
                           NotifyFilters.Security |
                           NotifyFilters.Size;


    watcher.Changed += new FileSystemEventHandler(OnFileEvent);
    watcher.Created += new FileSystemEventHandler(OnFileEvent);
    watcher.Deleted += new FileSystemEventHandler(OnFileEvent);
    watcher.Renamed += new RenamedEventHandler(OnRenameEvent);
    watcher.IncludeSubdirectories = true;
    watcher.EnableRaisingEvents = true;
}

public void OnFileEvent(object source, FileSystemEventArgs fsea)
{
    // Aqui você verifica modificações no arquivo (source)
}

public void OnRenameEvent(Object source, RenamedEventArgs rea)
{
    // Aqui você verifica arquivos renomeados
}

To relate the process to the file, You can use one of the proposed solutions in this OS question .

    
08.05.2015 / 17:37