C# Get working directory of another process

安稳与你 提交于 2019-12-10 03:34:36

问题


I want to determine the absolute path of files used by a known process by reading the command line. Currently, the process is started with relative paths in the command line that point to various files such as config files. The problem is that if the paths are not relative to the folder containing the executable, I have no way of converting the relative paths provided at the command line, well I can't be 100% sure.

For example two batch files:

BATCH 1 CD c:\test\bin test.exe ..\config\config.ini

BATCH 2 CD c:\test bin\test.exe config\config.ini

For batch file one, the command line I get is "c:\test\bin\test.exe ..\config\config.ini" and for batch file two I get "c:\test\bin\test.exe config\config.ini". So, see this I can't resolve the paths.

Anyway for starters, I got the command line from a WMI query using ManagementObjectSearcher. Now I need to get the working directory the process was started from to resolve the paths passed at the command line but how?

EDIT: I forgot one key detail. I want to get the working directory of another process. Basically, my main program gathers info from another program. I'm able to determine the process ID because I know the name of the executable. I can also determine the command line. I must now find the working directory or current directory the executable was started in so I can resolve the relative paths of command line. I hope I made the question clearer.


回答1:


I think Environment.CurrentDirectory should give you the directory the executable was started in. It is only reliable at the start of the process, because it can change later.

Or maybe try Process.GetCurrentProcess().StartInfo.WorkingDirectory. I didn't try it myself, just looked it up on MSDN




回答2:


Have you tried Application.ExecutablePath?

Alternatively, there are numerous Paths that can be retrieve from Application




回答3:


To get working directory (current directory) of another process in c# take a look at https://stackoverflow.com/a/23842609/3029359



来源:https://stackoverflow.com/questions/3375406/c-sharp-get-working-directory-of-another-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!