获取描述异常“对象引用未设置为对象的实例”。

时间:2016-07-23 19:04:19

标签: c# html windows visual-studio uwp

我写了以下方法从网页中提取所需的html数据:

public async System.Threading.Tasks.Task<string> getdata()
{
    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    HttpClient client = new HttpClient();
    HtmlDocument document = new HtmlDocument();
    byte[] htmlb = (await client.GetByteArrayAsync("http://<path-to-cgi>?passwd=" + (string)localSettings.Values["password"] + "&<param>=<hardcoded value>" + "&<param>=<hardcoded value>").ConfigureAwait(false));
    document.LoadHtml(Encoding.UTF8.GetString(htmlb,0,htmlb.Length));
    var inputs = document.DocumentNode.Descendants("div");
    HtmlNode elm = null;
    foreach (var input in inputs)
    {
        if (input.Attributes["id"].ToString() == "main")
        {
            elm = input;
        }
    }
    return (elm.InnerHtml);
}

当我执行此方法时,我得到上面提到的异常。

1 个答案:

答案 0 :(得分:0)

看起来你的if条件可能返回false,并且没有为elm分配值。为了确保从函数返回值,请替换

return (elm.InnerHtml); 

if(elm != null){
return (elm.InnerHtml ?? "");
}
else{
return "";
}