SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The following code, though run with elevated privildges, redirects to an access denied error page saying "You are currently signed in as: (my non-admin account)." What am I doing wrong?

    SPSecurity.RunWithElevatedPrivileges(delegate()
    {

        SPGroup group = SPContext.Current.Web.Groups["Group Name"];

        foreach (SPUser user in group.Users)
        {
           string email = CustomMethodGetsEmailFromProfile(user);
           SPUtility.SendEmail(...);
        }

     });

If I comment out the foreach loop, it works fine but defeats the purpose. Recall, I'm getting access denied. There's a few null checks that I didn't include as I'm writing this from memory. Thanks in advance for any help.

share|improve this question

You can't/shouldn't use SPContext when elevating privileges, as the objects represented within it were created under a different (...in this case probably one with less privileges) security context. Try something like this:

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID])
                {
                     // then your code
                }
            }
        });

Should do the trick.

share|improve this answer
    
Thanks, that did it. – Rick Lealti Jul 29 '11 at 19:59
    
Rick, could you please mark it as answered so it's clear to others folks that this is an answered question. – Rob D'Oria Jul 29 '11 at 20:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.