C# 如何提供凭据以打开文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/249540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:52:49  来源:igfitidea点击:

How to present credentials in order to open file?

c#.netsecurityfilesystems

提问by

How do I specify the username and password in order for my program to open a file for reading? The program that needs to access the file is running from an account that does not have read access to the folder the file is in. Program is written in C# and .NET 2, running under XP and file is on a Windows Server 2003 machine.

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

回答by Joe

You can impersonate a user who has the necessary rights. There is an article on MSDNthat describes how to do this.

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

回答by James Newton-King

You want to impersonate a user who does have the rights to access the file.

您想模拟一个有权访问该文件的用户。

I recommend using a class like this - http://www.codeproject.com/KB/cs/zetaimpersonator.aspx. It hides all the nasty implementation of doing impersonation.

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

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

回答by ΩmegaMan

I have used the Nuget package NuGet Gallery | Simple Impersonation Library 1.1.0but there are others; search on Impersonation for the others.

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

Example usage using the interactive login to work with file structures:

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

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

     Assert.IsTrue(Directory.Exists(directory));
}


James' answer below was before Nuget and before he would later have the most downloaded package on Nuget. Ironic eh?

下面詹姆斯的回答是在 Nuget 之前,在他后来在 Nuget 上下载最多的软件包之前。讽刺啊?