Sunday, June 21, 2009

How to Delete specific user from your sharepoint sites

Hey.

Small task I had today, to delete a certain user who left the company. They have a list in which they document all the workers who left, so I had to just check the list every day, see if there is anything new and if so, just delete that user from all SiteCollection - be aware, when you delete a user from the siteCollection it's enough, there is no need to drill down to each and each web site.

 


foreach (SPWebApplication webApp in service.WebApplications)
{
SPSiteCollection colSites = webApp.Sites;
for (int i = 0; i < colSites.Count; i++)
{
using (SPWeb web = colSites[i].OpenWeb())
{
SPUser user = web.SiteUsers[UserName_ToDelete];

try
{
if (!user.IsDomainGroup && !user.IsSiteAdmin)
{
web.SiteUsers.Remove(user.LoginName);
web.Update();
}
}
catch (Exception ex)
{
// user not found
}
}
colSites[i].Dispose();
}

}