FtpWebRequest Class in System.Net namespace helps in implementing a File Transfer Protocol (FTP) client in .Net.
To obtain an instance of FtpWebRequest, use the Create method.
The URI is of the form "ftp://127.0.0.1/path", first the .NET Framework logs into the FTP server
using the user name and password set by the Credentials property, then the current directory is set to
<UserDirectory>/path.
FtpWebRequest.KeepAlive specifies whether the control connection to the FTP server is closed after the request completes.
FtpWebRequest.UseBinary specifies the data type for file transfers.
FtpWebRequest.Method sets the command to send to the FTP server.
WebRequestMethods.Ftp.UploadFile Field represents the FTP STOR protocol method that uploads a file to an FTP server.
When using an FtpWebRequest object to upload a file to a server, you must write the file content to the request
stream obtained by calling the GetRequestStream method.
You must write to the stream and close the stream before sending the request.
Namespace used:
using System.Net; using System.IO;
public void ftpfile(string ftpfilepath, string inputfilepath)
{
string ftphost = "127.0.0.1";
//here correct hostname or IP of the ftp server to be given
string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential("userid", "password");
//userid and password for the ftp server to given
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(inputfilepath);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
ftpfile(@"/testfolder/testfile.xml", @"c:\testfile.xml");
Really useful piece of code. Thanks for this!
Thanks great article! I have a problem uploading big files, could kindly suggest a method for uploading big file and different file types? thanks in advance
I am using Fileupload (asp.net 3.5) I do not want to give 'inputfilepath' deliberately. Is there any method, so that the file selected from FileUpload can be sent via ftp ??/