首页 > 解决方案 > WNetAddConnection2 在某些站点中失败,错误代码为 1326,而网络使用成功

问题描述

我在 c# 中使用了一个小型控制台应用程序,代码基本上是从某个我忘记了其 url 的站点中获取的(对作者感到抱歉!),以测试 Windows 网络 API WNetAddConnection2 以列出指定文件夹中的 UNC 格式文件。该代码适用于大多数情况。具体来说,它可以在我办公室和大多数客户站点的许多机器上运行。但是,在特定客户端站点中,应用程序失败,错误代码为 1326(错误的名称或密码),有时错误代码为 86(错误的密码)。在这个特定的客户端站点中,“net use”成功了。因此,WNetAddConnection2 似乎以某种方式返回了一个误导性的错误代码。

我尝试将本地策略“网络安全:LAN Manager 身份验证级别”更改为“LM 和 NTLM - 如果协商使用 NTLMv2 会话安全”和“LM 和 NTLM”,但仍然失败。

我也试过打开防火墙的445、137、139端口,问题依旧。

公共类 NetworkConnection : IDisposable { 只读字符串 _networkName;

public NetworkConnection(string networkName, NetworkCredential credentials)
{
    _networkName = networkName;

    var netResource = new NetResource
    {
        Scope = ResourceScope.GlobalNetwork,
        ResourceType = ResourceType.Disk,
        DisplayType = ResourceDisplaytype.Share,
        RemoteName = networkName
    };

    var userName = string.IsNullOrEmpty(credentials.Domain)
        ? credentials.UserName
        : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);

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

    if (result != 0)
    {
        throw new Win32Exception(result, "Error connecting to remote share");
    }
}

~NetworkConnection()
{
    Dispose(false);
}

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

protected virtual void Dispose(bool disposing)
{
    WNetCancelConnection2(_networkName, 0, 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)]
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
}

}

非常感谢有关如何使我们的代码像“网络使用”一样工作或如何放松客户端站点施加的潜在网络限制的帮助。

标签: c#network-programming

解决方案


推荐阅读