Tuesday, 18 February 2014

Find and List network shares in C# using WMI, Registry and DirectoryEntry

Description:

In this article, I am going to write C# code examples to find and list network shares and share folder's local path in C# using WMI and enumerates network shares without WMI through Registry and Directory Entry in C#.

Summary:


Find and List Network Shares in C# using WMI

   You can get or lists network shares or share folders in C# using WMI API functions, to use WMI API functions, we need to add reference System.Management.
using System.Collections.Generic;
using System.Management;
using System;

namespace EnumerateShares
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Server Name:");
            string serverName = Console.ReadLine();
            Console.WriteLine("-------------");
            List<string> shares = GetNetworkShareFoldersList(serverName);
            foreach (string share in shares)
            {
                Console.WriteLine(share);
                Console.WriteLine("-------------");
            }
            Console.ReadLine();
        }

        public static List<string> GetNetworkShareFoldersList(string serverName)
        {
            List<string> shares = new List<string>();

            // do not use ConnectionOptions to get shares from local machine
            ConnectionOptions connectionOptions = new ConnectionOptions();
            //connectionOptions.Username = @"Domain\Administrator";
            //connectionOptions.Password = "password";
            //connectionOptions.Impersonation = ImpersonationLevel.Impersonate;

            ManagementScope scope = new ManagementScope("\\\\" + serverName + "\\root\\CIMV2",
                                                        connectionOptions);
            scope.Connect();

            ManagementObjectSearcher worker = new ManagementObjectSearcher(scope, 
                               new ObjectQuery("select Name from win32_share"));

            foreach (ManagementObject share in worker.Get())
            {
                shares.Add(share["Name"].ToString());
            }
            return shares;
        }
    }
}

Find and Lists Network Shares and Share's Local Path in C# using WMI

   You can also enumerates or lists network shares and share folder's local path (ex: C path: C:\Shares\FinanceShare) using WMI API functions, to use WMI API functions, we need to add reference System.Management.
using System.Collections.Generic;
using System.Management;
using System;

namespace EnumerateShares
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Server Name:");
            string serverName = Console.ReadLine();
            Console.WriteLine("-------------");
            Dictionary<string,string> shares = GetNetworkShareDetailUsingWMI(serverName);
            foreach (KeyValuePair<string,string> share in shares)
            {
                Console.WriteLine(share.Key + ": " + share.Value);
                Console.WriteLine("-------------");
            }
            Console.ReadLine();
        }

        public static Dictionary<string, string> GetNetworkShareDetailUsingWMI(string serverName)
        {
            Dictionary<string, string> shares = new Dictionary<string, string>();

            // do not use ConnectionOptions to get shares from local machine
            ConnectionOptions connectionOptions = new ConnectionOptions();
            //connectionOptions.Username = @"Domain\Administrator";
            //connectionOptions.Password = "password";
            //connectionOptions.Impersonation = ImpersonationLevel.Impersonate;

            ManagementScope scope = new ManagementScope("\\\\" + serverName + "\\root\\CIMV2",
                                                            connectionOptions);
            scope.Connect();

            ManagementObjectSearcher worker = new ManagementObjectSearcher(scope,
                                        new ObjectQuery("select Name,Path from win32_share"));
            foreach (ManagementObject share in worker.Get())
            {
                shares.Add(share["Name"].ToString(), share["Path"].ToString());
            }
            return shares;
        }
    }
}

Enumerates or Lists Network Shares in C# without WMI though Registry

   The network share folders information are stored in Registry in the following registry path: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Shares. So you can also enumerates or lists network shares and share folder's local path through Registry in C#.
using System.Collections.Generic;
using System;
using System.Linq;
using Microsoft.Win32;

namespace EnumerateShares
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Server Name:");
            string serverName = Console.ReadLine();
            Console.WriteLine("-------------");
            Dictionary<string,string> shares = GetNetworkShareDetailUsingRegistry(serverName);
            foreach (KeyValuePair<string,string> share in shares)
            {
                Console.WriteLine(share.Key + ": " + share.Value);
                Console.WriteLine("-------------");
            }
            Console.ReadLine();
        }

        public static Dictionary<string, string> GetNetworkShareDetailUsingRegistry(string serverName)
        {
            Dictionary<string, string> shares = new Dictionary<string, string>();

            using (RegistryKey reg = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, serverName))
            {
                using (RegistryKey key = reg.OpenSubKey(@"SYSTEM\CurrentControlSet\services\LanmanServer\Shares"))
                {
                    foreach (string shareName in key.GetValueNames())
                    {
                        // Network share local path
                        List<string> keyValues=((string[])key.GetValue(shareName)).ToList();
                        string shareLocalPath = 
                       keyValues.Where(a => a.StartsWith("Path=")).FirstOrDefault().Substring(5);
                        shares.Add(shareName, shareLocalPath);
                    }
                }
            }
                           
            return shares;
        }
    }
}

Find and List Network Shares in C# using DirectoryEntry

   You can also enumerates or lists network shares using DirectoryEntry and IADsFileShare API in C#. To use DirectoryEntry, you need to add reference System.DirectoryServices from .NET library(tab) and to use IADsFileShare, you need to reference ActiveDs from Com library.

Note: You can't get share folder's local path by this method.
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using ActiveDs;

namespace EnumerateShares
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Server Name:");
            string serverName = Console.ReadLine();
            Console.WriteLine("-------------");
            List<string> shares = GetNetworkSharesUsingActiveDSLib(serverName);
            foreach (string share in shares)
            {
                Console.WriteLine(share);
                Console.WriteLine("-------------");
            }
            Console.ReadLine();
        }

        public static List<string> GetNetworkSharesUsingActiveDSLib(string serverName)
        {
            List<string> shares = new List<string>();
            DirectoryEntry dirEntry = new DirectoryEntry("WinNT://" + serverName + "/LanmanServer");
            IADsContainer service = (IADsContainer)dirEntry.NativeObject;
            foreach (var info in service)
            {
                IADsFileShare shareInfo = (IADsFileShare)info;
                if (shareInfo.Class == "FileShare")
                {
                    shares.Add(shareInfo.Name);
                }
            }
            return shares;
        }
    }
}

Thanks,
Morgan
Software Developer Tha

Advertisements
Advertisements

No comments:

Post a Comment