Sunday, January 18, 2009

How To Delete a Sharepoint User in c#

you can effectively use this piece of code to remove existing users from the sharepoint site


First of all you have to import

using Microsoft.SharePoint;

Then use following code

public void RemoveUserFromSP(string _UserName)
{
SPSite site = new SPSite(ConfigurationManager.AppSettings["SITE_URL"].ToString());
SPWeb web = site.AllWebs[ConfigurationManager.AppSettings["WEB_SITE"].ToString()];

SPUserCollection userCollection = web.SiteUsers;

string domain = ConfigurationManager.AppSettings["DOMAIN"].ToString();

SPUser spUser;
try
{
spUser = web.AllUsers["ad:" + _UserName];
}
catch
{
spUser = web.AllUsers[domain + "\\" + _UserName]; ;
}
try
{
web.AllowUnsafeUpdates = true;
userCollection.Remove(spUser.LoginName);
}
catch (Exception ex)
{
//Response.Write(ex.Message);
//lblUserList.Text = ex.Message.ToString();
}

}

No comments: