Click here to Skip to main content
15,918,742 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have to upload file without giving full permission to my folder where all files will be uploaded.
I have to upload file using file impersonation in asp.net
when i write identity impersonate="true" in web config it shows error to site.

What I have tried:

<identity impersonate="true" username="" password="" />
C#
public partial class Uploadfile : System.Web.UI.Page
    {

        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;
 
        WindowsImpersonationContext impersonationContext;
 
        [DllImport("advapi32.dll")]
        public static extern int LogonUserA(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);
 
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();
 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);
 
        private bool ImpersonateUser(String userName, String domain, String password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
 
            if (RevertToSelf())
            {
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
                CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);
            return false;
        }
 
        private void UndoImpersonation()
        {
            impersonationContext.Undo();
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnUpload_Click(object sender, EventArgs e)
        {


            if (ImpersonateUser("username", "", "password"))
            {
 
                if (FileUpload1.PostedFile != null) 
                {
                    if (FileUpload1.HasFile)
            {
                string ext = System.IO.Path.GetExtension(FileUpload1.FileName);
                        if (ext == ".xls" || ext == ".rar" || ext == ".XLS" || ext == ".xlsx")
                        {
                            FileUpload1.SaveAs(Server.MapPath("~/Admin/reports1/") + FileUpload1.FileName);
                                    //BindGrid();
                        }
                        else
                        {
                            ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'> javascript: alert('Please Select Proper file Format.');</script>");
                            return;
                            //lblerr2.Text = "Please Select Proper file Format.";

                        }
            }
            else
            {
                ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'> javascript: alert('Please select file to upload.');</script>");
                return;
                //Response.Write("Please select file to upload");
            }
                    //string fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
                    //string folderPath = @"\\MyUNCShare\MyFolder\";
 
                    //string locationToSave = folderPath + "\\" + fileName;
                    //try
                    //{
                    //    FileUpload1.PostedFile.SaveAs(locationToSave);
                    //    Response.Write("The file has been uploaded.");
                    //}
                    //catch (Exception ex)
                    //{
                    //    Response.Write("Error: " + ex.Message);
                    //}
                }
                else
                {
                    Response.Write("Please select a file to upload.");
                }
 
                UndoImpersonation();
            }
            else
            {
                Response.Write("Failed");
            }
 
        }
    }
Posted
Updated 17-Mar-16 13:17pm
v2
Comments
ZurdoDev 14-Mar-16 8:42am    
What's the error? And why importing so many dlls like this? It should not be necessary.

If you just need to upload a file there is 2 simeple ways, one is with the AJAX file upload, these let you upload multiple files and have some nice java forms that looks fine, in the personal I dont like it to much I prefere the old stile, then the thing is if you are going to upload a single file o multiple files at the same time, and Im looking you are adding validator for only xls, xlsx files
, that make me think in if also you will need to thow the results in to a DB or is just matter to store the file.

If ts just matter to store the file.

Single File.

<div id="Div1" runat="server">
    <br />
    <asp:fileupload id="FileUpload3" runat="server" enabled="true" xmlns:asp="#unknown" />
    <asp:button id="Button1" runat="server" text="Upload" onclick="btnUpload_Click" xmlns:asp="#unknown" />
    <asp:label id="Label1" runat="server" text="" xmlns:asp="#unknown" />
    <br />
    <asp:label id="Label6" runat="server" text="" xmlns:asp="#unknown" />
</div>


protected void btnUpload_Click(object sender, EventArgs e)
{

    if (FileUpload1.HasFile)
    {
        string FileName = Server.HtmlEncode(FileUpload1.FileName);
        string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower();
        if (Extension != ".xls" && Extension != ".xlsx")
        {
            Response.Write("<script>alert('Please select a Excel spreadsheet to import!');</script>");
            return;
        }
        string abc = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName);
        string strUploadFileName = "~/TradeCompliance/Functional/Files_Archive/" + abc + " " + DateTime.Now.ToString("yyyyMMddHHmmss") + Extension;
        string FilePath = Server.MapPath(strUploadFileName);
        FileUpload1.SaveAs(FilePath);
    }
}


If multiple files needs to be stored at the same time then I use this (Check that in name you can sort the type of valid files to search for upload and the accept the type of file application works for xls 97 up to last vertion):

<br />
<input type="file" multiple="multiple" runat="server" width="300px" height="300px" aria-dropeffect="move" aria-multiline="true">
    aria-multiselectable="true" draggable="true" name="pdf" id="File1" accept="application/pdf" /><asp:label id="Label1" text="UploadComplete" runat="server" visible="false" xmlns:asp="#unknown" /><br />
<asp:button id="Button2" runat="server" text="UPLOAD" onclick="Button1_Click" xmlns:asp="#unknown" />
<br />
<asp:label id="Label2" runat="server" xmlns:asp="#unknown" />
<br />
<hr />
<div>
    <asp:literal id="Literal1" runat="server" xmlns:asp="#unknown" />
</div>
<br />
</input>

 protected void Button1_Click(object sender, EventArgs e)
    {
        string filepath = Server.MapPath("\\Logistics\\ArchiveFiles\\");
        string contentType = "";
        string filename = "";
        string HAWB_BOL = "";
        string tempPath = "";
        int filecnt = 0;

        HttpFileCollection uploadedFiles = Request.Files;
        Span1.Text = string.Empty;

        for (int i = 0; i < uploadedFiles.Count; i++)
        {
            HttpPostedFile userPostedFile = uploadedFiles[i];
            contentType = userPostedFile.ContentType;
            filename = Path.GetFileName(userPostedFile.FileName);
            HAWB_BOL = filename.Replace(".pdf", "");

            filecnt = AD(HAWB_BOL);

            tempPath = filepath + filename;
            
            if(filecnt < 1)
            {
                try
                {
                    if (userPostedFile.ContentLength > 0)
                    {
                        userPostedFile.SaveAs(tempPath);
                    }
                }
                catch (Exception Ex)
                {
                    Span1.Text += "Error: <br>" + Ex.Message;
                }
            }else
            {
                userPostedFile.SaveAs(tempPath);
                File.Delete(tempPath);
            }

        }
    }
</br>


I just delete dome parts of the code as I save in the multiple scenario to a DB to get the files available against a file, but basically with some minor changes you should be able to implement any of these.
 
Share this answer
 
Comments
Member 11466758 15-Mar-16 1:40am    
thanks for your solution , i uploaded the file using ajax file upload control with giving permission to folder where file will be uploaded.

now i have to upload file to a folder for particular user using impersonation method but i got error ,for this i refer https://support.microsoft.com/en-us/kb/306158 this code please help
At the Web.Config file you must add some thing like this.

<system.web>
  <authentication mode="Windows" />
  <identity impersonate="true" username="XUSER" password="XPASSWORD" />
</system.web>


<system.web>
  <authentication mode="Forms">
      <forms loginurl="~/Account/Login" timeout="2880" defaulturl="~/" />
    </authentication>
    <identity impersonate="true" username="XUSER" password="XPASSWORD" />
</system.web>


Depending on your authentification method these should work.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900