0
A
回答
0
从this螺纹:
const string file = @"\\machine\test\file.txt";
using (UserImpersonation2 user = new UserImpersonation2("user", "domain", "password"))
{
if (user.ImpersonateValidUser())
{
StreamReader reader = new StreamReader(file);
Console.WriteLine(reader.ReadToEnd());
reader.Close();
}
}
class UserImpersonation2:IDisposable
{
[DllImport("advapi32.dll")]
public static extern bool LogonUser(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
WindowsImpersonationContext wic;
IntPtr tokenHandle;
string _userName;
string _domain;
string _passWord;
public UserImpersonation2(string userName, string domain, string passWord)
{
_userName = userName;
_domain = domain;
_passWord = passWord;
}
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
public bool ImpersonateValidUser()
{
bool returnValue = LogonUser(_userName, _domain, _passWord,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
Console.WriteLine("LogonUser called.");
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
return false;
}
Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
Console.WriteLine("Value of Windows NT token: " + tokenHandle);
// Check the identity.
Console.WriteLine("Before impersonation: "
+ WindowsIdentity.GetCurrent().Name);
// Use the token handle returned by LogonUser.
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
wic = newId.Impersonate();
// Check the identity.
Console.WriteLine("After impersonation: "
+ WindowsIdentity.GetCurrent().Name);
return true;
}
#region IDisposable Members
public void Dispose()
{
if(wic!=null)
wic.Undo();
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
}
#endregion
}
+0
我习惯于使用advapi32.dll作为您的建议。但是如果有任何继承权限,它总是会抛出异常。 – duykaka 2013-02-22 06:20:18
相关问题
- 1. 如何在Java中打开特定文件夹使用按钮
- 2. 如何使用Python Tkinter打开特定的.csv文件按钮?
- 3. UWP:打开特定文件
- 4. 批处理文件 - 按特定顺序打开文件
- 5. 指定如何使用PHP打开特定的文件类型
- 6. iOS - 用特定程序打开文件
- 7. 按钮,打开应用程序路径+特定文件夹
- 8. 使用浏览按钮打开特定的文件
- 9. 打开特定的PDF文件,为用户
- 10. 打开文件用户指定
- 11. 打开特定的文本文件
- 12. 如何使用JFileChooser.showOpenDialog打开特定文件?
- 13. 如何在桌面中使用特定程序打开文件
- 14. 如何使用特定(非默认)类打开文件/协议
- 15. 如何确定Windows中是否打开特定文件?
- 16. 如何在python上打开特定的文本文件?
- 17. 如何在用户打开特定页面时自动打开pdf?
- 18. 特定的php文件不能打开
- 19. 从特定文件打开图像?
- 20. Excel宏 - 打开特定的word文件
- 21. 从特定磁盘打开文件
- 22. 如何打开在屏幕中间以特定大小打开的文件夹
- 23. 如何在用户点击通知时打开特定课程?
- 24. 如何使用打开文件对话框中一个特定的文件夹
- 25. 按需打开自定义文件
- 26. 使用Process.Start为特定文件夹打开文件夹
- 27. 用Python在特定文件夹中打开文件浏览器
- 28. 用批处理文件打开特定文件?
- 29. 如何打开用户的个人文件夹中的文件
- 30. 如何使console2在特定文件夹中打开?
请澄清:你想打开使用特定用户的凭据文件? – 2013-02-22 04:41:59
这个方法在.NET框架中不存在。更具体地说明你想要完成的事情,而不是你想要使用的方法。 – Rich 2013-02-22 04:42:25
我只想检查用户是否可以打开/读取文件。 (任何用户不仅登录用户) – duykaka 2013-02-22 06:12:27