如何提供凭据以便可以连接到.NET中的网络驱动器?
我正在尝试从网络驱动器检索文件,需要提供用户凭据才能访问该驱动器。
发布于 2014-03-13 20:36:59
非常优雅的解决方案,灵感来自this one。它只使用.Net库,不需要使用任何命令行或Win32应用程序接口。
可供参考的代码:
NetworkCredential theNetworkCredential = new NetworkCredential(@"domain\username", "password");
CredentialCache theNetCache = new CredentialCache();
theNetCache.Add(new Uri(@"\\computer"), "Basic", theNetworkCredential);
string[] theFolders = Directory.GetDirectories(@"\\computer\share");
发布于 2010-09-13 21:36:10
最好的方法是p/invoke WNetUseConnection。
[StructLayout(LayoutKind.Sequential)]
private class NETRESOURCE
{
public int dwScope = 0;
public int dwType = 0;
public int dwDisplayType = 0;
public int dwUsage = 0;
public string lpLocalName = "";
public string lpRemoteName = "";
public string lpComment = "";
public string lpProvider = "";
}
[DllImport("Mpr.dll")]
private static extern int WNetUseConnection(
IntPtr hwndOwner,
NETRESOURCE lpNetResource,
string lpPassword,
string lpUserID,
int dwFlags,
string lpAccessName,
string lpBufferSize,
string lpResult
);
发布于 2010-09-13 21:37:40
您可以使用WindowsIdentity类(带有logon token)在读取和写入文件时进行模拟。
var windowsIdentity = new WindowsIdentity(logonToken);
using (var impersonationContext = windowsIdentity.Impersonate()) {
// Connect, read, write
}
https://stackoverflow.com/questions/3700871
复制相似问题