将链接存储到变量而不是文本文件中

Store links into variable instead of text file

我正处于 C# 的早期学习阶段。我有一个用于将 Web 链接存储到文本文件中的代码。我如何将它们存储到变量中,以便稍后在代码中遍历它们并分别访问它们?

        string pdfLinksUrl = "https://www.nordicwater.com/products/waste-water/";

        // Load HTML content    
        var webGet = new HtmlAgilityPack.HtmlWeb();
        var doc = webGet.Load(pdfLinksUrl);

        // select all <A> nodes from the document using XPath
        // (unfortunately we can't select attribute nodes directly as
        // it is not yet supported by HAP)
        var linkNodes = doc.DocumentNode.SelectNodes("//a[@href]");

        // select all href attribute values ending with '.pdf' (case-insensitive)
        var pdfUrls = from linkNode in linkNodes
                      let href = linkNode.Attributes["href"].Value
                      where href.ToLower().StartsWith("https://www.nordicwater.com/product/")
                      select href;

        // write all PDF links to file
        System.IO.File.WriteAllLines(@"c:\temp\pdflinks.txt", pdfUrls.ToArray());

pdfUrls 保存你所有的 URL,当你将它们全部写入文件时你正在使用它

您可以使用 foreach 循环来轻松循环访问 URL:

foreach (string url in odfUrls.ToArray()) {
    Console.WriteLine($"PDF URL: {url}");
}