C# 从SP2010读取文件属性时,对象引用未设置为对象的实例
我有一个sharepoint文档库,它有一个名为“DocumentType”的自定义字段,这不是必填字段。当我尝试使用下面的代码读取此属性时,如果此字段中有值,其工作正常,但其值为空,则出现错误“对象引用未设置为对象的实例。”如果值不存在,我需要传递空字符串以进行进一步的逻辑,我如何处理C# 从SP2010读取文件属性时,对象引用未设置为对象的实例,c#,sharepoint-2010,nullreferenceexception,C#,Sharepoint 2010,Nullreferenceexception,我有一个sharepoint文档库,它有一个名为“DocumentType”的自定义字段,这不是必填字段。当我尝试使用下面的代码读取此属性时,如果此字段中有值,其工作正常,但其值为空,则出现错误“对象引用未设置为对象的实例。”如果值不存在,我需要传递空字符串以进行进一步的逻辑,我如何处理 SPFile spFile=Web.GetFile(Context.Request.Url.ToString()); string spDocumentType=string.Empty; if (spFile
SPFile spFile=Web.GetFile(Context.Request.Url.ToString());
string spDocumentType=string.Empty;
if (spFile.Properties["DocumentType"].ToString() == "INV") *In this line exception throwing where value is empty in this field in the doc library.
{
spDocumentType = spFile.Properties["DocumentType"].ToString();
}
这样做:
if(spFile.Properties["DocumentType"] !=null)
{
spDocumentType = spFile.Properties["DocumentType"].ToString() == "INV" ? spFile.Properties["DocumentType"].ToString() : "";
}
else
{
spDocumentType ="";
}
更改这段代码:
spFile.Properties["DocumentType"].ToString()
为此:
Convert.ToString(spFile.Properties["DocumentType"])
ToString()
抛出值为null
时出现的异常,该方法测试null
并返回一个空字符串。您是genius bro,它的工作方式很有魅力,感谢您的回复。上面两个答案都是正确的,但不允许同时接受这两个答案。