当前位置:首页 > C#教程 > C#高级

C# 带用户密码访问网络共享

原文:C# 带用户密码访问网络共享

调用WNetUseConnection API

函数详细参数参考:https://msdn.microsoft.com/en-us/library/windows/desktop/aa385482(v=vs.85).aspx

 

C# 调用WNetUseConnection连接共享类的代码:

NetworkShareConnect.cs

//引入命名空间
//using System.Runtime.InteropServices;publicclass NetworkShareConnect
    {
        #region WNetUseConnection枚举参数
        //dwScopeconstint RESOURCE_CONNECTED = 0x00000001;
        constint RESOURCE_GLOBALNET = 0x00000002;
        constint RESOURCE_REMEMBERED = 0x00000003;

        //dwTypeconstint RESOURCETYPE_ANY = 0x00000000;
        constint RESOURCETYPE_DISK = 0x00000001;
        constint RESOURCETYPE_PRINT = 0x00000002;

        //dwDisplayTypeconstint RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
        constint RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
        constint RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
        constint RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
        constint RESOURCEDISPLAYTYPE_FILE = 0x00000004;
        constint RESOURCEDISPLAYTYPE_GROUP = 0x00000005;

        //dwUsageconstint RESOURCEUSAGE_CONNECTABLE = 0x00000001;
        constint RESOURCEUSAGE_CONTAINER = 0x00000002;

        //dwFlagsconstint CONNECT_INTERACTIVE = 0x00000008;
        constint CONNECT_PROMPT = 0x00000010;
        constint CONNECT_REDIRECT = 0x00000080;
        constint CONNECT_UPDATE_PROFILE = 0x00000001;
        constint CONNECT_COMMANDLINE = 0x00000800;
        constint CONNECT_CMD_SAVECRED = 0x00001000;

        constint CONNECT_LOCALDRIVE = 0x00000100;
        #endregion#region Errors参数
        constint NO_ERROR = 0;

        constint ERROR_ACCESS_DENIED = 5;
        constint ERROR_ALREADY_ASSIGNED = 85;
        constint ERROR_BAD_DEVICE = 1200;
        constint ERROR_BAD_NET_NAME = 67;
        constint ERROR_BAD_PROVIDER = 1204;
        constint ERROR_CANCELLED = 1223;
        constint ERROR_EXTENDED_ERROR = 1208;
        constint ERROR_INVALID_ADDRESS = 487;
        constint ERROR_INVALID_PARAMETER = 87;
        constint ERROR_INVALID_PASSWORD = 1216;
        constint ERROR_MORE_DATA = 234;
        constint ERROR_NO_MORE_ITEMS = 259;
        constint ERROR_NO_NET_OR_BAD_PATH = 1203;
        constint ERROR_NO_NETWORK = 1222;

        constint ERROR_BAD_PROFILE = 1206;
        constint ERROR_CANNOT_OPEN_PROFILE = 1205;
        constint ERROR_DEVICE_IN_USE = 2404;
        constint ERROR_NOT_CONNECTED = 2250;
        constint ERROR_OPEN_FILES = 2401;

        privatestruct ErrorClass
        {
            //定义错误类结构体publicint num;
            publicstring message;
            public ErrorClass(int num, string message)
            {
                this.num = num;
                this.message = message;
            }
        }


        //连接失败信息汇总privatestatic ErrorClass[] ERROR_LIST = new ErrorClass[] {
            new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), 
            new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), 
            new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), 
            new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), 
            new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), 
            new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), 
            new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), 
            new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), 
            new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), 
            new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), 
            new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), 
            new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), 
            new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), 
            new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), 
            new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), 
            new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), 
            new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), 
            new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), 
            new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), 
            new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), 
        };

        privatestaticstring getErrorForNumber(int errNum)
        {
            //遍历获得错误代码foreach (ErrorClass er in ERROR_LIST)
            {
                if (er.num == errNum) return er.message;
            }
            return"Error: Unknown, " + errNum;
        }
        #endregion//调用系统函数WNetUseConnection
        //用于连接共享
        [DllImport("Mpr.dll")]
        privatestaticexternint WNetUseConnection(
            IntPtr hwndOwner,
            NETRESOURCE lpNetResource,
            string lpPassword,
            string lpUserID,
            int dwFlags,
            string lpAccessName,
            string lpBufferSize,
            string lpResult
            );
        //用于删除连接
        [DllImport("Mpr.dll")]
        privatestaticexternint WNetCancelConnection2(
            string lpName,
            int dwFlags,
            bool fForce
            );

        [StructLayout(LayoutKind.Sequential)]
        privateclass NETRESOURCE
        {
            publicint dwScope = 0;
            publicint dwType = 0;
            publicint dwDisplayType = 0;
            publicint dwUsage = 0;
            publicstring lpLocalName = "";//映射到本地的盘符,如"Z:"。不做驱动器映射,可为空publicstring lpRemoteName = "";//共享的网络路径publicstring lpComment = "";
            publicstring lpProvider = "";
        }

        ///<summary>/// 连接共享
        ///</summary>///<param name="remoteUNC">共享网络路径</param>///<param name="username">登录用户名</param>///<param name="password">密码</param>///<returns></returns>publicstaticstring connectToShare(string remoteUNC, string username, string password)
        {
            return connectToRemote(remoteUNC, username, password, false);
        }

        ///<summary>/// 没用户密码连接
        ///</summary>///<param name="remoteUNC">共享网络路径</param>///<returns></returns>publicstaticstring connectToShare(string remoteUNC)
        {
            return connectToRemote(remoteUNC, "", "", true);
        }

        privatestaticstring connectToRemote(string remoteUNC, string username, string password, bool promptUser)
        {
            NETRESOURCE nr = new NETRESOURCE
            {
                dwType = RESOURCETYPE_DISK,
                lpRemoteName = remoteUNC
            };

            int ret;
            if (promptUser)
                ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
            else
                ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);

            if (ret == NO_ERROR) returnnull;
            return getErrorForNumber(ret);
        }

        publicstaticstring disconnectRemote(string remoteUNC)
        {
            int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false);
            if (ret == NO_ERROR) returnnull;
            return getErrorForNumber(ret);
        }
    }

 

测试:

技术分享

 

注意:断开共享后,系统缓存还在,没能即时失去连接,在1-3分钟内仍然可以访问共享。

有时候要注销才能失去连接,原因未明 %>_<%

原文:http://www.cnblogs.com/lonelyxmas/p/4248000.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐