Simple enough question: I\'ve created a small app that is basically just a favourites that sits in my system tray so that I can open often-used sites/folders/files from the
The first thing to look for is /favicon.ico in the site root; something like WebClient.DownloadFile() should do fine. However, you can also set the icon in metadata - for SO this is:
<link rel="shortcut icon"
href="http://sstatic.net/stackoverflow/img/favicon.ico">
and note that alternative icons might be available; the "touch" one tends to be bigger and higher res, for example:
<link rel="apple-touch-icon"
href="http://sstatic.net/stackoverflow/img/apple-touch-icon.png">
so you would parse that in either the HTML Agility Pack or XmlDocument (if xhtml) and use WebClient.DownloadFile()
Here's some code I've used to obtain this via the agility pack:
var favicon = "/favicon.ico";
var el=root.SelectSingleNode("/html/head/link[@rel='shortcut icon' and @href]");
if (el != null) favicon = el.Attributes["href"].Value;
Note the icon is theirs, not yours.
http://realfavicongenerator.net/favicon_checker?site=http://stackoverflow.com gives you favicon analysis stating which favicons are present in what size. You can process the page information to see which is the best quality favicon, and append it's filename to the URL to get it.
The SHGetFileInfo
(Check pinvoke.net for the signature) lets you retrieve a small or large icon, just as if you were dealing with a file/folder/Shell item.
HttpWebRequest w = (HttpWebRequest)HttpWebRequest.Create("http://stackoverflow.com/favicon.ico");
w.AllowAutoRedirect = true;
HttpWebResponse r = (HttpWebResponse)w.GetResponse();
System.Drawing.Image ico;
using (Stream s = r.GetResponseStream())
{
ico = System.Drawing.Image.FromStream(s);
}
ico.Save("favicon.ico");
It's a good practice to minimize the number of requests each page needs. So if you need several icons, yandex can do a sprite of favicons in one query. Here is an example http://favicon.yandex.net/favicon/google.com/stackoverflow.com/yandex.net/
Using jquery
var favicon = $("link[rel='shortcut icon']").attr("href") ||
$("link[rel='icon']").attr("href") || "";