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" : "文件大小不一样");

posted on 2019-07-23 11:23  在代码的世界里游走  阅读(1037)  评论(0编辑  收藏  举报