Upload file on FTP
Here are sample code to upload file on FTP Server
string filename = Server.MapPath("file1.txt");
string ftpServerIP = "ftp.demo.com/";
string ftpUserName = "dummy";
string ftpPassword = "dummy";
FileInfo objFile = new FileInfo(filename);
FtpWebRequest objFTPRequest;
// Create FtpWebRequest object
objFTPRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + objFile.Name));
// Set Credintials
objFTPRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
// By default KeepAlive is true, where the control connection is
// not closed after a command is executed.
objFTPRequest.KeepAlive = false;
// Set the data transfer type.
objFTPRequest.UseBinary = true;
// Set content length
objFTPRequest.ContentLength = objFile.Length;
// Set request method
objFTPRequest.Method = WebRequestMethods.Ftp.UploadFile;
// Set buffer size
int intBufferLength = 16 * 1024;
byte[] objBuffer = new byte[intBufferLength];
// Opens a file to read
FileStream objFileStream = objFile.OpenRead();
try
{
// Get Stream of the file
Stream objStream = objFTPRequest.GetRequestStream();
int len = 0;
while ((len = objFileStream.Read(objBuffer, 0, intBufferLength)) != 0)
{
// Write file Content
objStream.Write(objBuffer, 0, len);
}
objStream.Close();
objFileStream.Close();
}
catch (Exception ex)
{
throw ex;
}
Please make sure your ftp path is set as shown below.
string CompleteDPath = "ftp://www.example.com/wwwroot/videos/";
string FileName = "sample.mp4";
WebRequest reqObj = WebRequest.Create(CompleteDPath + FileName);
The following script work great with me for uploading files and videos to another servier via ftp.
FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl + "" + username + "_" + filename);
ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword);
ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftpClient.UseBinary = true;
ftpClient.KeepAlive = true;
System.IO.FileInfo fi = new System.IO.FileInfo(fileurl);
ftpClient.ContentLength = fi.Length;
byte[] buffer = new byte[4097];
int bytes = 0;
int total_bytes = (int)fi.Length;
System.IO.FileStream fs = fi.OpenRead();
System.IO.Stream rs = ftpClient.GetRequestStream();
while (total_bytes > 0)
{
bytes = fs.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
total_bytes = total_bytes - bytes;
}
//fs.Flush();
fs.Close();
rs.Close();
FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
value = uploadResponse.StatusDescription;
uploadResponse.Close();
You can also use the higher-level WebClient
type to do FTP stuff with much cleaner code:
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
client.UploadFile("ftp://ftpserver.com/target.zip", "STOR", localFilePath);
}