首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用用户名和密码连接到网络驱动器

使用用户名和密码连接到网络驱动器
EN

Stack Overflow用户
提问于 2010-09-13 21:32:26
回答 9查看 128.5K关注 0票数 27

如何提供凭据以便可以连接到.NET中的网络驱动器?

我正在尝试从网络驱动器检索文件,需要提供用户凭据才能访问该驱动器。

EN

回答 9

Stack Overflow用户

发布于 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");
票数 18
EN

Stack Overflow用户

发布于 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
        );

Example code here

票数 14
EN

Stack Overflow用户

发布于 2010-09-13 21:37:40

您可以使用WindowsIdentity类(带有logon token)在读取和写入文件时进行模拟。

var windowsIdentity = new WindowsIdentity(logonToken);
using (var impersonationContext = windowsIdentity.Impersonate()) {
    // Connect, read, write
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3700871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档