欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-11 08:37:51
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" : "文件大小不一样");

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