Programmatically download file from FTP site using .Net

In this post I will discuss how to use FtpWebRequest class to download a file from a FTP location. The code makes use of GetResponse method to get response as byte array. You can argue about why not use DownloadFile method on WebClient. There are certain issues with use of this method. This method does not provide a lot of control on request. For example if the file is large, your request could time out. Or if you do not want process to block the request for long time, you will not be able to control it. By setting Timeout property, you can indicate when to terminate request of it is taking too long. Use of FtpWebRequest allows you to set more options on the request to control its behavior.

Code

static string DownloadDataFromFtp(string sourceFileLocation)
{
    var uri = new Uri(sourceFileLocation);
    var ftpClient = FtpWebRequest.CreateDefault(uri);
    ftpClient.Timeout = 15000;
    var response = ftpClient.GetResponse() as FtpWebResponse;
    string ftpdata = string.Empty;
    try
    {
        ftpdata = ProcessFtpContent(response);
    }
    finally
    {
        response.Close();
    }
    return ftpdata;
}

static string ProcessFtpContent(FtpWebResponse resp)
{
    string content = string.Empty;
    MemoryStream memStream = new MemoryStream();
    const int BUFFER_SIZE = 4096;
    int read = 0;
    int idx = 0;
    long size = 0;
    memStream.SetLength(BUFFER_SIZE);
    try
    {
        using (memStream)
        {
            while (true)
            {
                read = 0;
                byte[] respBuffer = new byte[BUFFER_SIZE];
                read = resp.GetResponseStream().Read(respBuffer, 0, BUFFER_SIZE);
                if (read == 0)
                {
                    break;
                }

                size += read;
                memStream.SetLength(size);
                memStream.Write(respBuffer, 0, read);
                idx += read;
            }
            content = System.Text.Encoding.UTF8.GetString(memStream.ToArray());
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine("ProcessContent[Failed]: {0} ", ex.Message);
        throw;
    }

    return content;
}
    

Search

Social

Weather

19.1 °C / 66.3 °F

weather conditions Clear

Monthly Posts

Blog Tags