Download Multiple (Bulk) Files from FTP folder in ASP.Net using C# and VB.Net

Last Reply on Dec 18, 2017 03:38 AM By dharmendr

Posted on Dec 18, 2017 03:19 AM

Hi ,

In the below link, I want to put a checkbox and perform a bulk download. Also, I want to provide a path where the files should save

https://www.aspsnippets.com/Articles/Download-Files-from-FTP-Web-Server-in-ASPNet-using-C-and-VBNet.aspx

Please let me know how it can be done.

You are viewing reply posted by: dharmendr on Dec 18, 2017 03:38 AM.
Posted on Dec 18, 2017 03:38 AM Modified on on Jan 04, 2018 04:32 AM

Hi Vikash21,

Check this example. Now please take its reference and correct your code.

I have taken reference of the below articles to create the example.

Download Files from FTP Web Server in ASP.Net using C# and VB.Net

Download multiple files as Zip Archive File in ASP.Net using C# and VB.Net

HTML

<asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="chkSelect" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Size" HeaderText="Size (KB)" DataFormatString="{0:N2}" />
        <asp:BoundField DataField="Date" HeaderText="Created Date" />
    </Columns>
</asp:GridView>
<asp:Button ID="Button1" Text="Download" runat="server" OnClick="DownloadMultipleFileAsZip" />

Namespaces

C#

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.UI.WebControls;
using Ionic.Zip;

VB.Net

Imports System.Net
Imports Ionic.Zip
Imports System.IO
Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    GetFilesFromFTP();
}

protected void DownloadMultipleFileAsZip(object sender, EventArgs e)
{
    List<Files> fileList = new List<Files>();
    foreach (GridViewRow row in gvFiles.Rows)
    {
        if ((row.FindControl("chkSelect") as CheckBox).Checked)
        {
            string fileName = row.Cells[1].Text.Trim();
            string ftp = "ftp://yourserver.com/";
            string ftpFolder = "Uploads/";
            try
            {
                WebClient request = new WebClient();
                string url = ftp + ftpFolder + fileName;
                request.Credentials = new NetworkCredential("Username", "Password");
                byte[] bytes = request.DownloadData(url);
                fileList.Add(new Files() { FileName = fileName, Bytes = bytes });
            }
            catch (WebException ex)
            {
                throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
            }
        }
    }

    using (ZipFile zip = new ZipFile())
    {
        zip.AlternateEncodingUsage = ZipOption.AsNecessary;
        zip.AddDirectoryByName("Files");
        foreach (Files file in fileList)
        {
            zip.AddEntry(file.FileName, file.Bytes);
        }

        Response.Clear();
        Response.BufferOutput = false;
        string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
        zip.Save(Response.OutputStream);
        Response.End();
    }
}

public void GetFilesFromFTP()
{
    string ftp = "ftp://yourserver.com/";
    string ftpFolder = "Uploads/";
    try
    {
        //Create FTP Request.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder);
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

        //Enter FTP Server credentials.
        request.Credentials = new NetworkCredential("Username", "Password");
        request.UsePassive = true;
        request.UseBinary = true;
        request.EnableSsl = false;

        //Fetch the Response and read it using StreamReader.
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        List<string> entries = new List<string>();
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            //Read the Response as String and split using New Line character.
            entries = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
        }
        response.Close();

        //Create a DataTable.
        DataTable dtFiles = new DataTable();
        dtFiles.Columns.AddRange(new DataColumn[3] { 
        new DataColumn("Name", typeof(string)),                                                    
        new DataColumn("Size", typeof(decimal)),                                                    
        new DataColumn("Date", typeof(string))});

        //Loop and add details of each File to the DataTable.
        foreach (string entry in entries)
        {
            string[] splits = entry.Split(new string[] { " ", }, StringSplitOptions.RemoveEmptyEntries);

            //Determine whether entry is for File or Directory.
            bool isFile = splits[0].Substring(0, 1) != "d";
            bool isDirectory = splits[0].Substring(0, 1) == "d";

            //If entry is for File, add details to DataTable.
            if (isFile)
            {
                dtFiles.Rows.Add();
                dtFiles.Rows[dtFiles.Rows.Count - 1]["Size"] = decimal.Parse(splits[4]) / 1024;
                dtFiles.Rows[dtFiles.Rows.Count - 1]["Date"] = string.Join(" ", splits[5], splits[6], splits[7]);
                string name = string.Empty;
                for (int i = 8; i < splits.Length; i++)
                {
                    name = string.Join(" ", name, splits[i]);
                }
                dtFiles.Rows[dtFiles.Rows.Count - 1]["Name"] = name.Trim();
            }
        }
        gvFiles.DataSource = dtFiles;
        gvFiles.DataBind();
    }
    catch (WebException ex)
    {
        throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
    }
}

public class Files
{
    public string FileName { get; set; }
    public byte[] Bytes { get; set; }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    GetFilesFromFTP()
End Sub

Protected Sub DownloadMultipleFileAsZip(ByVal sender As Object, ByVal e As EventArgs)
    Dim fileList As List(Of Files) = New List(Of Files)()
    For Each row As GridViewRow In gvFiles.Rows
        If (TryCast(row.FindControl("chkSelect"), CheckBox)).Checked Then
            Dim fileName As String = row.Cells(1).Text.Trim()
            Dim ftp As String = "ftp://yourserver.com/"
            Dim ftpFolder As String = "Uploads/"
            Try
                Dim request As WebClient = New WebClient()
                Dim url As String = ftp & ftpFolder & fileName
                request.Credentials = New NetworkCredential("Username", "Password")
                Dim bytes As Byte() = request.DownloadData(url)
                fileList.Add(New Files() With {.FileName = fileName, .Bytes = bytes})
            Catch ex As WebException
                Throw New Exception((TryCast(ex.Response, FtpWebResponse)).StatusDescription)
            End Try
        End If
    Next

    Using zip As ZipFile = New ZipFile()
        zip.AlternateEncodingUsage = ZipOption.AsNecessary
        zip.AddDirectoryByName("Files")
        For Each file As Files In fileList
            zip.AddEntry(file.FileName, file.Bytes)
        Next

        Response.Clear()
        Response.BufferOutput = False
        Dim zipName As String = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"))
        Response.ContentType = "application/zip"
        Response.AddHeader("content-disposition", "attachment; filename=" & zipName)
        zip.Save(Response.OutputStream)
        Response.[End]()
    End Using
End Sub

Public Sub GetFilesFromFTP()
    Dim ftp As String = "ftp://yourserver.com/"
    Dim ftpFolder As String = "Uploads/"
    Try
        Dim request As FtpWebRequest = CType(WebRequest.Create(ftp & ftpFolder), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails
        request.Credentials = New NetworkCredential("Username", "Password")
        request.UsePassive = True
        request.UseBinary = True
        request.EnableSsl = False
        Dim response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)
        Dim entries As List(Of String) = New List(Of String)()
        Using reader As StreamReader = New StreamReader(response.GetResponseStream())
            entries = reader.ReadToEnd().Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).ToList()
        End Using

        response.Close()
        Dim dtFiles As DataTable = New DataTable()
        dtFiles.Columns.AddRange(New DataColumn(2) {New DataColumn("Name", GetType(String)), New DataColumn("Size", GetType(Decimal)), New DataColumn("Date", GetType(String))})
        For Each entry As String In entries
            Dim splits As String() = entry.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)
            Dim isFile As Boolean = splits(0).Substring(0, 1) <> "d"
            Dim isDirectory As Boolean = splits(0).Substring(0, 1) = "d"
            If isFile Then
                dtFiles.Rows.Add()
                dtFiles.Rows(dtFiles.Rows.Count - 1)("Size") = Decimal.Parse(splits(4)) / 1024
                dtFiles.Rows(dtFiles.Rows.Count - 1)("Date") = String.Join(" ", splits(5), splits(6), splits(7))
                Dim name As String = String.Empty
                For i As Integer = 8 To splits.Length - 1
                    name = String.Join(" ", name, splits(i))
                Next

                dtFiles.Rows(dtFiles.Rows.Count - 1)("Name") = name.Trim()
            End If
        Next

        gvFiles.DataSource = dtFiles
        gvFiles.DataBind()
    Catch ex As WebException
        Throw New Exception((TryCast(ex.Response, FtpWebResponse)).StatusDescription)
    End Try
End Sub

Public Class Files
    Public Property FileName As String
    Public Property Bytes As Byte()
End Class