I spent a good part of the day today trying to figure out how to pragmatically add files to a document library.  I had to read in a directory of files, parse their names and add them to the document library.  In addition to adding the file, I needed to set a few fields, one of them being a Date and Time column/property.  Easy enough, right?  Well, I quickly found out it wasn't as easy as I originally thought.

My first attempt went as you would think.  I tried to set the Property to a DateTime object.

    1 //create the SP file to upload and set its initial properties

    2 SPFile fileToUpload = docLib.RootFolder.Files.Add(fl.Name, binFile, true);

    3 fileToUpload.Properties["Name"] = string.Format("{0} {1}", fileNameParts[1], fileNameParts[0]);

    4 fileToUpload.Properties["DateField"] = DateTime.Parse("12/18/2007");

    5 fileToUpload.Update();


As I thought, that worked fine.  The problem came when i hit a date that was prior to 1/1/1970.

    1 //create the SP file to upload and set its initial properties

    2 SPFile fileToUpload = docLib.RootFolder.Files.Add(fl.Name, binFile, true);

    3 fileToUpload.Properties["Name"] = string.Format("{0} {1}", fileNameParts[1], fileNameParts[0]);

    4 fileToUpload.Properties["DateField"] = DateTime.Parse("1/1/1968");

    5 fileToUpload.Update();


It throws the following error : "Microsoft.SharePoint.SPInvalidPropertyException: Date Times before 1/1/1970 are not supported.".  So anything after 1/1/1970 works fine, but anything prior to 1/1/1970 throws an error?!?!?!?!?

I searched high and low all over Google, the forums, etc.  Nothing, relating to anything with .NET, DateTime object, and a 1/1/1970 barrier.  So after doing a bunch of trial and error, I stumbled upon it. 
Sharepoint expects Date and Time columns in UTC format.  So what does that mean?

A UTC date should come in the form : yyyy-mm-ddThh:mm:ssZ    where T and Z are literals.
So here is the updated code that worked for me.

    1 //create the SP file to upload and set its initial properties

    2 SPFile fileToUpload = docLib.RootFolder.Files.Add(fl.Name, binFile, true);

    3 fileToUpload.Properties["Name"] = string.Format("{0} {1}", fileNameParts[1], fileNameParts[0]);

    4 //Date's are stored in SP in the format :    yyyy-mm-ddThh:mm:ssZ   T/Z are literals

    5 fileToUpload.Properties["DateField"] = "1950-01-01T00:00:00Z";

    6 fileToUpload.Update();


Posted in: Sharepoint  Tags: , ,
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2017 Tony Testa's World