How to upload and download files thru FTP Server?

How to upload and download files thru FTP Server?

I have use several references in creating this window application. I have somehow simplified it and extract codes from the references that I have used. There is only three buttons, they are upload, download and close. The upload button is used to copy file to ftp server. In short You are transferring or copying your local file to ftp server. The download button is used to get file from ftp server to your local folder or machine. The close button is used to close your application.

Here is what the application looks like, Here is my code,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace UploadDownloadFilesThruFTP
{
public partial class Form1 : Form
{
string ftpserverip;
string username;
string password;
string localFilename;
string targetFilename;
#region “Methods”
/// <summary>
/// Method to upload the specified file to the specified FTP Server
/// </summary>
/// <param name=”filename”>file full name to be uploaded</param>
private void Upload(string filename)
{
try
{
FileInfo fileInf = new FileInfo(filename);
if (ftpserverip == string.Empty)
ftpserverip = this.txtFtpServerIP.Text.Trim();
if (username == string.Empty)
username = this.txtUsername.Text.Trim();
if (password == string.Empty)
password = this.txtPassword.Text.Trim();
string uri = “ftp://” + ftpserverip + “/” + fileInf.Name;
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(“ftp://” + ftpserverip + “/” + fileInf.Name));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(username, password);
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Upload Error”);
}
}

private void Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
//filePath = <<The full path where the file is to be created.>>,
//fileName = <<Name of the file to be created(Need not be the name of the file on FTP server).>>
if (ftpserverip == string.Empty)
ftpserverip = this.txtFtpServerIP.Text.Trim();
if (username == string.Empty)
username = this.txtUsername.Text.Trim();
if (password == string.Empty)
password = this.txtPassword.Text.Trim();
FileStream outputStream = new FileStream(filePath + “\\” + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(“ftp://” + ftpserverip + “/” + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(username, password);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private bool CheckFTPSettings()
{
bool isFtp = true;
if (this.txtFtpServerIP.Text.Length == 0)
{
MessageBox.Show(“FTP Server name or IP Address is required.”);
isFtp = false;
this.txtFtpServerIP.Focus();
}
else
{
if (this.txtUsername.Text.Length == 0)
{
MessageBox.Show(“Username is required.”);
isFtp = false;
this.txtUsername.Focus();
}
else
{
if (this.txtPassword.Text.Length == 0)
{
MessageBox.Show(“Password is required.”);
isFtp = false;
this.txtPassword.Focus();
}
}
}
return isFtp;
}
#endregion

public Form1()
{
InitializeComponent();
ftpserverip = string.Empty;
username = string.Empty;
password = string.Empty;
localFilename = string.Empty;
targetFilename = string.Empty;
}

private void Form1_Load(object sender, EventArgs e)
{
this.txtFtpServerIP.Text = “ftp.converged.net.au”;
this.txtUsername.Text = “arnold”;
this.txtPassword.Text = “passw0rd”;
}

private void btnUpload_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog files = new OpenFileDialog();
files.ShowDialog();
if (files.SafeFileName != string.Empty)
localFilename = files.FileName;
else
{
MessageBox.Show(“Please choose a file to upload.”);
return;
}
if (CheckFTPSettings())
Upload(localFilename);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
}

private void btnDownloadFile_Click(object sender, EventArgs e)
{
try
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
localFilename = ofd.SafeFileName;
if (CheckFTPSettings())
{
if (fbd.ShowDialog() == DialogResult.OK)
{
Download(fbd.SelectedPath, localFilename);
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}

}

private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
  Here are my references that I have used in this blog:

Code Project

C# Corner

Code Guru

MSDN – Microsoft

Ondotnet

Advertisements
This entry was posted in C# 3.5, FTP Server. Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s