如何确定目录路径是否被SUBST映射了

6

如何使用C#判断文件是否在已经通过SUBST或位于用户文件夹中的文件夹中?


2
我不明白你所说的“subst'd”或“用户文件夹”的意思。 - simendsjo
subst 是一个 DOS 命令,它将为目录创建别名(例如,subst T: C:\workareas 将创建一个指向 C:\workareas 的新驱动器)。对于用户文件夹,我想找出它是否干净地位于 C:\Documents and Settings\%username% - petejamd
4个回答

3
我认为您需要使用P/Invoke调用QueryDosDevice()函数来获取驱动器号。Subst驱动器将返回一个类似于\??\C:\blah的符号链接。 \??\前缀表示它被替换,其余部分给出了驱动器和目录。

3
这是我用来获取路径是否被替换的代码: (某些部分来自于pinvoke)
using System.Runtime.InteropServices;

[DllImport("kernel32.dll", SetLastError=true)]
static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax);

public static bool IsSubstedPath(string path, out string realPath)
{
    StringBuilder pathInformation = new StringBuilder(250);
    string driveLetter = null;
    uint winApiResult = 0;

    realPath = null;

    try
    {
        // Get the drive letter of the path
        driveLetter = Path.GetPathRoot(path).Replace("\\", "");
    }
    catch (ArgumentException)
    {
        return false;
        //<------------------
    }

    winApiResult = QueryDosDevice(driveLetter, pathInformation, 250);

    if(winApiResult == 0)
    {
        int lastWinError = Marshal.GetLastWin32Error(); // here is the reason why it fails - not used at the moment!

        return false;
        //<-----------------
    }

    // If drive is substed, the result will be in the format of "\??\C:\RealPath\".
    if (pathInformation.ToString().StartsWith("\\??\\"))
    {
        // Strip the \??\ prefix.
        string realRoot = pathInformation.ToString().Remove(0, 4);

        // add backshlash if not present
        realRoot += pathInformation.ToString().EndsWith(@"\") ? "" : @"\";

        //Combine the paths.
        realPath = Path.Combine(realRoot, path.Replace(Path.GetPathRoot(path), ""));

        return true;
        //<--------------
    }

    realPath = path;

    return false;
}

请确保在您的类中引用了以下命名空间:using System.Runtime.InteropServices;否则将会出现错误。 - gg89

1
如果运行SUBST而没有参数,它会生成所有当前替换的列表。获取列表,并将其与您的目录进行比对。
还有一个问题是将卷映射到目录。我从未尝试过检测这些内容,但挂载点目录与常规目录显示方式不同,因此它们必须具有某种不同的属性,可以进行检测。

1

这看起来很有前途,正在研究它。 - petejamd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接