Search code examples
c#.netnetwork-drive

Easiest way in C# to find out if an app is running from a network drive?


I want to programmatically find out if my application is running from a network drive. What is the simplest way of doing that? It should support both UNC paths (\\127.0.0.1\d$) and mapped network drives (Z:).


Solution

  • This is for mapped drive case. You can use the DriveInfo class to find out whether drive a is a network drive or not.

    DriveInfo info = new DriveInfo("Z");
    if (info.DriveType == DriveType.Network)
    {
        // Running from network
    }
    

    Complete method and Sample Code.

    public static bool IsRunningFromNetwork(string rootPath)
    {
        try
        {
            System.IO.DriveInfo info = new DriveInfo(rootPath);
            if (info.DriveType == DriveType.Network)
            {
                return true;
            }
            return false;
        }
        catch
        {
            try
            {
                Uri uri = new Uri(rootPath);
                return uri.IsUnc;
            }
            catch
            {
                return false;
            }
        }
    }
    
    static void Main(string[] args) 
    {
        Console.WriteLine(IsRunningFromNetwork(System.IO.Path.GetPathRoot(AppDomain.CurrentDomain.BaseDirectory)));    }