The Sample Application For Uploading File to FTP Server:
This belowsample Code shows how to upload a file to an FTP server.
using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Net;
using System.IO;
namespaceFileUploadToFTP
{
public partial class Form1 : Form
{
stringfilePath;
publicForm1()
{
InitializeComponent();
}
privatevoid btnBrowse_Click(objectsender, 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 voidbtnUpload_Click(object sender, EventArgs e)
{
if(filePath == "")
{
MessageBox.Show("Please Select The File To Upload..");
}
else
{
btnUpload.Enabled = false;
try
{
FileInfofileInfo = new FileInfo(filePath);
stringfileName = fileInfo.Name.ToString();
WebRequestrequestFTP = WebRequest.Create("ftp://" + txtHost.Text + "/" + fileName);
requestFTP.Credentials = new NetworkCredential(txtUname.Text,txtPsw.Text);
requestFTP.Method = WebRequestMethods.Ftp.UploadFile;
FileStreamfStream = fileInfo.OpenRead();
intbufferLength = 2048;
byte[]buffer = new byte[bufferLength];
StreamuploadStream = requestFTP.GetRequestStream();
intcontentLength = 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.