获取 cmd.exe 的当前工作目录 [英] Get the current working directory for cmd.exe

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

问题描述

如何检索cmd.exe的当前工作目录?

How can I retrieve the current working directory of cmd.exe?

这似乎是可能的.例如使用ProcessExplorer,选择CMD.exe,右键单击,属性,图像选项卡,当前目录"反映使用CD或CHDIR命令设置的目录.

This seems possible. For example using ProcessExplorer, select CMD.exe, right click, properties, Image tab, "Current Directory" relects the directory set using the CD or CHDIR commands.

我查看了 .NET Process 和 ProcessStartInfo 类(ProcessStartInfo.WorkingDirectory 总是返回"),但似乎找不到确定这一点的方法.PInvoke 中也没有什么特别突出的.

I've looked at the .NET Process and ProcessStartInfo classes (ProcessStartInfo.WorkingDirectory always returns "") and can't seem to find a way of determining this. Nothing at PInvoke stands out either.

作为一个例子,我希望以编程方式能够说出以下内容: Process.GetCurrentWorkingDirectory(processID) 其中 processID 是另一个正在运行的进程的 Windows 进程 ID.

As an example I'm looking to programmatically be able to say something like: Process.GetCurrentWorkingDirectory(processID) where processID is a Windows process ID of another running process.

有没有解决方案,WinAPI 或 .NET?

Is there any solution, WinAPI or .NET?

[更新]

问这个问题的原因:

我已经使用命令提示符资源管理器栏"一段时间了,它很棒,除非我CD"到一个新目录,当前资源管理器窗口也不会改变.(即同步只是从资源管理器到命令提示符的一种方式).我正在寻找两种方式.

I've used the "Command Prompt Explorer Bar" for a while and it's great except if I "CD" to a new directory, the current Explorer window does not also change. (ie the Sync is only 1 way from Explorer to the commmand prompt). I'm looking to make this 2 way.

推荐答案

未经测试,一种可能的方法:

Untested, a possible approach:

创建一个带有 DllMain 的 DLL,它使用 GetThreadStartInformation() 查找缓冲区的地址,然后使用 GetCurrentDirectory 填充它.这应该没问题,因为这两个函数都在 kernel32 中,它始终存在.你需要在那里有一些结构来返回成功/失败.

Create a DLL with a DllMain that uses GetThreadStartInformation() to find the address of the buffer, and then uses GetCurrentDirectory to populate it. This should be OK, because both of those functions are in kernel32, which is always present. You will need to have some structure there to return success/failure.

  1. 获取 cmd.exe 进程的句柄.
  2. 在那里分配一些内存(VirtualAllocEx)
  3. 将 DLL 的路径放在内存中.(WriteProcessMemory)
  4. 将您的 dll 加载到 cmd.exe 地址空间.(CreateRemoteThread 的入口点是 LoadLibrary,参数是你之前分配的内存.)
  5. WaitForSingleObject 后跟 GetExitCodeThread(),为您提供 cmd.exe 进程中 DLL 的 HMODULE.
  6. ReadProcessMemory 以获取当前目录.
  7. 从 cmd.exe 地址空间卸载您的 dll.入口点为 FreeLibrary 的 CreateRemote 线程,参数为 HMODULE.
  8. WaitForSingleObject 等待 DLL 卸载.

大纲:细节留作练习!风险:在 cmd.exe 地址空间分配内存,改变其状态.必须注意 DllMain 中调用的函数.

Broad sketch: Details left as an excercise! Risks: Allocates memory in the cmd.exe address space, changes its state. Care must be taken with the functions called in DllMain.

这篇关于获取 cmd.exe 的当前工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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