How can I determine if a string is a local folder string or a network string?

元气小坏坏 提交于 2019-12-05 01:37:20

new Uri(mypath).IsUnc

I think the full answer to this question is to include usage of the DriveInfo.DriveType property.

public static bool IsNetworkPath(string path)
{
    if (!path.StartsWith(@"/") && !path.StartsWith(@"\"))
    {
        string rootPath = System.IO.Path.GetPathRoot(path); // get drive's letter
        System.IO.DriveInfo driveInfo = new System.IO.DriveInfo(rootPath); // get info about the drive
        return driveInfo.DriveType == DriveType.Network; // return true if a network drive
    }

    return true; // is a UNC path
}

Test the path to see if it begins with a slash char and if it does then it is a UNC path. In this case you will have to assume that it is a network path - in reality it may not be a path that points at a different PC as it could in theory be a UNC path that points to your local machine, but this isn't likely for most people I guess, but you could add checks for this condition if you wanted a more bullet-proof solution.

If the path does not begin with a slash char then use the DriveInfo.DriveType property to determine if it is a network drive or not.

Guy

See this answer to get the DriveInfo object for a file path

C# DriveInfo FileInfo

Use the DriveType from this to determine if it is a network path.

http://msdn.microsoft.com/en-us/library/system.io.driveinfo.drivetype.aspx

One more way to check whether path point to local or network drive:

var host = new Uri(@"\\foldera\folderb").Host; //returns "foldera"
if(!string.IsNullOrEmpty(host))
{
   //Network drive
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!