65.9K
CodeProject 正在变化。 阅读更多。
Home

使用凭据连接到 UNC 路径

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.83/5 (46投票s)

2009年10月16日

CPOL

2分钟阅读

viewsIcon

951427

downloadIcon

23558

使用 NetApi32 建立和断开到 UNC 路径的连接,使用指定的用户凭据。

Connection.jpg

引言

本文演示了如何通过 UNC 路径连接到远程资源并传递用户凭据。它实现了 IDisposable 接口,因此您可以在 using() 块中使用它。

背景

我有一个 ASP.NET 站点,我想访问网络资源,但由于代码在 ASP 用户下运行,因此没有足够的共享权限。我还有一个服务,每天晚上在两个不同域的文件共享之间复制文件。我希望有一种访问远程资源的方法,而无需通过更改权限或以特权用户身份运行来打开安全漏洞。

使用代码

UNCAccessWithCredentials 类实现了 Win32 方法 NetUseAdd()NetUseDel() 来创建远程连接。使用 NetUseAdd 添加的连接在资源管理器中不可见。激活时,它们将通过 DOS Net Use 命令显示。

类还实现了 IDisposable 接口,以便我们可以使用 using() 块。到达块的末尾时,该类会在其 Dispose() 方法中自动断开 UNC 连接。

using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials())
{
    if (unc.NetUseWithCredentials(uncpath, user, domain, password))
    {
        // Insert your code that requires access to the UNC resource
    }
    else
    {
        // The connection has failed. Use the LastError to get the system error code
        MessageBox.Show("Failed to connect to " + tbUNCPath.Text + 
                        "\r\nLastError = " + unc.LastError.ToString(),
                        "Failed to connect",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
    }
// When it reaches the end of the using block, the class deletes the connection.
}

如果您需要持久连接,请声明类的实例并使用 NetUseWithCredentials() 方法进行连接。连接后,您可以根据需要访问远程资源,直到断开连接。不要忘记在使用完 NetUseDelete() 方法后删除连接。

解释错误

Error.jpg

如果方法失败,它们将返回 false。如果发生这种情况,请使用类的 LastError 属性获取 Windows 系统错误代码。您可以使用 MSDN 系统错误代码 页面获取错误的描述。

在上面的错误中,错误 53 是 ERROR_BAD_NETPATH - “找不到网络路径”。看来我指定了错误的服务器或共享路径。

关注点

在研究如何执行此任务时,我发现了很多有趣的技巧可以完成工作,但并不理想。有些使用 LogonUser() 方法,只有当您的远程用户在执行机器上具有登录权限时才有效。我还发现了一些程序员运行 shell net use 命令的情况。

使用 API NetUseAdd 方法,我们可以在代码中控制该过程,而无需破解权限或诉诸 DOS 命令。

我找不到在托管代码中执行此操作的方法。如果您知道,请发布您的解决方案。我很乐意看到它。

© . All rights reserved.