Correct usage of SPFileCollection.Add() overloaded method in SPS 2003



I was recently involved in a case involving SPFileCollection.Add() method.  When we use one of the overloads of Add() method the “Created” & “Modified” dates weren’t correct (+5:30 hrs at my end & -7 hrs at the customer’s end – not exactly sure why, perhaps it’s defaulting to GMT as that appears to be the only logical reason).  The following are the overloaded methods in SPFileCollection.Add() method.


 


·         Add(string strUrl,byte[]file, bool overwrite)


·         Add(string strUrl,byte[] file)


·         Add(string strUrl,byte[] file,SPUser createdBy,SPUser modifiedBy,DateTime timeCreated,DateTime timeLastModified)


 


If we use the last overloaded method and provide DateTime.Now as the values for timeCreated & timeLastModified, we’ll see a difference in time between the time the document was uploaded and the time that shows up in the document library against “Created” & “Modified” fields.  Looks like DateTime.Now (by default) picks up GMT time.  Note: The other overloaded methods return the correct date & time.


 


A simple fix is to use DateTime.Now.ToUniversalTime()instead.


 


With my limited search experience, I was not able to find thing small information recorded yet.  So, thought of blogging this and saving some of your time J


 


A quick sample here:


 


static void Main(string[] args)


{


      SPSite site = new SPSite(“http://<sharepointserverurl>”);


      SPWeb web = site.OpenWeb();


      SPFolder folder = web.GetFolder(“shared documents”);


      SPUser user = site.Owner;


 


      FileStream fs = new FileStream(“test.doc”,FileMode.Open);


      byte[] fileContents = new byte[(int)fs.Length];


      fs.Read(fileContents,0,(int)fs.Length);


      fs.Close();


 


      SPFile file = folder.Files.Add(“test.doc”,fileContents,user,user,DateTime.Now.ToUniversalTime(),DateTime.Now.ToUniversalTime());


 


      Console.WriteLine(“Successfully uploaded document”);


      Console.Read();


}

Comments (4)

  1. jim hudson says:

    thanks sridhar, just what i needed. jim

  2. jas says:

    Thanks lot  sridhar, thats my requirement. i search for a long time.

  3. hh says:

    this thing should be deleted. Who cares about SPS2003.

  4. XristosK says:

    Thanks