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

Last Reply 11 days ago By itsgaurav

Posted 11 days ago

Dear Sir

All i need is download folders or images from FTP Server to a specific location only using VB.NET or ASP.NET. I saw you wonderful code example which explained that how can we download files from FTP. But that example is prompting SAVE/OPEN dialog. My need is to automatically save images to specific folder. e.g. "c:\UserName\Images" on button click.

Thanks in advance   

Posted 11 days ago

Hi itsgaurav,

Check with the below code.

C#

protected void DownloadFile(object sender, EventArgs e)
{
    string fileName = (sender as LinkButton).CommandArgument;
    string ftp = "ftp://yourserver.com/";
    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 (Stream responseStream = response.GetResponseStream())
        {
            using (Stream fileStream = new FileStream(@"c:\UserName\Images\" + fileName, FileMode.CreateNew))
            {
                responseStream.CopyTo(fileStream);
            }
        }
    }
    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
	Dim ftp As String = "ftp://yourserver.com/"
	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 response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
		Using responseStream As Stream = response.GetResponseStream()
			Using fileStream As Stream = New FileStream(Convert.ToString("c:\UserName\Images\") & fileName, FileMode.CreateNew)
				responseStream.CopyTo(fileStream)
			End Using
		End Using
	Catch ex As WebException
		Throw New Exception(TryCast(ex.Response, FtpWebResponse).StatusDescription)
	End Try
End Sub

 

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html