views:

291

answers:

3

Hello all,

I need to create a newsletters by URL. I to do next:

  1. Create a WebClient;
  2. Use WebClient's method DownloadData to get a source of page in byte array;
  3. Get string from source-html byte array and set it to the newsletter content.

But I have some troubles with paths. All elements' sources were relative (/img/welcome.png) but I need absolute (http://www.mysite.com/img/welcome.png).

How can I do this?

Best regards, Alex.

A: 
Gabriel
Thanks, I know the way like this, but I hoped that there's some more easily way to do it =)
Jo Asakura
A: 

if the request comes in from your site (same domain links) then you can use this:

new Uri(Request.Uri, "/img/welcome.png").ToString();

If you're in a non-web app, or you want to hardcode the domain name:

new Uri("http://www.mysite.com", "/img/welcome.png").ToString();
Artiom Chilaru
I need to replace all elements' src and href in the html what I get not only one path.
Jo Asakura
+2  A: 

One of the possible ways to resolve this task is the use the HtmlAgilityPack library.

Some example (fix links):

WebClient client = new WebClient();
byte[] requestHTML = client.DownloadData(sourceUrl);
string sourceHTML = new UTF8Encoding().GetString(requestHTML);

HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(sourceHTML);

foreach (HtmlNode link in htmlDoc.DocumentNode.SelectNodes("//a[@href]"))
{
    if (!string.IsNullOrEmpty(link.Attributes["href"].Value))
    {
        HtmlAttribute att = link.Attributes["href"];
        att.Value = this.AbsoluteUrlByRelative(att.Value);
    }
}
Jo Asakura