码迷,mamicode.com
首页 > Windows程序 > 详细

C#获取网页的HTML码、下载网站图片、获取IP地址

时间:2016-11-01 13:40:03      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:add   ssi   efault   创建   public   work   取数   intern   path   

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地址

标签:add   ssi   efault   创建   public   work   取数   intern   path   

原文地址:http://www.cnblogs.com/kongxiaoshuang/p/6018815.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!