【问题标题】:Getting exception with description "Object reference not set to an instance of an object." [duplicate]使用描述“对象引用未设置为对象的实例”获取异常。 [复制]
【发布时间】:2016-07-24 03:27:40
【问题描述】:

我编写了以下方法来从网页中提取所需的 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);
}

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

【问题讨论】:

  • 你应该真正从基本调试开始,至少给我们哪个行号,最好是哪个变量为空,一旦你这样做,你可能会自己找出解决方案.
  • 您对异常消息的哪一部分有疑问?听起来像是一个相当直截了当的信息。您正在尝试访问一个不存在的对象。

标签: c# html windows visual-studio uwp


【解决方案1】:

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

return (elm.InnerHtml); 

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2012-08-08
    • 1970-01-01
    相关资源
    最近更新 更多