Set Title Field on Document Upload

When uploading a file to a SharePoint library through code, you sometimes want to set item properties at the same time the document is created. To achieve this you simply populate a Hashtable object and pass this into the Add method of the SPFileCollection object:

public SPFile UploadDocument(SPDocumentLibrary library, string filename, string docTitle, byte[] fileBinary)
{
    SPFileCollection files = library.RootFolder.Files;
    System.Collections.Hashtable hash = new System.Collections.Hashtable();
    hash.Add("Title", docTitle);
 
    SPFile file = files.Add(filename, fileBinary, hash, false);
    return file;
}

There is an issue with the above method when trying to set the value for the Title field. After adding the file, you’ll find the Title column is left blank and SharePoint has not set its value. To have the value set, you have a couple of options.

  • 1. Change the name of the key in the Hashtable from “Title” to “vti_title”
  • 2. Use the unique identifier of the title field

For example:

public SPFile UploadDocument(SPDocumentLibrary library, string filename, string docTitle, byte[] fileBinary)
{
    SPFileCollection files = library.RootFolder.Files;
    System.Collections.Hashtable hash = new System.Collections.Hashtable();
    hash.Add("vti_title", docTitle);
 
    SPFile file = files.Add(filename, fileBinary, hash, false);
    return file;
}

or, use the built-in SPBuiltInFieldId.Title property value:

public SPFile UploadDocument(SPDocumentLibrary library, string filename, string docTitle, byte[] fileBinary)
{
    SPFileCollection files = library.RootFolder.Files;
    System.Collections.Hashtable hash = new System.Collections.Hashtable();
    hash.Add(SPBuiltInFieldId.Title.ToString(), docTitle);
 
    SPFile file = files.Add(filename, fileBinary, hash, false);
    return file;
}

Using either of the above will result in the title field being set on creation of the document.

This entry was posted in SharePoint and tagged . Bookmark the permalink.
0 0 votes
Article Rating
Subscribe
Notify of
guest

Solve the maths problem shown below before posting: *

3 Comments
Inline Feedbacks
View all comments
Ezz

Very good article!
It solved my problem.
THANKS 🙂

Panoone

Very useful and still applies to 2013. Seems insane that using the correct internal name “Title” doesn’t work as expected.

Just an FYI, it should be vti_title, not vti_Title. It’s case-sensitive.