C#实战小技巧(十一):获取网站图标

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/WZh0316/article/details/86355764

大部分正规网站的图标都保存在固定位置,可使用url地址进行下载,该url地址一般是“https://”或“http://” + “网址” + “/favicon.ico”,例如百度的网址为“www.baidu.com”,它的图标存放在“https://www.baidu.com/favicon.ico”。
下方是获取网址图标的C#示例代码,address变量是网址,下载图标后转为base64,保存在info对象的functionIcon属性中。

					string url = string.Empty; //网址图标地址

                    int lastPointIndex = address.LastIndexOf(".");
                    string prefix = address.Substring(0, lastPointIndex); //获取前缀
                    if (!prefix.StartsWith("https://") && !prefix.StartsWith("http://"))
                    {
                        prefix = new StringBuilder("https://").Append(prefix).ToString();
                    }

                    string suffix = address.Substring(lastPointIndex); //获取后缀
                    if (suffix.Contains("/"))
                    {
                        int slashIndex = suffix.IndexOf("/");
                        suffix = suffix.Substring(0, slashIndex);
                    }

                    url = new StringBuilder(prefix).Append(suffix).Append("/favicon.ico").ToString();

                    WebRequest request = WebRequest.Create(new Uri(url));
                    request.Timeout = 20 * 1000;
                    request.Method = "GET";
                    WebResponse response = request.GetResponse();
                    using (Stream s = response.GetResponseStream())
                    {
                        byte[] buff = new byte[1024];
                        int length = 0;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            while ((length = s.Read(buff, 0, buff.Length)) > 0)
                            {
                                ms.Write(buff, 0, length);
                            }

                            byte[] arr = new byte[ms.Length];
                            ms.Position = 0;
                            ms.Read(arr, 0, (int)ms.Length);
                            info.functionIcon = Convert.ToBase64String(arr).Trim();
                        }
                    }

                    response.Close();

猜你喜欢

转载自blog.csdn.net/WZh0316/article/details/86355764