Wednesday, December 2, 2009

How to set custom document template to document Library programmatically?

Setting custom document template to SharePoint document library involves two steps:
  1. Upload template document to the Forms Directory of SharePoint document Library
FileStream stream = File.OpenRead(@"c:\doc.doc");

byte[] content = new byte[stream.Length];
// Read the file from the stream into the byte array
stream.Read(content, 0, (int)stream.Length);
stream.Close();

// Give the file a name, used as the name of the list
// item once it gets into the document library
string fileNameOnceInLibrary = "NewTemplate.doc";

SPList list = CurrentWeb.Lists[“Shared Documents”];
//CurrentWeb is assumed to be created..

SPDocumentLibrary docLib = list as SPDocumentLibrary;
SPFolder DocParent = web.Folders[strDocLibName];
SPFolder formsFolder = DocParent.SubFolders["Forms"];

// Add the file to the Files collection and commit to database
SPFile file = formsFolder.Files.Add(formsFolder.Url + "/" + fileNameOnceInLibrary, content, true);

formsFolder.Update();

  1. Setting the DocumentTemplateUrl property for the document library:

docLib.DocumentTemplateUrl = file.Url;

docLib.Update();

No comments: