首页 > 代码库 > C#获取网页的HTML码、下载网站图片、获取IP地址
C#获取网页的HTML码、下载网站图片、获取IP地址
1、根据URL请求获取页面HTML代码
/// <summary> /// 获取网页的HTML码 /// </summary> /// <param name="url">链接地址</param> /// <param name="encoding">编码类型</param> /// <returns></returns> public static string GetHtmlStr(string url, string encoding) { string htmlStr = ""; if (!String.IsNullOrEmpty(url)) { WebRequest request = WebRequest.Create(url); //实例化WebRequest对象 WebResponse response = request.GetResponse(); //创建WebResponse对象 Stream datastream = response.GetResponseStream(); //创建流对象 Encoding ec = Encoding.Default; if (encoding == "UTF8") { ec = Encoding.UTF8; } else if (encoding == "Default") { ec = Encoding.Default; } StreamReader reader = new StreamReader(datastream, ec); htmlStr = reader.ReadToEnd(); //读取数据 reader.Close(); datastream.Close(); response.Close(); } return htmlStr; }
2、下载网站图片
/// <summary> /// 下载网站图片 /// </summary> /// <param name="picUrl"></param> /// <returns></returns> public string SaveAsWebImg(string picUrl) { string result = ""; string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/File/"; //目录 try { if (!String.IsNullOrEmpty(picUrl)) { Random rd = new Random(); DateTime nowTime = DateTime.Now; string fileName = nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + ".jpeg"; WebClient webClient = new WebClient(); webClient.DownloadFile(picUrl, path + fileName); result = fileName; } } catch { } return result; }
3、获取本地IP地址
/// <summary> /// 获取本地IP地址信息 /// </summary> public string GetAddressIP() { ///获取本地的IP地址 string AddressIP = string.Empty; foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (_IPAddress.AddressFamily.ToString() == "InterNetwork") { AddressIP = _IPAddress.ToString(); } } return AddressIP.ToString(); }
C#获取网页的HTML码、下载网站图片、获取IP地址
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。