Here’s a quick one on a straightforward way to upload a document to a SharePoint Document Library using the OM. The key point about this method is the ability to set the Content Type and Metadata at the point of uploading the document:
using (SPSite site = new SPSite("http://sharepointbleached.dev.local"))
{
using (SPWeb web = site.OpenWeb())
{
// Retrieve the required Content Type to be used.
SPContentType ctype = web.ContentTypes["TestDoc"];
SPList library = web.Lists["Test Library"];
// Set the Content Type and Metadata for the Document prior to adding the File
Hashtable properties = new Hashtable();
properties.Add("ContentTypeId", ctype.Id.ToString());
properties.Add("Priority", "(1) High");
properties.Add("TaskStatus", "Completed");
// Open the file to uploaded as a stream object
using (FileStream fs = new FileStream("Sample Presentation.ppt", FileMode.Open))
{
// Add the file passing in the metadata
SPFile file = library.RootFolder.Files.Add(Path.GetFileName(fs.Name), fs, properties, true);
// If Check In / Check Out has been enabled on the library,
// check whether the file needs to be checked in.
if (file.CheckOutType != SPFile.SPCheckOutType.None)
{
file.CheckIn(string.Empty);
}
fs.Close();
}
}
}
My next post will cover how to copy a document from one Web Application to another, preserving the Content Type and Metadata during the copy process.
Happy to answer any questions if you have them, just leave a comment.