简体   繁体   中英

c# System.ArgumentNullException: Value cannot be null. Parameter name: source

The program that I have created needs to read information from a website and then store it. I am getting the error:

System.ArgumentNullException: Value cannot be null.
Parameter name: source
at System.Linq.Enumerable.Select[TSource,TResult](IEnumerable 1 source, Func 2 selector)

However it does not always run in error. As in sometimes it works and sometimes it doesn't work. How can this be? Here is the code that is giving me the error line 4.

IEnumerable<string> webtemp = Enumerable.Empty<string>();
if (datastring.Contains("today_nowcard-temp"))
{
    webtemp = doc.DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span").Select(d => d.InnerText.Trim());

    foreach (var this_header in webtemp)
    {
        string[] temporary = this_header.Trim().Replace("Â", "-").Replace(" ", "-").Split('-');
        int f = (Convert.ToInt32(temporary[0]));
        _actualData[0].temp = GetCelsius(f);
        //Console.WriteLine(_actualData[0].temp);
    }
}

Reason behind this exception is the value that is returned by your SelectNodes method. Sometimes it returns null and then you try to perform Linq operation on null and it generate error. So you can perform a null check on this

var temp= doc.DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span");

if(temp != null){
//TODO
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM