In System.Net namespace the FtpWebRequest class is used for implementing a File Transfer Protocol(FTP) client . By using Credentials property first the .NET framework connect to FTP Server then The Create method is creates the file with same name as we selected by browse button, After that the file is reading by using OpenRead() method of FileStream class to a buffer, And then the buffer data is sequentially copied to FTP server File.
The Sample Application For Uploading File to FTP Server:
This below
sample Code shows how to upload a file to an FTP server.
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.Net;
using System.IO;
namespace
FileUploadToFTP
{
public partial class Form1 : Form
{
string
filePath;
public
Form1()
{
InitializeComponent();
}
private
void btnBrowse_Click(object
sender, EventArgs e)
{
openFileDialog1.CheckFileExists = true;
openFileDialog1.Filter = "*|*";
openFileDialog1.FileName = "";
openFileDialog1.InitialDirectory = Environment.CurrentDirectory.ToString();
if
(openFileDialog1.ShowDialog() == DialogResult.OK)
{
filePath =
openFileDialog1.FileName.ToString();
}
txtFileUpPath.Text = filePath;
}
private void
btnUpload_Click(object sender, EventArgs e)
{
if
(filePath == "")
{
MessageBox.Show("Please Select The File To Upload..");
}
else
{
btnUpload.Enabled = false;
try
{
FileInfo
fileInfo = new FileInfo(filePath);
string
fileName = fileInfo.Name.ToString();
WebRequest
requestFTP = WebRequest.Create("ftp://" + txtHost.Text + "/" + fileName);
requestFTP.Credentials = new NetworkCredential(txtUname.Text,
txtPsw.Text);
requestFTP.Method = WebRequestMethods.Ftp.UploadFile;
FileStream
fStream = fileInfo.OpenRead();
int
bufferLength = 2048;
byte[]
buffer = new byte[bufferLength];
Stream
uploadStream = requestFTP.GetRequestStream();
int
contentLength = fStream.Read(buffer, 0, bufferLength);
while
(contentLength != 0)
{
uploadStream.Write(buffer, 0, contentLength);
contentLength =
fStream.Read(buffer, 0, bufferLength);
}
uploadStream.Close();
fStream.Close();
requestFTP = null;
MessageBox.Show("File Uploading Is SuccessFull...");
}
catch
(Exception ep)
{
MessageBox.Show("ERROR: " + ep.Message.ToString());
}
btnUpload.Enabled = true;
filePath = "";
txtHost.Text = txtUname.Text =
txtPsw.Text = txtFileUpPath.Text = "";
}
}
}
}
For Entire Solution code File CLICK HERE.