Monday, 18 June 2007

Adding a document to a Document library

Here is one that stumped me for a while

One of my fellow developers had a web part that needed to convert a xml file to a pdf and then add the pdf to a document library . Well the conversion worked and everything was fine except he couldn’t workout how to get the pdf in to a document library.
There are no overrides on the .Add() method of the SPListItemCollection Class that take File in to account, the .File propriety is only a get and we didn’t know what Field to use. Evan the SPDocumentLibrary class was of no use.

After a bit of head scratching we found that we needed to use the list.Rootfolder.Files.add

This is in the SDK on one line in one of the related classes but I can’t find it again

Hopefully this post will help anyone else that gets snagged on this simple process

A useful tip

The Add method of the SPFilecolection returned a SPFile object
So you can use this code to add your relevant meta data

SPFile newFile = list.Rootfolder.Files.add( fileURL, fileStream);
SPListItem fileItem = newFile.Item;

Hope that help

No comments: