Search code examples
c#html-agility-pack

System.Reflection.TargetInvocationException error (C#)


I am trying to get an information from the web (adress in my code) with HtmlAgilityPack in C#, but I have to wait until the <div class="center fs22 green lh32"> is loaded on the page.

When I execute this code :

    var url = $"https://www.website.com/";
    var web = new HtmlWeb();
    var doc = web.LoadFromBrowser(url, html =>
    {
        return !html.Contains("<div class=\"center fs22 green lh32\"></div>");
    });
    string adress = doc.DocumentNode
          .SelectSingleNode("//td/span[@id='testedAddress")
          .Attributes["value"].Value;
    Console.WriteLine("Voici l'adresse :",adress);

I always get this error :

System.Reflection.TargetInvocationException

ThreadStateException: Impossible d'instancier le contrôle ActiveX '8856f961-340a-11d0-a96b-00c04fd705a2', car le thread actuel n'est pas un thread cloisonné (STA, Single-Threaded Apartment).

Translation : System.Reflection.TargetInvocationException: 'An exception has been raised by the target of an appeal.'

ThreadStateException: Can not instantiate ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2', because the current thread is not a partitioned thread (STA, Single-Threaded Apartment).

How can I get rid of this error ?


Solution

  • Apply STAThreadAttribute to your Main function:

     [STAThread]
     static void Main(string[] args)
     {
         //Your code here
     }