Update: I recently ran into this issue again and discovered that there is in fact a way to ensure that the user exists before creating the user object — the EnsureUser method of the SPWeb class. According to MSDN this method “Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site.” Check it out here. I tried this and it seems to resolve my issue. If the user is not a member of the web site, this method will add it which is effectively what I needed it to do.
Please note that you’ll need to set the AllowUnsafeUpdates property to true in order for the EnsureUser method to do it’s thing.
When trying to use SPWeb.Users to find a particular user in a site, I was receiving a “User cannot be found” error within the site that my method was being called from. I took a look at the site permissions and discovered that the user account I was attempting to add did not actually exist as a member of that site. At first glance, I didn’t actually think that this would be a problem, but apparently there is a key disctinction between the various SPWeb methods.
If I added the user to the site manually, the SPWeb.Users call worked. Any users automatically added to the site upon creation, will not be found with a SPWeb.Users call. This is an important disctinction.
My next attempt was to use SPWeb.SiteUsers which was only successful if the user existed at the site collection level. However, if the user was not a member of any group at the site collection level, my method would still fail with a “User cannot be found” error.
Alternatively, I might be able to leverage the user profile database to get a list of all possible users to choose from but I haven’t done any experimenting with this yet. If anyone has any additional information or feedback on this, please drop me a note.
Windows SharePoint Services 3.0 SDK
SPWeb.AllUsers – Gets the collection of user objects that represents all users who are either members of the site or who have browsed to the site as authenticated members of a domain group in the site.
SPWeb.SiteUsers – Gets the collection of all users that belong to the site collection.
SPWeb.Users – Gets the collection of user objects that are explicitly assigned permissions on the Web site.