下面的代码提取了一个 Png 或(已注释掉的 ico 文件),当 Paint 显示时,它会按预期显示一个 16x16 的小图标,但此图标文件(png 或 ico 不能用作 Treeview 图标。其他较大的 Png/Ico 文件可以但是工作正常。
public static bool GetURLIconFile(string webpageUrl, string IconFile)
{
//returns the icon for webpageURL in IconFile
string siteUrl = GetWebSite(webpageUrl); // just returns URL of site
var url = GetURLIcon("http://" + siteUrl);
if (url == null)
{
DeleteFile(IconFile);
return false;
}
try
{
HttpWebRequest w = (HttpWebRequest)HttpWebRequest.Create(url);
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(IconFile, System.Drawing.Imaging.ImageFormat.Png); // forpng
// ico.Save(IconFile, System.Drawing.Imaging.ImageFormat.ico); // forico
}
return true;
}
catch
{
DeleteFile(IconFile);
return false;
}
}
public static Uri GetURLIcon(string siteUrl)
{
// try looking for a /favicon.ico first
try
{
var url = new Uri(siteUrl);
var faviconUrl = new Uri(string.Format("{0}://{1}/favicon.ico", url.Scheme, url.Host));
try
{
using (var httpWebResponse = WebRequest.Create(faviconUrl).GetResponse() as HttpWebResponse)
{
if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.OK)
{
// Log("Found a /favicon.ico file for {0}", url);
return faviconUrl;
}
}
}
catch (WebException)
{
}
// otherwise parse the html and look for <link rel='icon' href='' /> using html agility pack
var htmlDocument = new HtmlWeb().Load(url.ToString());
var links = htmlDocument.DocumentNode.SelectNodes("//link");
if (links != null)
{
foreach (var linkTag in links)
{
var rel = GetAttr(linkTag, "rel");
if (rel == null)
continue;
if (rel.Value.IndexOf("icon", StringComparison.InvariantCultureIgnoreCase) > 0)
{
var href = GetAttr(linkTag, "href");
if (href == null)
continue;
Uri absoluteUrl;
if (Uri.TryCreate(href.Value, UriKind.Absolute, out absoluteUrl))
{
// Log("Found an absolute favicon url {0}", absoluteUrl);
return absoluteUrl;
}
var expandedUrl = new Uri(string.Format("{0}://{1}{2}", url.Scheme, url.Host, href.Value));
//Log("Found a relative favicon url for {0} and expanded it to {1}", url, expandedUrl);
return expandedUrl;
}
}
}
// Log("Could not find a favicon for {0}", url);
return null;
}
catch
{
return null;
}
}