winforms 下载文件时不了解stream.read()的辅助角色

eqqqjvef  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(149)

我在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循环中?如果我不使用这段代码,那么看起来下载是无限的,文件开始膨胀。
提前感谢!

iyfjxgzm

iyfjxgzm1#

程式码中的注解

// 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);
}

相关问题