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

≯℡__Kan透↙ 提交于 2020-01-13 08:01:48

问题


How can I determine in c# if a string is a local folder string or a network string besides regular expression?

For example:

I have a string which can be "c:\a" or "\\foldera\folderb"


回答1:


new Uri(mypath).IsUnc




回答2:


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.




回答3:


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




回答4:


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
}


来源:https://stackoverflow.com/questions/4325712/how-can-i-determine-if-a-string-is-a-local-folder-string-or-a-network-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!