Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从SP2010读取文件属性时,对象引用未设置为对象的实例_C#_Sharepoint 2010_Nullreferenceexception - Fatal编程技术网

C# 从SP2010读取文件属性时,对象引用未设置为对象的实例

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

我有一个sharepoint文档库,它有一个名为“DocumentType”的自定义字段,这不是必填字段。当我尝试使用下面的代码读取此属性时,如果此字段中有值,其工作正常,但其值为空,则出现错误“对象引用未设置为对象的实例。”如果值不存在,我需要传递空字符串以进行进一步的逻辑,我如何处理

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,它的工作方式很有魅力,感谢您的回复。上面两个答案都是正确的,但不允许同时接受这两个答案。