下载文件时不了解 Stream.Read() 的次要角色



我在WinForms中制作了一个从FTP下载文件的按钮,它运行良好,但我不明白Stream.Read((方法在下面代码的while循环中(在DownLoadFileFromFtp方法中(做了什么:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static void DownloadFileFromFtp (string serverURI, string pathToLocalFile)
{
FileStream localFileStream = File.Open(pathToLocalFile, FileMode.OpenOrCreate);
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(serverURI);
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpRequest.Credentials = new NetworkCredential("demo", "password");
WebResponse ftpResponse = ftpRequest.GetResponse();
Stream ftpResponseStream = ftpResponse.GetResponseStream();
byte[] buffer = new byte[2048];
Console.WriteLine($"nBuffer length is: {buffer.Length}");
int bytesRead = ftpResponseStream.Read(buffer, 0, buffer.Length);
while(bytesRead > 0)
{
localFileStream.Write(buffer, 0, buffer.Length);
bytesRead = ftpResponseStream.Read(buffer, 0, buffer.Length);
}
localFileStream.Close();
ftpResponseStream.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
if(NetworkInterface.GetIsNetworkAvailable())
{
toolStripStatusLabel1.Text = "Connected";
}
else
{
toolStripStatusLabel1.Text = "Disconnected";
}
}
private void DownloadFile_Click(object sender, EventArgs e)
{
DownloadFileFromFtp("ftp://test.rebex.net/pub/example/readme.txt", @"C:UsersnstelmakDownloadstestFile.txt");
}
}

有人能解释这段代码的作用吗(bytesRead=ftpResponseStream.Read(buffer,0,buffer.Length(;(在一段时间内?如果我不使用这段代码,那么下载量似乎是无限的,文件开始膨胀。

提前感谢!

代码中的注释

// Take initial read. The return value is number of bytes you had read from the ftp stream.
// it is not guarantee what that number will be
int bytesRead = ftpResponseStream.Read(buffer, 0, buffer.Length);
// Now you need to keep reading until the return value is '0'. If you call 
// stream.read() and got '0', it means that you came to the end of stream
while(bytesRead > 0)
{
localFileStream.Write(buffer, 0, buffer.Length);
// here you're going to keep reading bytes in the loop 
// until you come to the end of stream and can't read no more
bytesRead = ftpResponseStream.Read(buffer, 0, buffer.Length);
}

最新更新