Tuesday, June 1, 2010

How to update file / list item without harming the metadata & some more tips...

Nice thing I came across with the other day -

If you need to modify some SPListItem fields in lists, but you want to keep the "modified by" or "Last modified by" as it were before you can just use the method SystemUpdate ( which is exactly like Update but without changing those fields ).

 
using (SPSite site = new SPSite("http://blah-blah.com"))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["ListName"];
foreach(SPListItem item in list.Items)
{

item["Title"] = "*changed*";
item.SystemUpdate();
}
}
}

Another cool thing is :

You have two different "last modified" for a SPListItem. What do I mean by that ? you have the SPListItem["Last Modified"] value and you have also under SPListItem.File.TimeLastModified. In other words, you can see when the file that corresponds with that item were last used and not assuming that date from the "last modified" value that you have in the list.

 
public DateTime TimeLastModified { get; }


Last cool thing, promise , for this post :

When you want to upload a file to a list ( adding it to a file collection of that list ) you can you use a really strong overload under SPFileCollection -
 

public SPFile Add (
string urlOfFile,
Stream stream,
SPUser createdBy,
SPUser modifiedBy,
DateTime timeCreated,
DateTime timeLastModified
)


With this overload you determine what will be the createdBy,modifiedBy,timeCreated,timeLast modified...

This is very useful when you need to download/upload files from/to you SharePoint sites ( dont forget of course to backup metadata before using that so you will be able to retrieve it back :) )