top of page

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")                                

  27. {                                   

  28. item.File.CheckOut();                                   

  29. item["ContentTypeId"] = newCTID;                                   

  30. item.Update();                                   

  31. item.File.CheckIn("Checked in");                               

  32. }

  33. else                               

  34. {

  35. Console.WriteLine("File " + item.Name + "is checked out to" + item.File.CheckedOutByUser.ToString() + " and cannot be modified");                               

  36. }                           

  37. }

  38. else                           

  39. {

  40. Console.WriteLine("File "+item.Name+ " is associated with the content type "+ item.ContentType.Name+ " and shall not be modified");                           

  41. }                       

  42. }                   

  43. }

  44. else                   

  45. {

  46. Console.WriteLine("One of the content types specified has not been attached to the list "+list.Title);                   

  47. }

  48. Console.ReadLine();               

  49. }           

  50. }       

  51. }   

  52. }

  53. }

d. Hit F5.


0 comments
bottom of page