如何显示凭据才能打开文件?

如何指定用户名和密码以便我的程序打开文件进行阅读? 需要访问该文件的程序是从一个对该文件所在文件夹没有读访问权限的帐户运行的。程序是用C#和.NET 2编写的,在XP下运行,文件在Windows Server 2003机器上。

您希望模拟有权访问该文件的用户。

我建议使用这样的类 – http://www.codeproject.com/KB/cs/zetaimpersonator.aspx 。 它隐藏了做模仿的所有令人讨厌的实现。

using (new Impersonator("myUsername", "myDomainname", "myPassword")) { string fileText = File.ReadAllText("c:\test.txt"); Console.WriteLine(fileText); } 

我使用过Nuget包NuGet Gallery | Simple Impersonation Library 1.1.0但还有其他; 搜索其他人的模拟。

使用交互式登录处理文件结构的示例用法:

 using (Impersonation.LogonUser("{domain}", "{UserName}", "{Password}", LogonType.Interactive)) { var directory = @"\\MyCorpServer.net\alpha\cars"; Assert.IsTrue(Directory.Exists(directory)); } 

詹姆斯在下面的回答是在Nuget之前,之后他会在Nuget上获得最多下载的包。 讽刺呃?

您可以冒充具有必要权限的用户。 MSDN上有一篇文章介绍了如何执行此操作。