title: Windows Impersonation failed
body: <p>I am using following code to implement impersonation for the particular windows account,which is failing.Please help.</p>
  
  <pre><code>using System.Security.Principal;
  using System.Runtime.InteropServices;
  
  public partial class Source_AddNewProduct : System.Web.UI.Page
  {
  [DllImport("advapi32.dll", SetLastError = true)]
      static extern bool LogonUser(
          string principal,
          string authority,
          string password,
          LogonSessionType logonType,
          LogonProvider logonProvider,
          out IntPtr token);
      [DllImport("kernel32.dll", SetLastError = true)]
      static extern bool CloseHandle(IntPtr handle);
  
      enum LogonSessionType : uint
      {
          Interactive = 2,
          Network,
          Batch,
          Service,
          NetworkCleartext = 8,
          NewCredentials
      }
      enum LogonProvider : uint
      {
          Default = 0, // default for platform (use this!)
          WinNT35,     // sends smoke signals to authority
          WinNT40,     // uses NTLM
          WinNT50      // negotiates Kerb or NTLM
      }
  //impersonation is used when user tries to upload an image to a network drive
  protected void btnPrimaryPicUpload_Click1(object sender, EventArgs e)
      {
          try
          {
              string mDocumentExt = string.Empty;
              string mDocumentName = string.Empty;
              HttpPostedFile mUserPostedFile = null;
              HttpFileCollection mUploadedFiles = null;
              string xmlPath = string.Empty;
  
              FileStream fs = null;
              StreamReader file;
              string modify;
  
              mUploadedFiles = HttpContext.Current.Request.Files;
  
              mUserPostedFile = mUploadedFiles[0];
  
              if (mUserPostedFile.ContentLength &gt;= 0 &amp;&amp; Path.GetFileName(mUserPostedFile.FileName) != "")
              {
  
                  mDocumentName = Path.GetFileName(mUserPostedFile.FileName);
                  mDocumentExt = Path.GetExtension(mDocumentName);
                  mDocumentExt = mDocumentExt.ToLower();
                  if (mDocumentExt != ".jpg" &amp;&amp; mDocumentExt != ".JPG" &amp;&amp; mDocumentExt != ".gif" &amp;&amp; mDocumentExt != ".GIF" &amp;&amp; mDocumentExt != ".jpeg" &amp;&amp; mDocumentExt != ".JPEG" &amp;&amp; mDocumentExt != ".tiff" &amp;&amp; mDocumentExt != ".TIFF" &amp;&amp; mDocumentExt != ".png" &amp;&amp; mDocumentExt != ".PNG" &amp;&amp; mDocumentExt != ".raw" &amp;&amp; mDocumentExt != ".RAW" &amp;&amp; mDocumentExt != ".bmp" &amp;&amp; mDocumentExt != ".BMP" &amp;&amp; mDocumentExt != ".TIF" &amp;&amp; mDocumentExt != ".tif")
                  {
                      Page.RegisterStartupScript("select", "&lt;script language=" + Convert.ToChar(34) +
                          "VBScript" + Convert.ToChar(34) + "&gt; MsgBox " + Convert.ToChar(34) + "Please upload valid picture file format" + Convert.ToChar(34) +
                          " , " + Convert.ToChar(34) + "64" + Convert.ToChar(34) + " , " + Convert.ToChar(34) + "WFISware" + Convert.ToChar(34) + "&lt;/script&gt;");
  
                  }
                  else
                  {
                      int intDocLen = mUserPostedFile.ContentLength;
                      byte[] imageBytes = new byte[intDocLen];
                      mUserPostedFile.InputStream.Read(imageBytes, 0, mUserPostedFile.ContentLength);
                      //xmlPath = @ConfigurationManager.AppSettings["ImagePath"].ToString();
                      xmlPath = Server.MapPath("./../ProductImages/");
                      mDocumentName = Guid.NewGuid().ToString().Replace("-", "") + System.IO.Path.GetExtension(mUserPostedFile.FileName);
  
                      //if (System.IO.Path.GetExtension(mUserPostedFile.FileName) == ".jpg")
                      //{
  
                      //}
                      //if (System.IO.Path.GetExtension(mUserPostedFile.FileName) == ".gif")
                      //{
  
                      //}
  
                      mUserPostedFile.SaveAs(xmlPath + mDocumentName);
  
                      //Remove commenting till upto stmt xmlPath = "./../ProductImages/"; to implement impersonation
                      byte[] bytContent;
                      IntPtr token = IntPtr.Zero;
                      WindowsImpersonationContext impersonatedUser = null;
  
                      try
                      {
                          // Note: Credentials should be encrypted in configuration file
                          bool result = LogonUser(ConfigurationManager.AppSettings["ServiceAccount"].ToString(), "ad-ent",
                                                  ConfigurationManager.AppSettings["ServiceAccountPassword"].ToString(),
                                                  LogonSessionType.Network,
                                                  LogonProvider.Default,
                                                  out token);
                          if (result)
                          {
                              WindowsIdentity id = new WindowsIdentity(token);
  
                              // Begin impersonation
                              impersonatedUser = id.Impersonate();
                              mUserPostedFile.SaveAs(xmlPath + mDocumentName);
  
                          }
                          else
                          {
                              throw new Exception("Identity impersonation has failed.");
                          }
                      }
                      catch
                      {
                          throw;
                      }
                      finally
                      {
                          // Stop impersonation and revert to the process identity
                          if (impersonatedUser != null)
                              impersonatedUser.Undo();
                          // Free the token
                          if (token != IntPtr.Zero)
                              CloseHandle(token);
                      }
  
  
                      xmlPath = "./../ProductImages/";
                      xmlPath = xmlPath + mDocumentName;
                      string o_image = xmlPath;  //For impersoantion uncomment this line and comment next line
                      //string o_image = "../ProductImages/" + mDocumentName;
  
                      ViewState["masterImage"] = o_image;
                      //fs = new FileStream(xmlPath, FileMode.Open, FileAccess.Read);
                      //file = new StreamReader(fs, Encoding.UTF8);
                      //modify = file.ReadToEnd();
                      //file.Close();
  
                      //commented by saurabh kumar 28may'09
                      imgImage.Visible = true;
                      imgImage.ImageUrl = ViewState["masterImage"].ToString();
                      img_Label1.Visible = false;
                  }
  
  
                  //e.Values["TemplateContent"] = modify;
                  //e.Values["TemplateName"] = mDocumentName.Replace(".xml", "");
              }
  
          }
          catch (Exception ex)
          {
              ExceptionUtil.UI(ex);
              Response.Redirect("errorpage.aspx");
          }
  
  
      }
  }
  </code></pre>
  
  <p>The code on execution throws system.invalidoperation exception.I have provided full control to destination folder to the windows service account that i am impersonating.</p>