How we can create documents inside a document library based upon the content type’s document template?

How we can create documents inside a document library based upon the content type’s document template?

  • Comments 1

Before starting the coding, let us have a look at the storage location of documents whenever we add those in to any document libraries, also the location of content type’s document template.

Whenever you open your SharePoint document library using the Actions à Open with windows Explorer, it will show you the physical location of the files already there for your document library.

clip_image002

In this post I am taking the default document library which is “Shared Documents”. If you open this document library in the windows explorer then you can see a template.doc  file just beneath the form folder. So now it is pretty easy, isn’t it? Only you need to just find out this file and it's location and create & add the file to your library based upon this base template.

clip_image004

<code>

using System;

using System.Collections.Generic;

using System.Text;

using System.Collections;

using Microsoft.SharePoint;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            SPSite oSite = new SPSite("http://blr2r08-9:2100/sites/LastTest");

            SPWeb oWeb = oSite.OpenWeb();

 

            SPList projectDocumentLibrary = oWeb.Lists["Shared Documents"];

 

            // Retrieves the content type collection from "Shared Documents"

            SPContentTypeCollection oContentTypes= projectDocumentLibrary.ContentTypes;

            //loop through each content type and create a file based on that content type   

            foreach (SPContentType oContentType in oContentTypes)

            {               

                if (oContentType.DocumentTemplateUrl != string.Empty)

                {

                    // this line does the addition of files . DocumentTemplateUrl will give the template.doc's location which is /LastTest/Shared%20Documents/Forms/template.doc

                    SPFile oFile = projectDocumentLibrary.RootFolder.Files.Add("TestDoc1.doc", oWeb.GetFile(oContentType .DocumentTemplateUrl).OpenBinary(), true);

 

                    SPListItem oItem = oFile.Item;

 

                    //just updating the title

                    oItem["Title"] = "Test";

 

                    oItem.Update();

                }

            }          

 

        }

    }

}

</code>

Once you execute the above code after making appropriate changes as per your SharePoint site, then you can see that it is adding a TestDoc1.doc file in to the Shared Documents library.

clip_image005

 

Comments
Leave a Comment
  • Please add 7 and 7 and type the answer here:
  • Post