当连接到当前用户(在我的例子中是启用网络的服务用户)没有权限的网络共享时,必须提供名称和密码。
我知道如何使用 Win32 函数(mpr.dll
中的 WNet*
系列)执行此操作,但我想使用 .Net (2.0) 功能执行此操作.
有哪些选项可用?
也许更多信息有帮助:
- 用例是 Windows 服务,而不是 Asp.Net 应用程序。
- 该服务在没有共享权限的帐户下运行。
- 客户端不知道共享所需的用户帐户。
- 客户端和服务器不是同一域的成员。
最佳答案
我喜欢 Mark Brackett的回答如此之多,以至于我自己进行了快速实现。这是如果其他人急需它:
public class NetworkConnection : IDisposable
{
string _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);
}
}
~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;
[MarshalAs(UnmanagedType.LPWStr)]
public string LocalName;
[MarshalAs(UnmanagedType.LPWStr)]
public string RemoteName;
[MarshalAs(UnmanagedType.LPWStr)]
public string Comment;
[MarshalAs(UnmanagedType.LPWStr)]
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# - 连接到网络共享时如何提供用户名和密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/295538/