在.NET中运行带有重定向文件路径的进程

时间:2012-09-16 12:11:22

标签: c# .net vb.net io

有没有办法在.NET中运行带有重定向文件路径的进程,类似于Sandboxie和DropboxPortableAHK所做的那样?

例如,如果进程想要在C:\file.txt处写文件,我希望我的应用程序将进程写入C:\Sandbox\file.txt

3 个答案:

答案 0 :(得分:3)

由于.NET迟早会将调用重定向到底层操作系统,所以你真的可以附加一个钩子并替换CreateFile() - 就像修改路径的例程一样。

Detours Library可能就是您所需要的。它有一些许可问题,特别是在64位模式下,所以请寻找像这样的免费替代方案:DetourXS

这里给出了挂钩CreateFile / WriteFile / ReadFile的确切说明:CodingTheWheel

您只需使用以下过程编写DLL:

// Our custom version of the CreateFile Windows API, having the same parameters,
// return type, and calling convention as the version of CreateFile provided by the OS.
HANDLE WINAPI Mine_CreateFile(LPCWSTR lpFileName,DWORD dwDesiredAccess,
                              DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecAttr,
                              DWORD dwCreateDisp, DWORD dwFlagsAttr,HANDLE hTemplate)
{
    // First, call the original CreateFile provided by the operating system.
    HANDLE hFile = Real_CreateFile(lpFileName,dwDesiredAccess,dwShareMode,lpSecAttr,
                                    dwCreateDisp,dwFlagsAttr,hTemplate);

    // Now, do whatever we want with the filename (lpFileName)
    /// e.g., redirect C:\test.txt to C:\MyApp\test.txt

    // Now, do whatever we want with the file handle (hFile)

    // Call the original CreateFile

    // Return the same value returned to us by the original API
    return hFile;
}

答案 1 :(得分:2)

我建议您使用EasyHook,这是您要找的example

答案 2 :(得分:0)

这一点都不简单,但基本上你需要在本机代码中创建一个DLL(例如C ++)。此DLL挂钩文件和注册表IO,并将其重定向到您的沙箱目录。然后,将此DLL注入沙盒进程。然后,DLL将挂钩此进程的活动。

这是基本的想法。