WNetAddConnection2失败但网络使用成功

时间:2015-02-05 17:14:28

标签: c# network-programming

我正在尝试使用WNetAddConnection2连接到网络资源,但失败时出现错误代码ERROR_BAD_NET_NAME(错误代码67)。

但如果使用" net use"尽管命令具有相同的用户名和密码。

任何线索?

public class NETRESOURCE
    {
        public int dwScope;
        public int dwType;
        public int dwDisplayType;
        public int dwUsage;
        public string LocalName;
        public string RemoteName;
        public string Comment;
        public string Provider;
    }
    [DllImport("mpr.dll")]
    public static extern int WNetAddConnection2(NETRESOURCE netResource, string password, string username, int flags);

    public class ServerConnect
    {
        private string serverName;
        private string userName;
        private string password;
        public int nResult;

        public ServerConnect()
        {
            serverName = "";
            userName = "";
            password = "";
            nResult = -1;
        }
        public void SetConnectionParam(string serName, string uName, string pwd)
        {
            serverName = serName;
            userName = uName;
            password = pwd;
        }

        public void Connect()
        {
            NETRESOURCE myResource = new NETRESOURCE();
            myResource.dwScope = 0;
            myResource.dwType = 0x00000001; //RESOURCETYPE_DISK
            myResource.dwDisplayType = 0;
            myResource.LocalName = "";
            myResource.RemoteName = serverName;
            myResource.dwUsage = 0;
            myResource.Comment = "";
            myResource.Provider = "";
            nResult = WNetAddConnection2(myResource, password, userName, 0);     


        }
    };

    public void ConnectToDataServer(string serverName)
    {
        ServerConnect oConnect = new ServerConnect();
        oConnect.SetConnectionParam(serverName, @"Domain\username", @"password");
        Thread connectionThread = new Thread(new ThreadStart(oConnect.Connect));
        connectionThread.Start();
        while (!connectionThread.IsAlive) ;// Wait till thread starts and Alive
        int nCount = 0;
        while (connectionThread.IsAlive)
        {
            Thread.Sleep(500);
            nCount++;
            if (nCount == 10) // wait for 5 secs
            {
                //WriteLine(this, "Failed to Connect to to server " + serverName , LogStatus.Error);
                connectionThread.Abort();
                Thread.Sleep(1000);
            }
        }
        //WriteLine(this, oConnect.nResult.ToString(), LogStatus.Success);
    }
    public void ConnectToServer()
    {

        ConnectToDataServer(@"\\ServerName");
}

1 个答案:

答案 0 :(得分:0)

首先,我们需要查看您的代码,因为WNetAddConnection2是Windows函数,因此是P / Invoked,而P / Invoke操作总是非常非常繁琐。

在假设您已正确调用的注释中,可能存在权限(如果您运行的是Windows 8,则尤其如此)。当你支持VS时,请确保Run as Administrator,因为这通常会将相同的凭据扩展到执行应用程序,而控制台通常具有不同的权限。