using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management; using System.Runtime.InteropServices; namespace ConsoleApplication1 { class Class1 { #region Get remote share folder name, use Windows API NetShareEnum [DllImport("Netapi32.dll", CharSet = CharSet.Unicode)] private static extern NET_API_STATUS NetShareEnum( StringBuilder serverName, int level, ref IntPtr bufPtr, uint prefMaxLen, ref int entriesRead, ref int totalEntries, ref int resumeHandle ); [DllImport("Netapi32.dll", SetLastError = true)] static extern int NetApiBufferFree(IntPtr Buffer); public enum NET_API_STATUS : uint { NERR_Success = 0, NERR_InvalidComputer = 2351, NERR_NotPrimary = 2226, NERR_SpeGroupOp = 2234, NERR_LastAdmin = 2452, NERR_BadPassword = 2203, NERR_PasswordTooShort = 2245, NERR_UserNotFound = 2221, ERROR_ACCESS_DENIED = 5, ERROR_NOT_ENOUGH_MEMORY = 8, ERROR_INVALID_PARAMETER = 87, ERROR_INVALID_NAME = 123, ERROR_INVALID_LEVEL = 124, ERROR_MORE_DATA = 234, ERROR_SESSION_CREDENTIAL_CONFLICT = 1219 } [StructLayoutAttribute(LayoutKind.Sequential)] public struct _SHARE_INFO_0 { [MarshalAsAttribute(UnmanagedType.LPWStr)] public string shi0_netname; } public static void EnumNetShares(string remoteMachineName) { StringBuilder serverName = new StringBuilder(remoteMachineName); int level = 0; IntPtr bufPtr = IntPtr.Zero; uint prefMaxLen = 0xFFFFFFFF; int entriesRead = 0; int totalEntries = 0; int resumeHandle = 0; int structSize = Marshal.SizeOf(typeof(_SHARE_INFO_0)); NET_API_STATUS result = NetShareEnum(serverName, level, ref bufPtr, prefMaxLen, ref entriesRead, ref totalEntries, ref resumeHandle); if (result == NET_API_STATUS.NERR_Success) { IntPtr current = bufPtr; for (int i = 0; i < entriesRead; i++) { _SHARE_INFO_0 shareInfo = (_SHARE_INFO_0)Marshal.PtrToStructure(current, typeof(_SHARE_INFO_0)); Console.WriteLine(shareInfo.shi0_netname); current = new IntPtr(current.ToInt32() + structSize); } } else if (result == NET_API_STATUS.ERROR_MORE_DATA) { NetApiBufferFree(bufPtr); } else { // Something else. } } #endregion #region Get remote share folder name, use WMI private static void DisplayShareFolders(string computerName, string userName, string password) { string queryStr = "select * from Win32_Share"; ConnectionOptions co = new ConnectionOptions(); co.Username = userName; co.Password = password; ManagementScope ms = new ManagementScope(string.Format(@"\\{0}\root\cimv2", computerName), co); ms.Connect(); if (ms.IsConnected) { ObjectQuery query = new ObjectQuery(queryStr); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query)) { using (ManagementObjectCollection searchResult = searcher.Get()) { foreach (ManagementObject mo in searchResult) { foreach (PropertyData property in mo.Properties) { Console.WriteLine("Name:{0}\tPath:{1}", mo.Properties["Name"].Value.ToString(), mo.Properties["Path"].Value.ToString()); } } } } } } #endregion } }