C# 正则获取图片路径并保存至本地

C# 正则获取图片路径并保存至本地

var reg = new System.Text.RegularExpressions.Regex("<\\s*img\\s+[^>]*?src\\s*=\\s*(\'|\")(.*?)\\1[^>]*?\\/?\\s*>");
            var srcReg = new System.Text.RegularExpressions.Regex("(?<=(src=\"))[^\"]*?(?=\")");
            int i = 0;
            foreach (DataRow dr in dt.Rows)
            {
                foreach (object a in reg.Matches(dr["content"].ToString()))
                {
                    i++;
                    //imgList.Add(a.ToString());
                    string s = srcReg.Match(a.ToString()).Value;
                    try
                    {
                        Down(s, s.Substring(s.IndexOf("allimg") + 7, s.Length - s.IndexOf("allimg") - 7).Replace("/", "-"));
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine(s);
                        Console.WriteLine(ex.Message);
                        continue;
                    }
                }
            }
            Console.WriteLine(i);
            Console.ReadKey();

执行下载并保存到本地方法:

        /// <summary>
        /// 执行下载并保存到本地
        /// </summary>
        /// <param name="url">图片地址</param>
        /// <param name="dtnow">保存的文件名</param>

        public static void Down(string url, string dtnow)
        {
            WebRequest wreq = WebRequest.Create(url);
            HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
            Stream s = wresp.GetResponseStream();
            System.Drawing.Image img;
            img = System.Drawing.Image.FromStream(s);
            img.Save("H:\\木庄网络博客\\DataCleaning\\img\\" + dtnow, ImageFormat.Jpeg);

            MemoryStream ms = new MemoryStream();
            img.Save(ms, ImageFormat.Jpeg);
            img.Dispose();


        }

欢迎分享,(木庄网络博客交流QQ群:562366239

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论