Search code examples
c#-4.0sharepointsharepoint-2010sharepoint-2013

Upload/Overwrite SharePoint document without loosing list item metadata from code


I've uploaded a document to SharePoint from code and along with couple of list item properties. I can see the document successfully uploaded with item column values.

In the next step, I've tried to upload the same document without list item properties from code flagging it to overwrite existing file. File was successfully uploaded and overwritten, however it has lost the list item column values provided in first step.

My target is to overwrite the file without disturbing existing list item metadata. This should surely be possible as SharePoint UI can upload/overwrite document without disturbing existing metadata.

Can you anybody let me know how SharePoint achieves this please? Cheers


Solution

  • I've acheived it this way. I reckon this could be the only way.

    using (SPSite site = new SPSite(url))
    {
        using (var web = site.OpenWeb())
        {
            var lib = web.Lists["Documents"] as SPDocumentLibrary;
    
            var file = web.GetFile(string.Format("{0}/Shared Documents/{1}", web.Url, fileName));
    
            if (file.Exists)
                file = lib.RootFolder.Files.Add(fileName, newContent, file.Properties, true);
            else
                file = lib.RootFolder.Files.Add(fileName, newContent, true);
        }
    }
    

    Got to provide file.Properties member, which has all the document properties in a HashTable while adding file. Don't forget to provide True flag to overwrite the document and check out, if required.