How to change the content type for files in SharePoint

In this article we will be seeing how to change a batch of files in a document library from one content type to another using C#.

I have batch of files in a document library which belongs to the "Document "content type. I want to change the content type from "Document" to "_CustomContentType (which is a custom content type).


Steps Involved:

a. Open Visual Studio 2010.

b. Create a console application.

c. Replace the code with the following.

  1. using System;

  2. using System.Collections.Generic;

  3. using System.Linq;

  4. using System.Text;

  5. using Microsoft.SharePoint;

  6. namespace ChangeContentType

  7. {

  8. class Program   

  9. {

  10. static void Main(string[] args)       

  11. {

  12. using (SPSite site = new SPSite("http://serverName:1111/SitePages/Home.aspx"))           

  13. {

  14. using (SPWeb web = site.RootWeb)               

  15. {

  16. SPList list = web.Lists["Shared Documents"];

  17. SPContentType oldCT = list.ContentTypes["Document"];

  18. SPContentType newCT = list.ContentTypes["_CustomContentType"];

  19. SPContentTypeId newCTID = newCT.Id;

  20. if ((oldCT !=null) && (newCT != null))                   

  21. {

  22. foreach (SPListItem item in list.Items)                       

  23. {

  24. if (item.ContentType.Name == oldCT.Name)                           

  25. {

  26. if (item.File.CheckOutType.ToString() == "None")