Skip to main content

Uploading file to SharePoint with metadata update

The task

Programmatically upload file to SharePoint document library and update document metadata. In our scenario we will have an XML document to upload.

Solution
1. Get the file contents as byte array
2. Add file to the SharePoint SPFolder object
3. Update corresponding item metadata


XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml("");

using (MemoryStream ms = new MemoryStream())
{
try
{
xDoc.Save(ms);

SPFolder folder = null;

SPWeb web = ... // Initialize your SPWeb object here

folder = web.Folders["your_document_library_site_relative_URL"];

string sFileName = "my_new_file_name.xml";

SPFile file = folder.Files.Add(sFileName, ms.ToArray(), true);
// true in Add method above is to say that we overwrite the file if it exists

SPListItem item = file.Item;

item[item.Fields["my_metadata_column_display_name"].InternalName] = "some_value";

... // provide other metadata columns values here

item.Update();
}
catch
{
}
}


Comments

  1. what's the function for string sFileName = "my_new_file_name.xml";?

    ReplyDelete

Post a Comment