Nick Grattan's Blog

About Microsoft SharePoint, .NET, Natural Language Processing and Machine Learning

Code for Creating New Documents based on a content type and template

with 16 comments

This method “CreateDocument” will create a new document in a SharePoint document library using a content type. It will copy the document template associated with the content type into the new document:

// Creates document in given list (root folder).
// Returns true if the file was created, false if it already
// exists or throws exception for other failure
protected bool CreateDocument( string sFilename,
                string sContentType, string sList)
        SPSite site = SPContext.Current.Site;

        using (SPWeb web = site.OpenWeb())
            SPList list = web.Lists[sList];
            // this always uses root folder
            SPFolder folder = web.Folders[sList];
            SPFileCollection fcol = folder.Files;

            // find the template url and open
            string sTemplate =
            SPFile spf = web.GetFile(sTemplate);
            byte[] binFile = spf.OpenBinary();
            // Url for file to be created
            string destFile = fcol.Folder.Url + “/” + sFilename;

            // create the document and get SPFile/SPItem for
            // new document
            SPFile addedFile = fcol.Add(destFile, binFile, false);
            SPItem newItem = addedFile.Item;
            newItem[“ContentType”] = sContentType;
            return true;
    catch (SPException spEx)
        // file already exists?
        if (spEx.ErrorCode == -2130575257)
            return false;
            throw spEx;

This code:

  1. Gets a SPSite for the current site collection, and opens an SPWeb for the site.
  2. Gets a SPList for the given list, and then an SPFolder for the root folder in this list. This code always creates the document in the root folder, but the code can easily be changed to place the document in any folder in the document library.
  3. Gets a SPFileCollection for the documents in the folder.
  4. “DocumentTemplateUrl” is used to return the Url of document template associated with the given content type.
  5. Get an SPFile for the document template in spf and open it for binary access using OpenBinary
  6. Add a new document to the folder through the SPFileCollection referenced by fcol.
  7. Get an SPItem for the new document and set the “ContentType” column to ensure it uses the correct content type (it will default to the first content type in the document library).
  8. Update the item and the added file.
  9. The catch section checks for an -2130575257 error, which indicates the file already exists.


Written by Nick Grattan

December 8, 2008 at 10:23 pm

16 Responses

Subscribe to comments with RSS.

  1. Nice article. I was looking for the exact code implementation on the net when I found your article.
    Can you also provide inputs on how to add values to certain fields in the document before uploading the file.
    The document here refers to the document based on the template/ content type.

    Swati Agarwal

    January 2, 2010 at 9:52 am

  2. If template is xyz.xsn — infopath template file
    Then what would be the aditional steps to create infopath .xml file document?

    Swati Agarwal

    January 2, 2010 at 3:59 pm

  3. Hi, I am looking for the same scenario…

    the only difference is, we are using SharePoint Client Object Model for .net Managed Windows Application.

    Will you please let me know how the same above thing possible in client object model also ?



    January 24, 2012 at 11:14 am

  4. Is the created document an .xsn template file or an instance of the template file as an .xml file?


    July 12, 2012 at 6:45 pm

    • Hi Mike, I presume your using an InfoPath library. In that case the template will be the xsn file and the document will be an xml document. However, I have not tried this code with an InfoPath library. Regards, Nick

      Nick Grattan

      July 12, 2012 at 6:54 pm

      • Nick, thanks. Yes it’s an InfoPath library. My current solution involves extracting the template from the infopath cab file (.xsn). This seems simpler.

        Trying to test this function. What is the expected format of sList…is this just the name of the list?


        July 12, 2012 at 7:25 pm

      • Ok – tested it and it does in fact create the instance of the infopath template. Very nice, much better than having to extract it. I just had to change the line web.Folders[sList] to list.RootFolder otherwise it throws an error. I am on Sharepoint 2010….

        Protected bool CreateDocument( string sFilename, string sContentType, string sList)

        SPFolder folder = list.RootFolder; // web.Folders[sList];



        July 12, 2012 at 7:54 pm

    • and Thanks!


      July 12, 2012 at 7:57 pm

      • Nick — sorry was doing too many things at once and got confused here and there. The code above only creates the xsn version of the infopath form rather than the instance version of the form. So far I have only managed to do this by extracting it from the .xsn file. Thanks…..


        July 12, 2012 at 8:41 pm

      • Just one thing to remember … with SharePoint 2010 you can create InfoPath forms on lists as well as document libraries. Check that you have a document library and not a list. Regards, Nick.

        Nick Grattan

        July 13, 2012 at 6:42 am

  5. Nice one… really useful …. 🙂


    August 21, 2012 at 9:51 am

    • that creates the form but with no extension , when i give “.xml” with the name of the form as argument, it create one but cant open in web … :/


      September 18, 2012 at 1:04 pm

    • Thanks for this great post, it worked fine, but How can I upload in specific folder not at root folder?


      June 13, 2013 at 4:55 pm

  6. […] Source: Nick Grattan’s SharePoint Blog […]

  7. Hi, I’ve got this error message when I wanted to open created document with MS word:
    “We are sorry. We can’t open [document name] because we found a problem with its contents”

    notice that I can open documents which are created manually based on the same template.

    Any advice or comments would be appreciated


    June 24, 2014 at 10:47 am

  8. what about using client object model? is this posible?


    April 29, 2015 at 7:36 am

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: