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.

3 Responses to Set Title Field on Document Upload

  1. Ezz says:

    Very good article!
    It solved my problem.
    THANKS 🙂

  2. Panoone says:

    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.

    • Stu says:

      Yep, that’s quite common with the SharePoint API, some of the attributes for fields have to be uppercase TRUE\FALSE and won’t accept other variations.

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve the maths problem shown below before posting: *