C#转换SharePoint API日期字符串遇空值报错,求解决方案
问题描述
在C#处理SharePoint列表的OpeningDate列时,遇到空值转换失败的问题,会返回“return error string parse”错误。已尝试以下加载SharePoint数据的代码:
// Get items from sharepoint list try { context.Load(items, its => its.Include( i => i.Id, i => i["SOQAssignmentCode"], i => i["OpeningDate"] )); } catch (Exception d) { ComponentMetaData.FireError(0, "", "Error on Load context SP Source." + d.Message, "", 0, out vbool); } try { context.ExecuteQuery(); } catch (Exception d) { ComponentMetaData.FireError(0, "", "Error on ExecuteQuery SP Source." + d.Message, "", 0, out vbool); }
以及以下转换代码,但转换过程失败:
try { //Récupérations des données string ac = string.Empty; string ast = string.Empty; string dateValue = null; string emptyString = "01/01/1900 00:00:00"; string dateValue4 = null; foreach (ListItem listItem in items) { dateValue = listItem["OpeningDate"]?.ToString() ?? emptyString; dateValue4 = listItem["OpeningDate"]?.ToString() ?? null; var dateValue2 = DateTime.ParseExact(dateValue4,"yyyy/mm/dd", null); if (listItem["SOQAssignmentCode"] != null) { foreach (ListItem item_not_to_take in listItems_not_to_take) { if (listItem["SOQAssignmentCode"].ToString() != item_not_to_take["SOQAssignmentCode"].ToString()) ac = listItem["SOQAssignmentCode"].ToString(); Output0Buffer.AddRow(); Output0Buffer.SOQAssignmentCode = ac; Output0Buffer.SOQOpeningDate = dateValue2; Output0Buffer.SPID = listItem.Id;
请问:
- 空值转换失败的原因是什么?
- 是否有更简便的日期字符串转换方法?
问题分析与解决方案
空值转换失败的原因
- 当
OpeningDate为空时,dateValue4被赋值为null,而DateTime.ParseExact不接受null作为输入字符串,直接调用会抛出ArgumentNullException,导致转换失败。 - 格式字符串
"yyyy/mm/dd"存在错误:mm代表分钟,日期的月份应该用大写MM,这会导致非空日期也可能出现转换错误。
更简便的日期转换方法
直接将SharePoint字段值转换为DateTime?(可空DateTime类型),无需先转字符串,从根源避免格式问题和空值处理的麻烦:
优化后的转换代码示例
foreach (ListItem listItem in items) { // 直接转换为可空DateTime,空值自动转为null DateTime? openingDate = listItem["OpeningDate"] as DateTime?; // 按需处理空值,替换为默认日期(如果不需要默认值,直接使用openingDate即可) DateTime dateValue2 = openingDate ?? new DateTime(1900, 1, 1); if (listItem["SOQAssignmentCode"] != null) { foreach (ListItem item_not_to_take in listItems_not_to_take) { if (listItem["SOQAssignmentCode"].ToString() != item_not_to_take["SOQAssignmentCode"].ToString()) ac = listItem["SOQAssignmentCode"].ToString(); Output0Buffer.AddRow(); Output0Buffer.SOQAssignmentCode = ac; // 如果SOQOpeningDate是可空类型,直接赋值openingDate即可 Output0Buffer.SOQOpeningDate = dateValue2; Output0Buffer.SPID = listItem.Id; } } }
额外容错优化
如果必须通过字符串转换,建议使用DateTime.TryParseExact替代ParseExact,即使格式有误或值为空也不会抛出异常,而是返回转换是否成功的布尔值:
string dateStr = listItem["OpeningDate"]?.ToString(); DateTime parsedDate; if (DateTime.TryParseExact(dateStr, "yyyy/MM/dd", null, DateTimeStyles.None, out parsedDate)) { dateValue2 = parsedDate; } else { // 转换失败时的处理逻辑,比如赋值默认日期 dateValue2 = new DateTime(1900, 1, 1); }
内容的提问来源于stack exchange,提问作者Henry-Philippe Dumont LU
相关产品推荐
相关产品推荐

