• C# 中从网络上下载文件保存到本地文件


    下面是C#中常用的从Internet上下载文件保存到本地的一些方法,没有太多的技巧。

             1.通过  WebClient  类下载文件

    1     WebClient webClient = new WebClient();
    2     webClient.Encoding = Encoding.UTF8;

    //这里使用DownloadString方法,如果是不需要对文件的文本内容做处理,直接保存,那么可以直接使用功能DownloadFile(url,savepath)直接进行文件保存。
    3 string outText = webClient.DownloadString("https://blog.csdn.net/zxf122895/article/details/77853703"); 4 File.WriteAllText("D:\test1.html", outText);

           

               2.  使用  WebClient  进行图片下载

                 主要思路是通过  WebClient  的 DownloadData 方法下载图片的二进制数据,在通过 MemoryStream 转换为内存流。最后通过 Image 类的 FromStream 方法获取 Image 对象,调用 Image 的 Save(savePath,ImageFormat) 方法保存即可。

    1   WebClient webClient = new WebClient();
    2   Byte[] imgData = webClient.DownloadData("imgurl");
    3   Stream ms = new MemoryStream(imgData);
    4   ms.Position = 0;
    5   Image img = Image.FromStream(ms);
    6   img.Save(@"D:111.jpg", ImageFormat.Jpeg);

           

                3.通过 HttpClient 方法

     1        private static async Task<string> GetMethod(string url)
     2         {
     3             using (HttpClient httpClient = new HttpClient())
     4             {
     5                 HttpResponseMessage response = await httpClient.GetAsync(url);
     6                 response.EnsureSuccessStatusCode();
    //同样的,在此处可通过 ReadAsStreamAsync()方法,以流的方式下载指定文件(或者将网络流通过 MemoryStream 转换为内存流,再转换为byte进行存储或保存),再通过 Image 对象从流中读取图片文件。
    7 string retString = await response.Content.ReadAsStringAsync(); 8 File.WriteAllText("D:\index.html", retString); 9 return retString; 10 } 11 }

     

                 4.HttpWebRequest  方式

    1             HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://Room/6/2/00/0027a4a8-23e5-42e9-ae95-55f4c99fb8db.html");
    2                 httpWebRequest.Method = "GET";
    3                 using (WebResponse response = httpWebRequest.GetResponse())
    4                 {
    5                     Stream stream = response.GetResponseStream();
    6                     StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
    7                     File.WriteAllText("D:\123456.html", streamReader.ReadToEnd());
    8                 }

     

  • 相关阅读:
    LeetCode Single Number
    Leetcode Populating Next Right Pointers in Each Node
    LeetCode Permutations
    Leetcode Sum Root to Leaf Numbers
    LeetCode Candy
    LeetCode Sort List
    LeetCode Remove Duplicates from Sorted List II
    LeetCode Remove Duplicates from Sorted List
    spring MVC HandlerInterceptorAdapter
    yum
  • 原文地址:https://www.cnblogs.com/wangyuliang/p/10322127.html
Copyright © 2020-2023  润新知