0
votes

I have a block of code that is executing without errors when i login as a system administrator on the SharePoint 2010 site. But i have problems in executing the same with a regular user account. Can someone please help me on how to execute a code block by logging in as a different SharePoint account (Admin account) using C# code.

Example:

Using(Domain,LoginID,Password)
{

//Execute Code

//logout as admin

} 

Error Message on SharePoint 2010:

Error Occured: System.UnauthorizedAccessException: Access to the path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\template\layouts\Test\Dev\ABC.xlsx' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename) at App.Test.btnFileUpload_Click(Object sender, EventArgs e)

Code Sample:

if (fileUpload.HasFile)
{
    strTarget = Server.MapPath(fileUpload.FileName);
    string[] arrCheckExtension = strTarget.Split('.');
    if (arrCheckExtension.Length >= 2)
    {
        if (arrCheckExtension[1].ToString().Equals("xls") || arrCheckExtension[1].ToString().Equals("xlsx"))
        {
            fileUpload.SaveAs(strTarget);
            strConnForExcel = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR=YES;IMEX=1;""", strTarget);
            strQueryForExcel = String.Format("select id from [{0}$]", "Test");
            OleDbDataAdapter adap = new OleDbDataAdapter(strQueryForExcel, strConnForExcel);
            ds = new DataSet();
            adap.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (strids == "")
                    {
                        strids += ds.Tables[0].Rows[i]["id"].ToString();
                    }
                    else
                    {
                        strids += "," + ds.Tables[0].Rows[i]["id"].ToString();
                    }
                }
                txtUpload.Text = strids;

            }
        }
        else
        {
            Response.Write("<script language='javascript'>alert('Please Select File with .xls or xlsx Extension');</script>");

        }
    }
}
1
Maybe you should try save the uploaded somewhere else than to the layouts-folder of SharePoint. That's quite a security risk... Use the Temp-directory or create a new folder (C:\UploadedFiles) and make sure that the necessary users have write permissions to it. If you know where the excels are going to be stored, then you shouldn't need the Server.MapPath command at all.artokai

1 Answers

0
votes

The error occurs because you are trying to save the Excel-file to the layouts-folder in the program files. User uploaded files should not be stored there for security reasons.

Lose the Server.MapPath and save the uploaded file to the TEMP-directory or for example to "D:\UploadedFiles" instead.

You can use SPSecurity.RunWithElevatedPrivileges to run your code using the web application pool identity. This can help you to narrow the filesystem folder level access rights to just to the application pool account.

More details about this function: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx

An example from the page mentioned:

SPSecurity.RunWithElevatedPrivileges(delegate()
          // Your code here
});

Note that you'll have to create the SPSite and SPWeb objects inside the elevated block in order for the elevation to take effect (if you need those).