tags:

views:

2546

answers:

2

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.

A: 

I don't know of a single method to check that. However, you can compare the Uri's Host property to either the local host name or IP address.

You can get the local machine name using:

string hostName = System.Net.Dns.GetHostName()

You can then get an array of IP addresses by passing that string to:

System.Net.IPAddress[] addresses = System.Net.Dns.GetHostAddresses(hostName);

Switch on the Uri's HostNameType property, probably UriHostNameType.Dns or UriHostNameType.IPv4, to match either the name or IP address.

+5  A: 

Don't know if there's a more efficient way of doing this, but it seems to work for me:

    IPAddress[] host;
    IPAddress[] local;
    bool isLocal = false;

    host = Dns.GetHostAddresses(uri.Host);
    local = Dns.GetHostAddresses(Dns.GetHostName());

    foreach (IPAddress hostAddress in host)
    {
        if (IPAddress.IsLoopback(hostAddress))
        {
            isLocal = true;
            break;
        }
        else
        {
            foreach (IPAddress localAddress in local)
            {
                if (hostAddress.Equals(localAddress))
                {
                    isLocal = true;
                    break;
                }
            }

            if (isLocal)
            {
                break;
            }
        }
    }
Eric Rosenberger