首页 > 编程语言 >C# 获取本地共享目录和网络共享目录

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

时间:2023-05-05 15:24:45浏览次数:37  
标签:null string C# System public int 网络共享 networkName 目录

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.网络共享账户和密码存下来的地方:

 

标签:null,string,C#,System,public,int,网络共享,networkName,目录
From: https://www.cnblogs.com/wuguoqiang/p/17374196.html

相关文章

  • npm ERR! code EPERM npm ERR! syscall mkdir npm ERR! path C:\Program Files\node
    npm项目初始化代码npminit--yesidea代码安装npmnpmiexperss我输入的时候报错了,如下图所示没关系,只需要手动打开C盘的路径文件找到这个文件,并且把他Ctrl+D删除掉即可之后在运行这串代码就可以啦明显成功了......
  • C# Pdf添加文本水印(iTextSharp)
    第一步通过Nuget添加iTextSharp引用具体实现代码如下:///<summary>///添加文本水印///</summary>///<paramname="pdfPath">pdf文件</param>///<paramname="outPath">输出文件位置</param>......
  • C# 通过iTextSharp实现关键字签字盖章(通过在内容中插入盖章图片的形式)
    此功能通过 iTextSharp 读取PDF文档信息,并循环查找每一页PDF文件,在整个PDF中只要是符合条件的地方都会盖章,如只需要在最后一页盖章,请将方法中For循环去掉,并将PdfContentBytecontentByte=pdfStamper.GetUnderContent(i);parser.ProcessContent<PdfLocation>(i,location);......
  • Apache 配置https虚拟主机
    一、安装带ssl的Apache2.2.211、安装apache之前需要先检查openssl是否安装完毕,yumlist"*openssl*",如果没有用yum安装下即可2、apache安装,网上文档很多,以下是专门针对ssl的编译参数#cd/usr/local/src/tarbag#wgethttp://labs.renren.com/apache-mirror//httpd/httpd-2.2......
  • C# 通过ICSharpCode.SharpZipLib实现文件压缩下载
    通过管理NuGet包添加ICSharpCode.SharpZipLib引用以完成,多文件或者文件夹压缩后下载效果1、压缩文件实体类///<summary>///文件路径集合,文件名集合,压缩文件名///</summary>publicclassFileNameListZip{///<summary>///文件路......
  • Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified
    导入一个新的springbootmaven项目启动一直报这个错,查出来的答案都说是加注解把数据库扫描给排除掉,这种方式其实有点鸵鸟,项目原先是没问题的,现在导入到自己的环境启动不起来,那肯定是不能去改动代码的。排查了一遍,发现是项目中的resources文件没有指定成资源文件,所以找不到数据库......
  • C#生成二维码(【ThoughtWorks.QRCode】【QRCoder】【ZXing.Net】)
    1、通过ThoughtWorks.QRCode实现生成二维码,可直接通过添加Nuget包引用///<summary>///ThoughtWorks.QRCode生成二维码///</summary>///<paramname="filePath">二维码生成后保存地址</param>///<paramname="qrCo......
  • Vue3 开发必备的 VSCode 插件
    分享6个Vue3开发必备的VSCode插件,可以直接用过VSCode的插件中心直接安装使用。1、Volar相信使用VSCode开发Vue2的同学一定对Vetur插件不会陌生,作为Vue2配套的VSCode插件,它的主要作用是对Vue单文件组件提供高亮、语法支持以及语法检测。而随着Vue3正式......
  • 《花雕学AI》31:ChatGPT--用关键词/咒语/提示词Prompt激发AI绘画的无限创意!
    你有没有想过用AI来画画?ChatGPT是一款基于GPT-3的聊天模式的AI绘画工具,它可以根据你输入的关键词/咒语/提示词Prompt来生成不同风格和主题的画作。Prompt是一些简短的文字,可以用来指导ChatGPT的创作过程。在这篇文章中,我将展示一些用ChatGPT和不同的Prompt创造出来的有趣和创意的A......
  • Linux系统目录架构
    1.目录树结构图,如下:2.每个目录的具体功能描述boot:包括内核和其他系统启动时使用的文件。root:系统管理员、超级用户root的默认主目录。dev:存放设备文件的目录,linux系统把所有的设备都看成是一个文件。bin:存放可执行文件命令的地方,一般用户可以操作这些命令,比如ls,pwd等外部......