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;
        }

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

///
/// 下载文件(Stream 形式处理)
///
/// 下载文件链接地址
/// 保存路径
///
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 ,然后进行文件流读取,不知为何,自测失败,下载的文件无法正常打开)。 现在还没有找到合理解释,希望大家评论。  
///
/// 下载文件
///
/// 资源URL
/// 保存根目录/目录
///
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;
    }

本文转载自:https://www.cnblogs.com/skyheaving/p/12499629.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值