In SharePoint 2010 I came across a bug where the listitems lost their content types and reverted all the way back to being a ‘folder’. This was in a document library where the content types were managed by setting “Allow management of content types” to Yes in the advanced library settings.
I needed a way of iterating through every list item in the list and programmatically setting the content type to the correct one.
First off I made a small struct to store the path of the document library and the corresponding content type name.
public struct ListContentTypeMapping
{
public string Folder;
public string ContentType;
}
Then I iterate through the list to change the content types. The actual way to change content types of list items (at least in sharepoint 2010) is to change the property called “ContentTypeId” and set it to the Id (SPContentTypeId) of the chosen SPContentType object.
public void SetContentTypesOnDocumentLibraries(IEnumerable<ListContentTypeMapping> mappings)
{
using (var siteRoot = new SPSite("http://sitename/"))
{
foreach (var mapping in mappings)
{
using (var web = siteRoot.RootWeb)
{
var list = web.GetList(mapping.Folder);
foreach(SPListItem item in list.Items)
{
ChangeContentType(list, item, mapping.ContentType);
}
}
}
}
}
private static void ChangeContentType(SPList list, SPListItem listItem, string contentTypeName)
{
SPContentType contentType = list.ContentTypes[contentTypeName];
listItem["ContentTypeId"] = contentType.Id;
listItem.Update();
}
Here’s some sample code, it will change all the items in those folders to the specific content types.
var mappings = new List<ListContentTypeMapping>();
mappings.Add(new ListContentTypeMapping { Folder = "some/path/to/list/", ContentType = "ContentTypeOne" });
mappings.Add(new ListContentTypeMapping { Folder = "some/path/to/anotherlist/", ContentType = "ContentTypeTwo" });
SetContentTypesOnDocumentLibraries(mappings);
Comments