连接到网络共享时如何提供用户名和密码 [英] How to provide user name and password when connecting to a network share

查看:34
本文介绍了连接到网络共享时如何提供用户名和密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当连接到当前用户(在我的例子中是启用网络的服务用户)没有权限的网络共享时,必须提供名称和密码.

When connecting to a network share for which the current user (in my case, a network enabled service user) has no rights, name and password have to be provided.

我知道如何使用 Win32 函数(mpr.dll 中的 WNet* 系列)来实现这一点,但希望使用 .Net (2.0) 功能来实现.

I know how to do this with Win32 functions (the WNet* family from mpr.dll), but would like to do it with .Net (2.0) functionality.

有哪些可用的选项?

也许更多信息会有所帮助:

  • 用例是 Windows 服务,而不是 Asp.Net 应用程序.
  • 该服务在没有共享权限的帐户下运行.
  • 客户端不知道共享所需的用户帐户.
  • 客户端和服务器不是同一个域的成员.

推荐答案

您可以更改线程标识,或者 P/Invoke WNetAddConnection2.我更喜欢后者,因为我有时需要为不同的位置维护多个凭据.我将它包装成一个 IDisposable 并在之后调用 WNetCancelConnection2 以删除信用(避免多个用户名错误):

You can either change the thread identity, or P/Invoke WNetAddConnection2. I prefer the latter, as I sometimes need to maintain multiple credentials for different locations. I wrap it into an IDisposable and call WNetCancelConnection2 to remove the creds afterwards (avoiding the multiple usernames error):

using (new NetworkConnection(@"\server
ead", readCredentials))
using (new NetworkConnection(@"\server2write", writeCredentials)) {
   File.Copy(@"\server
eadfile", @"\server2writefile");
}

这篇关于连接到网络共享时如何提供用户名和密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆