2

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 ?

8
  • Are you by any chance running this code in a separate Thread? Mar 1, 2018 at 9:06
  • No, all my code is in one thread
    – Lulucmy
    Mar 1, 2018 at 9:07
  • That's odd, usually this only happens when you try to use UI components in a non STA-Thread. Mar 1, 2018 at 9:08
  • Try setting the thread apartment to STA in your Main() [STAThread]
    – Oscar
    Mar 1, 2018 at 9:09
  • @Lulucmy Is this a console application? Mar 1, 2018 at 9:13

1 Answer 1

3

Apply STAThreadAttribute to your Main function:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.