0

I am trying this code to get SPUser object but it keeps throwing exception of user not found even when it returns true for DoesUserHavePermissions(..., does anyone know any fix or way around ?

if (web.Site.RootWeb.DoesUserHavePermissions("UserLoginName", SPBasePermissions.Open))
{
   SPUser user = web.Site.RootWeb.Users["UserLoginName"];
}

Can't use web.Ensure

2 Answers 2

1

Try RootWeb.AllUsers instead.

if (web.Site.RootWeb.DoesUserHavePermissions("UserLoginName", SPBasePermissions.Open))
{
   SPUser user = web.Site.RootWeb.AllUsers["UserLoginName"];
}

Or you can also try RootWeb.SiteUsers

Reference

0

just created this console app for you:

        try
        {
            using (SPSite mysite = new SPSite("http://yourwebsite:2010"))
            {

                using (SPWeb web = mysite.OpenWeb())
                {
                    Console.Write("web users");
                    Console.WriteLine();
                    Console.WriteLine();
                    foreach (SPUser user in web.Users)
                    {
                        Console.Write(user.Name);
                        Console.WriteLine();
                    }

                    Console.WriteLine();
                    Console.WriteLine();
                    Console.Write("site collection users");
                    Console.WriteLine();
                    Console.WriteLine();
                    foreach (SPUser user in web.SiteUsers)
                    {
                        Console.Write(user.Name);
                        Console.WriteLine();
                    }
                }

            }
        }
        catch (Exception a)
        {
        }

        Console.Read();

so what you want is web.SiteUsers for site collection and web.Users for webs ;) not web.Site.RootWeb.Users. If you run the code above within a console app you should see the user within the list and if it has a domain tag or not!

or do:

using (SPWeb web = SPContext.Current.Site.RootWeb) 
{
    SPUser user = web.Users["UserLoginName"];
}

get the correct web context if your looking for the root web of a site ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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