我有以下代码:
foreach (SPListItem item in list.Items)
{
string itemId = item.ID.ToString();
string contentType = item.ContentType.ToString();
string displayName = item.DisplayName;
string name = item.Name;
// todo: Title not always retreiving? Likely due to folders, needs more handling
//string title = item["Title"].ToString() ?? null;
string title = "";
string url = item.Url;
string author = item["Created By"].ToString();
// todo: Checked out files catering
const string checkedOutBy = "";
DateTime lastModified = Convert.ToDateTime(item["Modified"]);
string lastModifiedBy = item["Modified By"].ToString();
DateTime created = Convert.ToDateTime(item["Created"]);
query.RecordItems(itemId, contentType,
displayName, name,
title, url, author,
checkedOutBy,
lastModified,
lastModifiedBy,
created,
author);
}
我遇到的问题是,在循环 Title 或 ContentType 的某些迭代中会抛出 Nullreferenceexception,但不是在所有迭代中都会抛出。我相信我已经通过以下方式满足了这一点,但我不确定 - 有没有更好的方法?
foreach (SPListItem item in list.Items)
{
try
{
string itemId = item.ID.ToString();
string contentType = item.ContentType.ToString();
string displayName = item.DisplayName;
string name = item.Name;
// todo: Title not always retreiving? Likely due to folders, needs more handling
//string title = item["Title"].ToString() ?? null;
string title = "";
string url = item.Url;
string author = item["Created By"].ToString();
// todo: Checked out files catering
const string checkedOutBy = "";
DateTime lastModified = Convert.ToDateTime(item["Modified"]);
string lastModifiedBy = item["Modified By"].ToString();
DateTime created = Convert.ToDateTime(item["Created"]);
query.RecordItems(itemId, contentType,
displayName, name,
title, url, author,
checkedOutBy,
lastModified,
lastModifiedBy,
created,
author);
}
catch (NullReferenceException ex)
{
Logger.Error("[{0}] Filed moving on file {1} as not all content was present", item.Name);
}
}