Introduction:
In my previous article I have explained about Auto refresh page using javascript. In this article I am going to
explain about how to upload file to ftp server using c# code
Explanation:
The code uses FileInfo and FtpWebRequest classes. To use this classes include the below two namespaces in the code first.
using System.IO;
using System.Net;
Below is the code used to upload file to ftp server.
private void
UploadFileToFTPServer(string filename)
{
string ftpServerIP = "ftp.server.in/";
string ftpUserName = "username";
string ftpPassword = "password";
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();
Console.Write("File upload success...");
}
catch (Exception
ex)
{
throw
ex;
}
}
Comments
Post a Comment