SharePoint Config

Ari Bakker's thoughts on customising and configuring SharePoint

Programatically Populating a Document Library

without comments

Every now and then I want to populate a SharePoint document library with files for testing purposes. To do this I have created a little console app that will take a template file and upload it x number of times to a document library, generating a unique name each time. At the moment this is a very basic application, but if you need to generate dummy data then it provides a starting place for doing so.

Note: If you are running this on a publishing site you might also want to turn off content approval for the document library (list > settings > document library settings > versioning settings > content approval) so that everyone can see the documents.

File Uploading Program

class Program

static readonly string webUrl = “http://localhost”;
static readonly string docLibrary = “Documents”;
static readonly string template = “C:\\Temp\\PageTemplate.doc”;
static readonly int itemsToUpload = 200;

static void Main(string[] args)
UploadFiles(webUrl, docLibrary, template, itemsToUpload);

/// Populates a document library with x number of randomly named files based on a template
static void UploadFiles(string webUrl, string docLibrary, string template, int itemsToUpload)
using (SPWeb web = new SPSite(webUrl).OpenWeb())
// get a reference to the folder to populate
SPFolder docLib = web.Folders[webUrl + “/” + docLibrary];
byte[] binFile = null;

// read in the template file
using (FileStream fStream = new FileStream(template, System.IO.FileMode.Open))
binFile = new byte[(int)fStream.Length];
fStream.Read(binFile, 0, (int)fStream.Length);

// grab the extension of the file
string ext = template.Substring(template.LastIndexOf(“.”));

for (int i = 0; i < itemsToUpload; i++)
// generate random filename
Guid fileGuid = Guid.NewGuid();
string filename = fileGuid.ToString() + ext;

// upload and check in
SPFile file = docLib.Files.Add(filename, binFile);
file.CheckIn(“System checkin”);
Console.WriteLine(“Added “ + filename + ” to “ + docLibrary + ” library”);

Post to Twitter Post to Delicious Post to Digg Post to Reddit Post to StumbleUpon

Written by Ari Bakker

April 25th, 2007 at 10:33 pm

Posted in Development

Leave a Reply