Wednesday, October 8, 2008

Programmatically Upload Documents to a SP Doc Library


I’m rather late getting around to posting this, but for anyone who has to program against a SharePoint document library (or the SPListItems that those documents correspond to), I hope this can be a quick jump-start. 

While migrating a large enterprise application to SharePoint, we had to make sure that the EIGHTEEN GIGABYTES of documents came along with the rest of the application.  (For anyone who’s curious about the performance considerations involved in such an effort, I’d be glad to discuss). 

But as far as the actual uploading of the documents to the SharePoint document library, then subsequently setting a few properties on the newly-uploaded documents, I think once you check out the source code you’ll agree it’s actually rather straight forward. 

So I’ll let the source do the talking …

// Open the site and web
SPSite site = new SPSite(txtSite.Text);
SPWeb web = site.OpenWeb();
SPFolder docLibFolder = web.GetFolder(txtDocumentLibrary.Text);

// Read the file on disk into a FileStream
FileStream fs;
Byte[] docContents;
fs = File.OpenRead(fileName);
docContents = new byte[Convert.ToInt32(fs.Length)];
fs.Read(docContents, 0, Convert.ToInt32(fs.Length));

// Perform the actual upload to the SP doc library
SPFile uploadedFile;
uploadedFile = docLibFolder.Files.Add(documentTitle, docContents);

// The “.Add()” method return to us a reference to the document’s
// corresponding SPListItem object. Here we can set properies as needed.
SPListItem listItem;
listItem = uploadedFile.Item;

listItem["Title"] = documentTitle;
listItem["Name"] = documentTitle;

listItem.Update();

// Close our FileStream object to release the resources
fs.Close();

No comments: