• WebClient 从服务器下载/获取文件方式


      今天主要记录、分享 使用WebClient 下载/获取 文件的两种方式。  

      话不多说,放置代码。

      第一种:使用 WebClient 自封装方法: DownloadFile();  下载方便、直接。

            /// <summary>
            /// 下载文件(WebClient.DownloadFile)
            /// </summary>
            /// <param name="downFileUrl">下载文件链接地址</param>
            /// <param name="savePath">保存路径</param>
            /// <returns></returns>
            public static string DownLoadFileByWebClientStatic(string downFileUrl, string savePath)
            {
                string result = string.Empty;
                try
                {
                    WebClient wcClient = new WebClient();
                    wcClient.DownloadFile(downFileUrl, savePath);
                    result = "下载成功";
                }
                catch (WebException ex)
                {
                    result = $"下载失败!Error={ ex.Message}";
                }
                return result;
            }
    
            /// <summary>
            /// 下载文件(wcClient.DownloadFileAsync)
            /// </summary>
            /// <param name="downFileUrl">下载文件链接地址</param>
            /// <param name="savePath">保存路径</param>
            /// <returns></returns>
            public static string DownLoadFileMethod(string downFileUrl, string savePath)
            {
                string result = string.Empty;
                try
                {
                    WebClient wcClient = new WebClient();
                    wcClient.DownloadDataCompleted += (t, s) =>
                    {
                        result = "下载成功";//不会直接返回(无状态?)
                    };
                    wcClient.DownloadFileAsync(new Uri(downFileUrl), savePath);
                }
                catch (WebException ex)
                {
                    result = $"下载失败!Error={ ex.Message}";
                }
                return result;
            }

      第二种:使用读取文件流形式下载/获取文件。(自测通过)

         /// <summary>
            /// 下载文件(Stream 形式处理)
            /// </summary>
            /// <param name="downFileUrl">下载文件链接地址</param>
            /// <param name="savePath">保存路径</param>
            /// <returns></returns>
            public static string DownLoadFileByWebClient(string downFileUrl, string savePath)
            {
                string result = string.Empty;
                try
                {
                    WebClient wcClient = new WebClient();
    
                    WebRequest webReq = WebRequest.Create(downFileUrl);
                    WebResponse webRes = webReq.GetResponse();
                    long fileLength = webRes.ContentLength;
                    Stream srm = webRes.GetResponseStream();
                    StreamReader srmReader = new StreamReader(srm);
    
                    byte[] bufferbyte = new byte[fileLength];
                    int allByte = (int)bufferbyte.Length;
                    int startByte = 0;
                    while (fileLength > 0)
                    {
                        int downByte = srm.Read(bufferbyte, startByte, allByte);
                        if (downByte == 0) break;
                        startByte += downByte;
                        allByte -= downByte;
                    }
                    //检测保存文件所在目录是否存在
                    if (!File.Exists(savePath))
                    {
                        string[] dirArray = savePath.Split('\');
                        string temp = string.Empty;
                        for (int i = 0; i < dirArray.Length - 1; i++)
                        {
                            temp += dirArray[i].Trim() + "\";
                            if (!Directory.Exists(temp))
                                Directory.CreateDirectory(temp);
                        }
                    }
    
                    using (FileStream fsSave = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        fsSave.Write(bufferbyte, 0, bufferbyte.Length);
                        fsSave.Dispose();
                    }
                    
                    //与using 方法两者等同。
                    //FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
                    //fs.Write(bufferbyte, 0, bufferbyte.Length);
                    srm.Close();
                    srmReader.Close();
                    //fs.Close();
    
                    result = $"下载成功 path={savePath}";
                }
                catch (WebException ex)
                {
                    result = $"下载失败!Error={ ex.Message}";
                }
                return result;
            }
            

         第二种 通过文件流 下载,方法分支:(使用WebClient 的 OpenRead() 方式获取到Stream ,然后进行文件流读取,不知为何,自测失败,下载的文件无法正常打开)。 现在还没有找到合理解释,希望大家评论。    

     /// <summary>
            /// 下载文件
            /// </summary>
            /// <param name="URLAddress">资源URL</param>
            /// <param name="saveBasePath">保存根目录/目录</param>
            /// <returns></returns>
            public string DownFileByStream(string URLAddress, string saveBasePath)
            {
                string result = string.Empty;
                try
                {
                    WebClient client = new WebClient();
                    Stream str = client.OpenRead(URLAddress);
                    StreamReader reader = new StreamReader(str);
    
                    byte[] bytes = new byte[1024 * 1024];//自定义大小 1M
                    int allybytes = (int)bytes.Length;
                    int startbytes = 0;
    
                    while (allybytes > 0)
                    {
                        int m = str.Read(bytes, startbytes, allybytes);  //获取当前读取字节位置
                        if (m == 0)
                            break;
                        startbytes += m;
                        allybytes -= m;
                    }
    
                    reader.Dispose();
                    str.Dispose();
                    
                    string path = saveBasePath + System.IO.Path.GetFileName(URLAddress);
                    FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                    fsWrite.Write(bytes, 0, startbytes);
                    fsWrite.Flush();
                    fsWrite.Close();
    
                    result = "下载成功!";
                }
                catch (Exception ex)
                {
                    result = "下载失败!" + ex.Message;
                }
                return result;
            }

        如有不合理之处,欢迎指出。以上就是今天的记录;本文大部分内容都可以搜到,只是此处做了一个小整理。

        如果您觉得本文对您有帮助,欢迎点击“收藏”按钮!(/:微笑)欢迎转载,转载请注明出处。

  • 相关阅读:
    I-Cache和D-cache
    socat使用
    反射
    属性方法
    getitem
    文件打开编辑和函数参数
    python3编码问题个人理解
    正文内容 python3编码问题
    进度条制作
    集合关系
  • 原文地址:https://www.cnblogs.com/skyheaving/p/12499629.html
Copyright © 2020-2023  润新知