This is a task that I’ve come across a few times over the years I’ve been working with SharePoint. The way to do it isn’t immediately obvious and I always end up stuffing around looking for a solution. So, I thought I’d document it once and for all.
The code below outlines the basic steps:
// open site and get the spweb
SPSite site = new SPSite(Insert your site URL here);
SPWeb web = site.OpenWeb();
// open document library as a folder
SPFolder docoLibFolder = web.GetFolder(Insert the name of the document library here);
// upload document
FileStream fStream = File.OpenRead(Insert the path of the document to load here);
Byte[] Contents = new byte[Convert.ToInt32(fStream.Length)];
fStream.Read(Contents, 0, Convert.ToInt32(fStream.Length));
SPFile uploadedFile = docoLibFolder.Files.Add(documentNumber, Contents);
// check the document in if it is checked out
// (depends on the security settings of the document library)
if (uploadedFile.CheckOutStatus != SPFile.SPCheckOutStatus.None)
{
uploadedFile.CheckIn(Insert Comments Here);
}
Note that the file is returned to you when you add it to the ‘Files’ collection. Once you’ve got the SPFile you can get the actual SPListItem and add meta-data if required.
SPListItem listItem = uploadedFile.Item;
-->