Hi namojainashis...,
Refer below sample code.
HTML
<asp:Button Text="View" runat="server" OnClick="FTPViewPDF" />
Namespaces
C#
using System.IO;
using System.Net;
VB.Net
Imports System.IO
Imports System.Net
Code
C#
protected void FTPViewPDF(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 webResponse = (FtpWebResponse)request.GetResponse();
using (MemoryStream stream = new MemoryStream())
{
//Download the File.
CopyStream(webResponse.GetResponseStream(), stream);
byte[] bytes = stream.ToArray();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
}
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[4096];
while (true)
{
int read = input.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
return;
}
output.Write(buffer, 0, read);
}
}
VB.Net
Protected Sub FTPViewPDF(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = (TryCast(sender, LinkButton)).CommandArgument
Dim ftp As String = "ftp://yourserver.com/"
Dim ftpFolder As String = "Uploads/"
Try
Dim request As FtpWebRequest = CType(WebRequest.Create(ftp & ftpFolder & fileName), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.DownloadFile
request.Credentials = New NetworkCredential("Username", "Password")
request.UsePassive = True
request.UseBinary = True
request.EnableSsl = False
Dim webResponse As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)
Using stream As MemoryStream = New MemoryStream()
CopyStream(webResponse.GetResponseStream(), stream)
Dim bytes As Byte() = stream.ToArray()
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/pdf"
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Using
Catch ex As WebException
Throw New Exception((TryCast(ex.Response, FtpWebResponse)).StatusDescription)
End Try
End Sub
Public Shared Sub CopyStream(ByVal input As Stream, ByVal output As Stream)
Dim buffer As Byte() = New Byte(4095) {}
While True
Dim read As Integer = input.Read(buffer, 0, buffer.Length)
If read <= 0 Then
Return
End If
output.Write(buffer, 0, read)
End While
End Sub