2013-02-22 29 views
0

如何使用.Net打开特定用户的文件。
例子:如何按特定用户打开文件

File.OpenFile(filePath, user) 
+1

请澄清:你想打开使用特定用户的凭据文件? – 2013-02-22 04:41:59

+0

这个方法在.NET框架中不存在。更具体地说明你想要完成的事情,而不是你想要使用的方法。 – Rich 2013-02-22 04:42:25

+0

我只想检查用户是否可以打开/读取文件。 (任何用户不仅登录用户) – duykaka 2013-02-22 06:12:27

回答

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

相关问题