SharePoint 2010 SPListCollection.GetList by Id without permissions

If you want to get hold of a SharePoint List by its ID, but only when the current user has access to it, there are many pitfalls. If you try to use SPListCollection.GetList, and plan to check the permissions after you get it, it’s too late. Your app will blow up and the user will get the “Access Denied” window.

One solution is to make use of the ListsForCurrentUser property, and use a Lambda query to check if our ID is among the lists the current user has access to:

web = OpenWebById(webId);
if (web == null)
	return null;

var listId = new Guid(myListId);

// Return null if the current user does not have access
// (and if list does not exist)

web.Lists.ListsForCurrentUser = true;
List<SPList> lists = web.Lists.Cast<SPList>().ToList();
if ((lists.Where(t => t.ID == listId)).Count() == 0)
	return null;

// If we get to here, the user HAS access, so we can safely
// use web.Lists.GetList() or alternatively web.Lists[listId]

var list = web.Lists.GetList(listId, false);

Sometimes it’s easiest to solve SharePoint programming problems by going around them.

As always: Comments are welcome!

Advertisements

About Øystein Garnes

Software Project Manager, former .Net and SharePoint 2010 developer, husband, Boston Terrier owner, amateur caveman chef, amateur genealogist, cross country skier, food blogger.
This entry was posted in SharePoint and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s