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