In some code I've been recently writing, one of the more tricky issues has been retrieving the identity of the user who created a list item. There is nothing on the SPListItem class or any of its base classes and in fact buried in the documentation is this snippet of code:
string userValue = listItem["Assigned To"];
int index = userValue.IndexOf(';');
int id = Int32.Parse(userValue.Substring(0, index));
SPUser user = site.SiteUsers.GetByID(id);
…with a note to say that you can use this to also get the Author and Editor fields.
But this is misleading in three respects:
-
The field containing the creator of the list item appears to be *either* "Created By" *or* "Author".
-
The indexer returns an object, not a string, so you have to cast the return value in the first line to a string.
-
In some cases the "Created By" field is null (appears that this may be a time-based issue and that immediately after creation the "Created By" field may not be set, so you need to defend against a null value coming back from the field.
So my code ended up being:
string creator;
object oCreator = item["Created By"];
if (oCreator != null)
{
creator = oCreator.ToString();
}
else
{
oCreator = item["Author"];
if (oCreator != null)
{
creator = oCreator.ToString();
}
}
if (creator != null)
{
// Do stuff with the creator string
}