在c#中读取的文本文件

时间:2009-11-27 10:55:46

标签: c# text-files

我有一个文本文件,它来自邮件正文的内容。它包含html代码。

我只想从该文本文件中获取href标记。我想用asp.net c#web应用程序执行此操作。

是否有人有代码可以帮助我...

谢谢

2 个答案:

答案 0 :(得分:8)

尝试使用Html Agility Pack解析电子邮件中的HTML,并从< a>中提取 href 属性。标签

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(emailBody);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
{
   HtmlAttribute att = link.Attributes["href"];
   string href = att.Value;
}

答案 1 :(得分:1)

你可以使用正则表达式,即使它不是一个完美的解决方案:

class Program
{
    static void Main(string[] args)
    {
        var text = File.ReadAllText(@"d:\test.htm");

        Regex regex = new Regex("href\\s*=\\s*\"([^\"]*)\"", RegexOptions.IgnoreCase);
        MatchCollection matches = regex.Matches(text);
        foreach(Match match in matches)
        {
            Console.WriteLine(match.Groups[1]);
        }
    }
}