none
access dinied when using SPSecurity.RunWithElevatedPrivileges() RRS feed

  • Question

  • Hi All,

    In my project, i have to upload a file to sharepoint library folder in a console program. However, i am fail to upload file to sharepoint library by including  SPSecurity.RunWithElevatedPrivileges();

    i know that it will use the permission  of current login user to do thing if not including SPSecurity.RunWithElevatedPrivileges() and if included, the program will use system account.

    In my case, if i add my code in SPSecurity.RunWithElevatedPrivileges() (show as below, C1), it will throw out a  "Access is denied " error. However, when i remove the spsecurity, it is successfully to upload to sharepoint (C2).

    My question is where to config the system account (my program is run as admin)?

     // C1         
      SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite("http://SiteURUL"))
                    {
                        using (SPWeb oWeb = site.OpenWeb())
                            {
                                oWeb.AllowUnsafeUpdates = true;
                                try
                                {
                                    string fileToUpload = dir + fileName;
                                    if (!System.IO.File.Exists(fileToUpload))
                                        throw new FileNotFoundException("File not found.", fileToUpload);
    
                                    SPFolder myLibrary = oWeb.GetFolder(ReportPath);
    
                                    // Prepare to upload
                                    Boolean replaceExistingFiles = true;
    
                                    FileStream fileStream = File.OpenRead(fileToUpload);
    ;
                                    // Upload document
                                    SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
    
                                    // Commit 
                                    myLibrary.Update();
     
                                }
                                catch (Exception ec)
                                {
                                    Console.WriteLine("error when upload2SP error:" + Convert.ToString(ec)); //=> access denied
                                }
                                oWeb.AllowUnsafeUpdates = false;
                            }
                        site.AllowUnsafeUpdates = false;
                    }
                });
                Console.WriteLine("end");
    
    
    
    //c2
    using (SPSite site = new SPSite("http://SiteURUL"))
                    {
                        using (SPWeb oWeb = site.OpenWeb())
                            {
                                oWeb.AllowUnsafeUpdates = true;
                                try
                                {
                                    string fileToUpload = dir + fileName;
                                    if (!System.IO.File.Exists(fileToUpload))
                                        throw new FileNotFoundException("File not found.", fileToUpload);
    
                                    SPFolder myLibrary = oWeb.GetFolder(ReportPath);
    
                                    // Prepare to upload
                                    Boolean replaceExistingFiles = true;
    
                                    FileStream fileStream = File.OpenRead(fileToUpload);
    ;
                                    // Upload document
                                    SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
    
                                    // Commit 
                                    myLibrary.Update();
     
                                }
                                catch (Exception ec)
                                {
                                    Console.WriteLine("error when upload2SP error:" + Convert.ToString(ec)); //=> access denied
                                }
                                oWeb.AllowUnsafeUpdates = false;
                            }
                        site.AllowUnsafeUpdates = false;
                    }
                Console.WriteLine("end");//work perfectly

    Monday, March 27, 2017 5:40 AM

Answers

  • Hi,

    If you want to use SPSecurity.RunWithElevatedPrivileges in console application, there's no SharePoint context.

    Instead, you can create a batch file (like if you have input parameters) and use the "RunAs" method that Windows gives you (example, in Windows Server 2008 R2 you have to hold down Shift and Right-click the batch file, in order to get the Run As option).  If you’re setting up the job as a scheduled task through Windows, you simply have to set the account to the Application Pool account and specify that it should run whether or not the account is logged in.

    More information is here:

    https://suehernandez.wordpress.com/2013/10/25/spsecurity-runwithelevatedprivileges-and-console-applications/

    Or please try to impersonate Users in SharePoint use this:

    string siteStr = "http://mysharepointsite/";
     
    //we just need to get a handle to the site for us
    //to get the system account user token
    SPSite tempSite = new SPSite(siteStr);
     
    SPUserToken systoken = tempSite.SystemAccount.UserToken;
     
    using (SPSite site = new SPSite(siteStr, systoken))
    {
       using (SPWeb web = site.OpenWeb())
       {
           //right now, logged in as Site System Account
           Console.WriteLine("Currently logged in as: " +
                            web.CurrentUser.ToString());
     
           //add your code here
       }
    }
    

    http://www.sharepointdeveloperhq.com/2009/04/how-to-programmatically-impersonate-users-in-sharepoint/

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    • Marked as answer by Johnson yau Wednesday, March 29, 2017 4:13 AM
    Tuesday, March 28, 2017 4:02 AM
    Moderator