Friday, July 20, 2012

Remove User from User Information Table

Remove a single user from User Information table:
Remove a user based on Login Name
web.AllowUnsafeUpdates = true;
string userName = "domainname\\username";
SPUser user = web.SiteUsers[userName];
 if (!user.IsDomainGroup && !user.IsSiteAdmin)
     {
         web.SiteUsers.Remove(user.LoginName);
          web.Update();
     }
web.AllowUnsafeUpdates = false;


Remove Multiple user:
Remove multiple user based on Domain name
web.AllowUnsafeUpdates = true;
SPList _list = web.Lists.TryGetList("User Information List");
SPQuery qry = new SPQuery();
qry.Query = "<Where><Contains><FieldRef Name='Name' /><Value Type='Text'>Domainname</Value></Contains></Where>";
SPListItemCollection _itmcol = _list.GetItems(qry);
if (_itmcol.Count > 0)
  {
      string userName = "";
     foreach (SPListItem itm in _itmcol)
      {
        userName = Convert.ToString(itm["Name"]);
        SPUser user = web.SiteUsers[userName];
        Console.WriteLine(userName + "("+ Convert.ToString(itm["Title"])+ ")" + "\n");
        web.SiteUsers.Remove(user.LoginName);
        web.Update();
      }
 }
web.AllowUnsafeUpdates = false;

No comments:

Post a Comment

How to launch a document by clicking a link to the file?

Word: <a href='ms-word:ofe|u|path/to/web/word/document.docx'>Link to document</a> Excel: <a href='ms-excel:o...