www.evget.com 慧都控件网  国内最大控件代理商与技术支持商

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

   WindowsImpersonationContext impersonationContext;
 
   [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
     public static extern int LogonUser(String lpszUserName,
                                     String lpszDomain,
                                     String lpszPassword,
                                     int dwLogonType,
                                    int dwLogonProvider,
                                    ref IntPtr phToken);
   [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
   public extern static int DuplicateToken(IntPtr hToken,
                                     int impersonationLevel,
                                    ref IntPtr hNewToken);
  
  private bool impersonateValidUser(String userName, String domain, String password)
   {

      IntPtr token = IntPtr.Zero;
      IntPtr tokenDuplicate = IntPtr.Zero;

      if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
      LOGON32_PROVIDER_DEFAULT, ref token) != 0)
       {
           if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)          {
               WindowsIdentity tempWindowsIdentity;
             tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
               impersonationContext = tempWindowsIdentity.Impersonate();
               if (impersonationContext != null)
                return true;
              else
                   return false;
           }
         else
               return false;
      }
       else
           return false;
   }
   private void undoImpersonation()
   {
       impersonationContext.Undo();//回退为未更改前账户
   }

    protected void Button1_Click(object sender, EventArgs e)
   {
       //临时更改为 跟 网络硬盘相同用户名密码的账户(此账户必须在网络盘有写入权限)本机也需要同样帐号密码的帐户

       if (impersonateValidUser("test", "192.168.18.203", "1111"))
       {
            //登陆后处理密码
            if (!Directory.Exists(@"\192.168.18.203sp est"))
            {
               try
               {
                   Directory.CreateDirectory(@"\192.168.18.203sp est");
               }
               catch (Exception e1)
               {
                  Response.Write(e1.Message);
               }
           }
           FileUpload1.SaveAs(@"\192.168.18.203sp estq.txt");
           undoImpersonation();
       }        else
      {
           Response.Write("登陆失败");
          //失败后处理密码
 } }