使用C#,如何知道文件夹是否位于网络上

时间:2011-08-10 13:52:35

标签: c# network-programming getfiles getfileversion

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

我该怎么做?

6 个答案:

答案 0 :(得分:6)

如果您在谈论映射的网络驱动器,可以使用DriveInfo的{​​{3}}:

var driveInfo = new DriveInfo("S:\");
if(driveInfo.DriveType == DriveType.Network)
    // do something

答案 1 :(得分:4)

来自另一个SO问题的{p> Original AnswerCheck if path is on network

使用PathIsNetworkPath(pinvoke reference):

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

    static void Main(string[] args)
    {
        Console.WriteLine(PathIsNetworkPath("i:\Backup"));
    }
}

答案 2 :(得分: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;
}

答案 3 :(得分:0)

var dirInfo = new DirectoryInfo(yourPath);
var driveInfo = new DriveInfo(dirInfo.Root);
if (driveInfo.DriveType == DriveType.Network)
    Console.WriteLine("Is a network drive!");

答案 4 :(得分: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函数识别映射到驱动器号的网络驱动器

答案 5 :(得分:0)

您可以使用folowing方法获取文件夹的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;
    }