Home > Enterprise >  Don't Understand Secondary Role of Stream.Read() While Downloading File
Don't Understand Secondary Role of Stream.Read() While Downloading File

Time:09-22

I made a button in WinForms to download file from FTP and it works fine but I don't understand what Stream.Read() method is doing in the while loop in the code below (in DownLoadFileFromFtp method):

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

Can anybody explain what this piece of code doing (bytesRead = ftpResponseStream.Read(buffer, 0, buffer.Length);) in a while loop? If I don use this piece of code then it seems like download is infinite and the file began to be bloated.

Thanks in advance!

CodePudding user response:

Comments in code

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

  • Related