2011-04-19 69 views
1

说我是否构建了一个从网络文件夹读取文件的Windows应用程序。网络折叠限制只有一个用户“fooUser”的访问。该应用程序安装在网络上的多台机器上。替换当前Windows用户与其他用户运行EXE

我需要用“fooUser”替换当前用户,以便能够通过代码访问网络文件夹中的文件。

回答

7

这是一个非常简单的模拟方案,将让你成为任何人一拍期间(当然你有适当的凭据。)
这个类将尽一切繁重的工作适合你....

public class Impersonator : IDisposable 
    { 

    const int LOGON32_PROVIDER_DEFAULT = 0; 
    const int LOGON32_LOGON_INTERACTIVE = 2; 

    [DllImport("advapi32.dll", SetLastError = true)] 
    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 extern static bool CloseHandle(IntPtr handle); 

    private IntPtr token = IntPtr.Zero; 
    private WindowsImpersonationContext impersonated; 
    private readonly string _ErrMsg = ""; 

    public bool IsImpersonating 
    { 
     get { return (token != IntPtr.Zero) && (impersonated != null); } 
    } 

    public string ErrMsg 
    { 
     get { return _ErrMsg; } 
    } 

    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] 
    public Impersonator(string userName, string password, string domain) 
    { 
     StopImpersonating(); 

     bool loggedOn = LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token); 
     if (!loggedOn) 
     { 
     _ErrMsg = new System.ComponentModel.Win32Exception().Message; 
     return; 
     } 

     WindowsIdentity identity = new WindowsIdentity(token); 
     impersonated = identity.Impersonate(); 
    } 

    private void StopImpersonating() 
    { 
     if (impersonated != null) 
     { 
     impersonated.Undo(); 
     impersonated = null; 
     } 

     if (token != IntPtr.Zero) 
     { 
     CloseHandle(token); 
     token = IntPtr.Zero; 
     } 
    } 

    public void Dispose() 
    { 
     StopImpersonating(); 
    } 
    } 

你可以像这样使用它;

using (Impersonator = new Impersonator(yourName,yourPassword,yourDomain)) 
{ 
// Read files from network drives. 
// Other activities.... 
} 

它放置假冒者在“使用”块,或处置是非常重要的,当你做了做你的模拟的任务,否则系统将继续无限期地模仿,这将导致各种问题。

+0

它工作完美! – RolandoCC 2013-05-27 16:47:32

0

您可以将映射驱动器设置为使用'fooUser'凭据的文件夹共享。

虽然如果您有用户的登录名/密码,您可以让您的代码使用模拟。 按我的回答Windows Impersonation from C#

对于模拟代码见 以下两个代码项目文章:

http://www.codeproject.com/KB/cs/cpimpersonation1.aspx

http://www.codeproject.com/KB/cs/zetaimpersonator.aspx

和Microsoft知识库文章他们是 基础时间:

http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158