In this article I will explain how to display List of files from FTP folder with Download option in ASP.Net using C# and VB.Net.
An ASP.Net GridView with a Download button will display the list of files from the FTP folder and when the Download button is clicked, the file will be downloaded from FTP folder.
HTML Markup
The following HTML Markup consists of an ASP.Net GridView.
<asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="100" />
<asp:BoundField DataField="Size" HeaderText="Size (KB)" DataFormatString="{0:N2}"
ItemStyle-Width="100" />
<asp:BoundField DataField="Date" HeaderText="Created Date" ItemStyle-Width="100" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
CommandArgument='<%# Eval("Name") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Net;
using System.Data;
VB.Net
Imports System.IO
Imports System.Net
Imports System.Data
Displaying List of files from FTP folder in ASP.Net
Inside the Page Load event of the page, an FtpWebRequest is made to the FTP Web Server with the Method property set as ListDirectoryDetails.
Once the FtpWebResponse is received, it is read as string using StreamReader class.
Sample FTP Response
Following is a sample FTP Response consisting of two Files and a Directory, difference between File and Directory is the first character which is dash (-) if it is a File and small letter (d) if it is a Directory.
-rw-r--r-- 1 ftp ftp 845941 May 26 00:48 Desert.jpg
-rw-r--r-- 1 ftp ftp 595284 May 26 00:48 Hydrangeas.jpg
drwxr-xr-x 1 ftp ftp 0 May 26 00:51 Images
The response string is first split with New Line character to get individual entries and then each entry is split using Space character to get the details of the File such as its Name, Size and Created Date.
The fetched details are inserted into a DataTable which is then bound to the GridView control.
C#
protected void Page_Load(object sender, EventArgs e)
{
//FTP Server URL.
string ftp = "ftp://yourserver.com/";
//FTP Folder name. Leave blank if you want to list files from root folder.
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();
}
}
//Bind the GridView.
gvFiles.DataSource = dtFiles;
gvFiles.DataBind();
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
'FTP Server URL.
Dim ftp As String = "ftp://yourserver.com/"
'FTP Folder name. Leave blank if you want to list files from root folder.
Dim ftpFolder As String = "Uploads/"
Try
'Create FTP Request.
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(ftp & ftpFolder), FtpWebRequest)
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.
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
Dim entries As New List(Of String)()
Using reader As 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()
End Using
response.Close()
'Create a DataTable.
Dim dtFiles As New DataTable()
dtFiles.Columns.AddRange(New DataColumn(2) { _
New DataColumn("Name", GetType(String)), _
New DataColumn("Size", GetType(Decimal)), _
New DataColumn("Date", GetType(String))})
'Loop and add details of each File to the DataTable.
For Each entry As String In entries
Dim splits As String() = entry.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)
'Determine whether entry is for File or Directory.
Dim isFile As Boolean = splits(0).Substring(0, 1) <> "d"
Dim isDirectory As Boolean = splits(0).Substring(0, 1) = "d"
'If entry is for File, add details to DataTable.
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
'Bind the GridView.
gvFiles.DataSource = dtFiles
gvFiles.DataBind()
Catch ex As WebException
Throw New Exception(TryCast(ex.Response, FtpWebResponse).StatusDescription)
End Try
End Sub
Downloading a File from FTP folder in ASP.Net
Each GridView row consists of a Download Button to download the respective file from the FTP folder. When the Download button is clicked, an FtpWebRequest is made to the FTP Web Server with the Method property set as DownloadFile.
Once the FtpWebResponse is received, it is copied to the MemoryStream class object which is then written to the Response Stream as an Array of bytes and finally it is downloaded as file.
C#
protected void DownloadFile(object sender, EventArgs e)
{
string fileName = (sender as LinkButton).CommandArgument;
//FTP Server URL.
string ftp = "ftp://yourserver.com/";
//FTP Folder name. Leave blank if you want to Download file from root folder.
string ftpFolder = "Uploads/";
try
{
//Create FTP Request.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
request.Method = WebRequestMethods.Ftp.DownloadFile;
//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 into a MemoryStream object.
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using (MemoryStream stream = new MemoryStream())
{
//Download the File.
response.GetResponseStream().CopyTo(stream);
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(stream.ToArray());
Response.End();
}
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
}
VB.Net
Protected Sub DownloadFile(sender As Object, e As EventArgs)
Dim fileName As String = TryCast(sender, LinkButton).CommandArgument
'FTP Server URL.
Dim ftp As String = "ftp://yourserver.com/"
'FTP Folder name. Leave blank if you want to Download file from root folder.
Dim ftpFolder As String = "Uploads/"
Try
'Create FTP Request.
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(Convert.ToString(ftp & ftpFolder) & fileName), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.DownloadFile
'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 into a MemoryStream object.
Dim resp As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
Using stream As New MemoryStream()
'Download the File.
resp.GetResponseStream().CopyTo(stream)
Response.AddHeader("content-disposition", "attachment;filename=" & fileName)
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(stream.ToArray())
Response.End()
End Using
Catch ex As WebException
Throw New Exception(TryCast(ex.Response, FtpWebResponse).StatusDescription)
End Try
End Sub
Screenshot
Downloads
Download Code