Saturday, 3 December 2011

NAnt FTP Task

An NAnt task to allow file uploads using FTP allowing FTP+SSL to used.

<target name="ftp">
<ftp
server="ftp.yeticide.co.uk"
username="username"
password="password"
basedir="path-to-folder"
usessl="true">
<fileset>
<include name="NAnt.Task.Ftp/bin/**/*.dll"/>
</fileset>
</ftp>
</target>


using System.IO;
using System.Net;
using System.Text;
using NAnt.Core;
using NAnt.Core.Attributes;
using NAnt.Core.Types;

namespace NAnt.Task.Ftp
{
[TaskName("ftp")]
public class FtpTask : NAnt.Core.Task
{
[TaskAttribute("server")]
public string Server { get; set; }

[TaskAttribute("username")]
public string Username { get; set; }

[TaskAttribute("password")]
public string Password { get; set; }

[TaskAttribute("port")]
public int Port { get; set; }

[TaskAttribute("basedir")]
public string BaseDirectory { get; set; }

[TaskAttribute("usessl")]
public bool UseSSL { get; set; }

[BuildElement("fileset", Required = true)]
public virtual FileSet FileSet { get; set; }

public FtpTask()
{
Port = 21;
}

protected override void ExecuteTask()
{
if (FileSet != null)
{
foreach (var file in FileSet.FileNames)
{
if (File.Exists(file))
{
Log(Level.Info, file);
var ftpRequest = CreateUploadRequest(new FileInfo(file).Name);
// Copy the contents of the file to the request stream.
var sourceStream = new StreamReader(file);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
ftpRequest.ContentLength = fileContents.Length;

var requestStream = ftpRequest.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();

var response = (FtpWebResponse) ftpRequest.GetResponse();
Log(Level.Info, "Upload Complete: {0}", response.StatusDescription);
}
else
{
Log(Level.Error, "File doesn't exists: {0}", file);
}
}
}
}

protected FtpWebRequest CreateUploadRequest(string fileName)
{
var ftpServer = string.Format("ftp://{0}:{1}/{2}/{3}", Server, Port, BaseDirectory, fileName);

Log(Level.Info, "Preparing Upload: {0} => {1}", fileName, ftpServer);
var ftpRequest = (FtpWebRequest)WebRequest.Create(ftpServer);

if (!string.IsNullOrWhiteSpace(Username) && !string.IsNullOrWhiteSpace(Password))
{
ftpRequest.Credentials = new NetworkCredential(Username, Password);
}

if (UseSSL)
{
Log(Level.Info, "Using ssl");
ftpRequest.EnableSsl = true;
}

ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

return ftpRequest;
}
}
}

No comments:

Post a Comment