C# 获取本地共享目录和网络共享目录

1.在工程添加对应的cs文件

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;

namespace XXX
{
    public class NetworkConnection : IDisposable
    {
        public string networkName = null;
        bool disposed = false;

        public NetworkConnection(string networkName,
            NetworkCredential credentials)
        {
            var netResource = new NetResource()
            {
                Scope = ResourceScope.GlobalNetwork,
                ResourceType = ResourceType.Any,
                //DisplayType = ResourceDisplaytype.Share,
                RemoteName = networkName
            };

            var result = 0;

            if (credentials == null)  //connent exist
            {
                result = WNetAddConnection2(
                netResource,
                null,
                null,
                0);
            }
            else //connect is not exist  
            {
                var userName = string.IsNullOrEmpty(credentials.Domain)
                    ? credentials.UserName
                    : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);

                result = WNetAddConnection2(
                netResource,
                credentials.Password,
                userName,
                0);
            }
            

            if (result != 0)
            {
                //throw new Win32Exception(result);
                this.networkName = null;
            }
            else
            {
                this.networkName = networkName;
            }
        }

        ~NetworkConnection()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
                return;

            WNetCancelConnection2(networkName, 0, true);

            disposed = true;
        }

        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2(NetResource netResource,
            string password, string username, int flags);

        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2(string name, int flags,
            bool force);



        [StructLayout(LayoutKind.Sequential)]
        protected struct SHARE_INFO_1
        {
            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi1_netname;
            [MarshalAs(UnmanagedType.U4)]
            public uint shi1_type;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi1_remark;
        }
        [DllImport("Netapi32.dll", EntryPoint = "NetShareEnum")]
        protected static extern int NetShareEnum(
        [MarshalAs(UnmanagedType.LPWStr)] string servername,
        [MarshalAs(UnmanagedType.U4)] uint level,
        out IntPtr bufptr,
        [MarshalAs(UnmanagedType.U4)] int prefmaxlen,
        [MarshalAs(UnmanagedType.U4)] out uint entriesread,
        [MarshalAs(UnmanagedType.U4)] out uint totalentries,
        [MarshalAs(UnmanagedType.U4)] out uint resume_handle
        );

        [DllImport("Netapi32.dll")]
        public static extern int NetApiBufferFree(IntPtr lpBuffer);

        public static List<string> NetShareList(string server)
        {
            IntPtr buffer;
            uint entriesread;
            uint totalentries;
            uint resume_handle;

            List<string> share = new List<string>();

            do
            {
                //-1应该是获取所有的share,msdn里面的例子是这么写的,返回0表示成功
                int Status = NetShareEnum(server, 1, out buffer, -1, out entriesread, out totalentries, out resume_handle);

                if (Status == 0)    //ERROR_SUCCESS
                {
                    Int32 ptr = buffer.ToInt32();
                    ArrayList alShare = new ArrayList();
                    for (int i = 0; i < entriesread; i++)
                    {

                        SHARE_INFO_1 shareInfo = (SHARE_INFO_1)Marshal.PtrToStructure(new IntPtr(ptr), typeof(SHARE_INFO_1));
                        if (shareInfo.shi1_type == 0)//Disk drive类型
                        {
                            alShare.Add(shareInfo.shi1_netname);
                        }
                        ptr += Marshal.SizeOf(shareInfo);//有点类似C代码
                    }
                    
                    for (int i = 0; i < alShare.Count; i++)
                    {
                        share.Add(alShare[i].ToString());
                    }

                    NetApiBufferFree(buffer);

                    return share;
                }
                else if (Status == 234)    //ERROR_MORE_DATA
                {

                }
                else
                {
                    return null;
                }

            } while (true);  
        }
    }

    public class Win32Api
    {
        enum FORMAT_MESSAGE : uint
        {
            ALLOCATE_BUFFER = 0x00000100,
            IGNORE_INSERTS = 0x00000200,
            FROM_SYSTEM = 0x00001000,
            ARGUMENT_ARRAY = 0x00002000,
            FROM_HMODULE = 0x00000800,
            FROM_STRING = 0x00000400
        }

        [DllImport("kernel32.dll")]
        static extern int FormatMessage(FORMAT_MESSAGE dwFlags, IntPtr lpSource, int dwMessageId, uint dwLanguageId, out StringBuilder msgOut, int nSize, IntPtr Arguments);

        public static string GetErrorString(int lastError)
        {
            if (0 == lastError) return ("");
            else
            {
                StringBuilder msgOut = new StringBuilder(256);
                int size = FormatMessage(FORMAT_MESSAGE.ALLOCATE_BUFFER | FORMAT_MESSAGE.FROM_SYSTEM | FORMAT_MESSAGE.IGNORE_INSERTS,
                              IntPtr.Zero, lastError, 0, out msgOut, msgOut.Capacity, IntPtr.Zero);
                return (msgOut.ToString().Trim());
            }
        }

        public enum LangID
        {
            LANG_ENGLISH = 1033,
            LANG_JAPANESE = 1041,
            LANG_SIMPLIFIED_CHINESE = 2052,
            LANG_TRADITIONAL_CHINESE = 1028,
            LANG_KOREAN = 1042,
        }

        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern System.UInt16 GetThreadUILanguage();

        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern System.UInt16 SetThreadUILanguage(System.UInt16 LangId);

    }

    [StructLayout(LayoutKind.Sequential)]
    public class NetResource
    {
        public ResourceScope Scope;
        public ResourceType ResourceType;
        public ResourceDisplaytype DisplayType;
        public int Usage;
        public string LocalName;
        public string RemoteName;
        public string Comment;
        public string Provider;
    }

    public enum ResourceScope : int
    {
        Connected = 1,
        GlobalNetwork,
        Remembered,
        Recent,
        Context
    };

    public enum ResourceType : int
    {
        Any = 0,
        Disk = 1,
        Print = 2,
        Reserved = 8,
    }

    public enum ResourceDisplaytype : int
    {
        Generic = 0x0,
        Domain = 0x01,
        Server = 0x02,
        Share = 0x03,
        File = 0x04,
        Group = 0x05,
        Network = 0x06,
        Root = 0x07,
        Shareadmin = 0x08,
        Directory = 0x09,
        Tree = 0x0a,
        Ndscontainer = 0x0b
    }
}

2.访问本地共享目录

public List<string> GetShareName()
{       
    //获取本机共享目录,传入null就好了
    return NetworkConnection.NetShareList(null);
}

3.访问网络上的共享目录

public string GetMachineFromIPAddress(string ipAddress)
        {
            string machineName = null;

            try
            {
                if(ipAddress != string.Empty)
                {
                    IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress);
                    machineName = hostEntry.HostName;
                    machineName = machineName.Substring(0, machineName.IndexOf('.'));
                }
            }
            catch(Exception ex)
            {

            }
            return machineName;
        }

        public string GetIPAddressFromMachine(string machineName)
        {
            string ipAddress = null;

            try
            {
                if (machineName != string.Empty)
                {
                    ipAddress = Dns.GetHostAddresses(machineName)[0].ToString();   
                }
            }
            catch (Exception ex)
            {

            }
            return ipAddress;
        }

        public List<string> GetPcShareFileList(string hostName)
        {
            try
            {
                string sharingUserName = null;
                string sharingPassword = null;

                string networkName = "\\\\" + hostName + "\\IPC$";

                List<string> FileNameList = null;

                NetworkConnection NetworkConn = new NetworkConnection(networkName, null);

                if(NetworkConn.networkName == null)
                {                                       
                    //需要传入用户名和密码
                    NetworkConn = new NetworkConnection(networkName, new NetworkCredential(sharingUserName, sharingPassword));
                }

                if (NetworkConn.networkName != null && hostName != null && hostName != string.Empty)
                {
                    FileNameList = NetworkConnection.NetShareList(hostName);

                    if (FileNameList == null)
                    {
                        if ((hostName.Length - hostName.Replace(".", "").Length) == 3)  //ip
                        {
                            FileNameList = NetworkConnection.NetShareList(GetMachineFromIPAddress(hostName));
                        }
                        else  //machine name 
                        {
                            FileNameList = NetworkConnection.NetShareList(GetIPAddressFromMachine(hostName));  
                        }
                    }
                }                               

                return FileNameList;
            }
            catch(Exception ex)
            {

            }

            return null;
        }

后面是测试可能遇到的问题:

1.解决访问共享时提示多重连接的问题

cmd中执行以下的命令:net use * /delete

2.查看新的网络连接

cmd中的命令: net use

3.网络共享账户和密码存下来的地方:

 

posted on 2023-05-05 15:07  wu.g.q  阅读(600)  评论(0编辑  收藏  举报

导航