19

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"

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
user526731
  • 191
  • 1
  • 1
  • 3
  • 5
    Even a UNC path (starting with `\\\`) can be pointing to your local machine. – Oded Dec 01 '10 at 15:11
  • see http://stackoverflow.com/questions/520753/what-is-the-correct-way-to-check-if-a-path-is-an-unc-path-or-a-local-path/520796#520796 – nos Dec 01 '10 at 15:13
  • It is too late but this is perfect answer [link], hope this some one [1]: http://stackoverflow.com/questions/2243569/check-if-path-is-on-network#2244497 – mahmoodels Nov 28 '13 at 08:18
  • possible duplicate of [Method to determine if path string is local or remote machine](http://stackoverflow.com/questions/354477/method-to-determine-if-path-string-is-local-or-remote-machine) – Drake Jun 11 '14 at 15:04

4 Answers4

30

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.

Kev
  • 1,832
  • 1
  • 19
  • 24
  • Isn't this wrong for rooted paths like '/tmp/file.txt', even though it's not specified in the examples above? – Snowbear May 05 '23 at 15:07
23

new Uri(mypath).IsUnc

jtdubs
  • 13,585
  • 1
  • 17
  • 12
7

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

Community
  • 1
  • 1
Guy
  • 3,353
  • 24
  • 28
  • 1
    The `DriveInfo` won't work with netowrk paths like `\\foldera\folderb` throwing an `ArgumentException' – Phate01 Apr 11 '20 at 15:16
1

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
}
Vasyl Senko
  • 1,779
  • 20
  • 33