如何确定目录路径是否已 SUBST'd

问题描述 投票:0回答:4

如何确定文件是否位于已SUBST'ed的文件夹中或位于使用 C# 的用户文件夹中?

c# security directory
4个回答
4
投票

这是我用来获取路径替换信息的代码: (部分部分来自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;
}

摘自@rrreee 的评论。我没有检查过,但听起来很有用:

Handy tip: lastWinErr will be 2, if the drive letter in path is not mapped

3
投票

我认为您需要 P/Invoke QueryDosDevice() 来获取驱动器号。 Subst drivers 将返回一个符号链接,类似于 \??\C: lah。 \??\ 前缀表示它已被替换,其余部分为您提供驱动器+目录。


2
投票

如果 SUBST 在不带参数的情况下运行,它将生成所有当前替换的列表。获取列表,然后根据列表检查您的目录。

还有将卷映射到目录的问题。我从未尝试检测这些,但安装点目录的显示确实与常规目录不同,因此它们必须具有某种不同的属性,并且可以被检测到。


1
投票

我认为你有几个选择--

通过 System.Management 类: http://briancaos.wordpress.com/2009/03/05/get-local-path-from-unc-path/

或者

通过P/调用此MAPI函数: ScUNCFromLocalPath http://msdn.microsoft.com/en-us/library/cc842520.aspx

© www.soinside.com 2019 - 2024. All rights reserved.