Method to determine if path string is local or remote machine

David Boike picture David Boike · Dec 9, 2008 · Viewed 26.6k times · Source

What's the best way, using C# or other .NET language, to determine if a file path string is on the local machine or a remote server?

It's possible to determine if a path string is UNC using the following:

new Uri(path).IsUnc

That works great for paths that start with C:\ or other drive letter, but what about paths like:

\\machinename\sharename\directory
\\10.12.34.56\sharename\directory

...where both refer to the local machine - these are UNC paths but are still local.

Answer

Renato Heeb picture Renato Heeb · Dec 13, 2010

This is how I did it.

    public static bool IsLocal(DirectoryInfo dir)
    {
        foreach (DriveInfo d in DriveInfo.GetDrives())
        {
            if (string.Compare(dir.Root.FullName, d.Name, StringComparison.OrdinalIgnoreCase) == 0) //[drweb86] Fix for different case.
            {
                return (d.DriveType != DriveType.Network);
            }
        }
         throw new DriveNotFoundException();
    }