C# 获取另一个进程的工作目录 [英] C# Get working directory of another process

查看:139
本文介绍了C# 获取另一个进程的工作目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过读取命令行来确定已​​知进程使用的文件的绝对路径.目前,该过程是从命令行中的相对路径开始的,这些路径指向各种文件,例如配置文件.问题是,如果路径不是相对于包含可执行文件的文件夹,我无法转换命令行提供的相对路径,我不能 100% 确定.

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.

例如两个批处理文件:

第 1 批光盘 c:\test\bintest.exe ..\config\config.ini

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

第 2 批光盘 c:\testbin\test.exe config\config.ini

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

对于批处理文件一,我得到的命令行是c:\test\bin\test.exe ..\config\config.ini",对于批处理文件二,我得到的是c:\test\bin\test.exe 配置\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.

无论如何,对于初学者来说,我使用 ManagementObjectSearcher 从 WMI 查询中获得了命令行.现在我需要获取启动进程的工作目录以解析在命令行传递的路径,但如何解决?

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?

我忘记了一个关键细节.我想获取另一个进程的工作目录.基本上,我的主程序从另一个程序收集信息.我能够确定进程 ID,因为我知道可执行文件的名称.我也可以确定命令行.我现在必须找到启动可执行文件的工作目录或当前目录,以便我可以解析命令行的相对路径.我希望我把问题说得更清楚了.

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.

推荐答案

我认为 Environment.CurrentDirectory 应该给你启动可执行文件的目录.它只在进程开始时可靠,因为它可以稍后更改.

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.

或者尝试Process.GetCurrentProcess().StartInfo.WorkingDirectory.我自己没有尝试,只是在 上查了一下MSDN

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

这篇关于C# 获取另一个进程的工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆