7

使用 C#,我希望我的应用程序返回文件夹(具有已知路径)是位于网络中还是位于我的计算机中。

我怎样才能做到这一点?

4

6 回答 6

7

如果您正在谈论映射的网络驱动器,则可以使用DriveInfo'DriveType属性

var driveInfo = new DriveInfo("S:\");
if(driveInfo.DriveType == DriveType.Network)
    // do something
于 2011-08-10T13:58:46.277 回答
5

另一个 SO 问题的原始答案检查路径是否在网络上

使用PathIsNetworkPath(pinvoke参考):

class Program
{
    [DllImport("shlwapi.dll")]
    private static extern bool PathIsNetworkPath(string pszPath);

    static void Main(string[] args)
    {
        Console.WriteLine(PathIsNetworkPath("i:\Backup"));
    }
}
于 2011-08-10T13:58:52.637 回答
3

根据@jgauffin 和@Daniel 的回答,你可以试试这个小技巧:

private static bool IsNetwork(String path)
{
    if (path.StartsWith(@"\\"))
       return true;
    var dir = new DirectoryInfo(path);
    var drive = new DriveInfo(dir.Root.ToString());
    return drive.DriveType == DriveType.Network;
}
于 2011-08-10T14:07:03.870 回答
0

您可以使用以下方法获取文件夹的 UNC 路径。不完全是您正在寻找的东西,但可能有用

    public static string GetUniversalPath(string folderPath)
    {
        if (String.IsNullOrEmpty(folderPath) || folderPath.IndexOf(":") > 1)
            return folderPath;

        if (folderPath.StartsWith("\\"))
        {
            return folderPath;
        }
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT RemoteName FROM win32_NetworkConnection WHERE LocalName = '" + folderPath.Substring(0, 2) + "'");
        foreach (ManagementObject managementObject in searcher.Get())
        {
            string remoteName = managementObject["RemoteName"] as String;
            if (!String.IsNullOrEmpty(remoteName))
            {
                remoteName += folderPath.Substring(2);
                return remoteName;
            }            
        }
        return folderPath;
    }
于 2011-08-10T14:04:50.627 回答
0

从Shell Lightweight Utility API尝试以下操作:

class Class
{
    [DllImport("shlwapi.dll")]
    private static extern bool PathIsNetworkPath(string Path);

    [STAThread]
    static void Main(string[] args)
    {
        string strPath = "D:\\Temp\\tmpfile.txt";
        bool blnIsLocalPath = IsLocalPath(strPath);
        Console.WriteLine(blnIsLocalPath.ToString());
        Console.ReadLine();
    }

    private static bool IsLocalPath(string Path)
    {
        return !PathIsNetworkPath(Path);
    }
 }

需要考虑的事项:

  • 以两个反斜杠字符 (\) 开头的路径被解释为通用命名约定 (UNC) 路径。
  • 以字母开头后跟冒号 (:) 的路径被解释为已安装的网络驱动器。但是,PathIsNetworkPath 无法识别通过 Microsoft MS-DOS SUBST 命令或 DefineDosDevice 函数映射到驱动器号的网络驱动器
于 2011-08-10T14:02:54.200 回答
0
var dirInfo = new DirectoryInfo(yourPath);
var driveInfo = new DriveInfo(dirInfo.Root);
if (driveInfo.DriveType == DriveType.Network)
    Console.WriteLine("Is a network drive!");
于 2011-08-10T13:59:44.077 回答