我在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:\Users\nstelmak\Downloads\testFile.txt");
}
}
有人能解释一下这段代码在做什么吗(bytesRead = ftpResponseStream.Read(buffer,0,buffer.Length);)在while循环中?如果我不使用这段代码,那么看起来下载是无限的,文件开始膨胀。
提前感谢!
1条答案
按热度按时间iyfjxgzm1#
程式码中的注解