Here an example of how to upload a file to a FTP-server, using the class FtpWebRequest
, which is included in the .NET Framework.
string ftpPath = string.Format("ftp://{0}/{1}", urlOrIpNumber, filePath);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpPath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential (userName, password);
byte[] fileContents = GetFileContent();
request.ContentLength = fileContents.Length;
using(var requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
}
All you need to do is reference the System.Net
namespace.
Update: Shorter code version
This code comes from Mads Kristensen, written in the middle of 2006.
private static void Upload(string ftpServer, string userName, string password, string filename)
{
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential(userName, password);
client.UploadFile(ftpServer + "/" + new FileInfo(filename).Name, "STOR", filename);
}
}
I'm not sure if there are any scenarios that this code doesn't work with.