C# download to local through image url

1 Full path image address download, if the suffix is ​​empty, how to deal with it

//url  要下载的图片地址,全路径
//file 要保存的地址 文件夹/文件名
//ext  图片后缀
//fileType 图片后缀
public static bool DownFile2(string url, string file, string ext,out string fileType)
        {
            WebClient wc = new WebClient();
            bool reslut = true;
            try
            {
                
                Stream stream = wc.OpenRead(url);
                //如果图片没有后缀的,根据下面方法获取后缀名
                fileType = wc.ResponseHeaders["Content-Type"].Split('/')[1];

                stream.Close();  //以及释放内存  
                wc.Dispose();
                //  只下载这几种类型png  gif  jpeg  bmp  jpg
                if (fileType!= "png" && fileType != "gif" && fileType != "jpeg" && fileType != "bmp" && fileType != "jpg")
                {
                    reslut = false;
                    return reslut;
                }
                if (ext=="")
                {
                    file += "."+ fileType;
                }
                //下载方法
                wc.DownloadFile(url, file);
            }
            catch (Exception e)
            {
                fileType = "";
                reslut = false;
            }
            //下载
            //读取下载下来的源文件HTML格式的字符
            //string mainData = File.ReadAllText(file, Encoding.UTF8);
            //return mainData;
            return reslut;
        }

Guess you like

Origin blog.csdn.net/zhang123csdn/article/details/126437036