• C# -- 使用缓冲区进行文件下载操作


    C# -- 使用缓冲区进行文件下载操作

    1. 为避免下载超大文件占用内存资源,文件下载使用缓冲区,一点一点读取文件资源。

        string str0 = @"ftp://localhost:21/xx/1.txt";
        string str1 = @"D:2.txt";
    
        FtpWebRequest ftpWebRequest1 = (FtpWebRequest)WebRequest.Create(str0);
        ftpWebRequest1.KeepAlive = false;
        ftpWebRequest1.Method = WebRequestMethods.Ftp.GetFileSize;
        FtpWebResponse ftpWebResponse1 = (FtpWebResponse)ftpWebRequest1.GetResponse();
        long iContentLength1 = ftpWebResponse1.ContentLength;
        Console.WriteLine("FTP file content length:{0}字节", iContentLength1);
    
    
        FtpWebRequest ftpWebRequest2 = (FtpWebRequest)WebRequest.Create(str0);
        ftpWebRequest2.Method = WebRequestMethods.Ftp.DownloadFile;
        FtpWebResponse ftpWebResponse2 = (FtpWebResponse)ftpWebRequest2.GetResponse();
        Stream stream = ftpWebResponse2.GetResponseStream();
    
        FileStream fileStream = new FileStream(str1, FileMode.Create);
    
        int BufferSize = 2* 1024 * 1024;
        byte[] Buffer = new byte[BufferSize];
    
        int iRead = 0;
        iRead = stream.Read(Buffer, 0, BufferSize);
        while (iRead > 0)
        {
            fileStream.Write(Buffer, 0, iRead);
            iRead = stream.Read(Buffer, 0, BufferSize);
        }
    
    stream.Close();
        fileStream.Close();
    FileInfo newFileInfo
    = new FileInfo(str1); long iContentLength2 = newFileInfo.Length; Console.WriteLine("Download file content lenth:{0}字节", iContentLength2); Console.WriteLine("文件校验:{0}", iContentLength1 == iContentLength2 ? "OK" : "文件大小不一样");

  • 相关阅读:
    迷宫 广搜
    steam 字符串hash or map
    Karen与测试 奇迹淫巧+快速幂
    puzzle 期望树形DP
    函数 贪心
    P1032 字串变换 字符串
    等效集合 图论(缩点)
    高斯消元
    loj2537. 「PKUWC2018」Minimax
    loj2538. 「PKUWC2018」Slay the Spire
  • 原文地址:https://www.cnblogs.com/ChengWenHao/p/CSharpDownloadFileUseBufferByte.html
Copyright © 2020-2023  润新知