# Thursday, 25 March 2010

Upload a file using FTPS

I just implemented a little routine to upload a file to an FTP site using SSL. I started looking at purchasing a component to help me out, but it turns out the .NET Framework offers all you need.

public class FtpStatus
{
    public FtpStatus()
    {
        Succes = true;
    }
 
    public bool Succes { get; set; }
    public string Message { get; set; }
}
 
/// <summary>
/// Upload a file using FTP and SSL.
/// </summary>
/// <param name="host">Full name without the 's', e.g.  ftp://secure.develop-one.com</param>
/// <param name="filename">Filename including server path, e.g.  /Upload/test.txt</param>
/// <param name="file"></param>
public FtpStatus UploadFile( string host, bool useSsl, string username, string password, string filename, byte[] file )
{
    FtpStatus result = new FtpStatus();
 
    string target = host + filename;
    FtpWebRequest request = (FtpWebRequest) FtpWebRequest.Create( target );
    request.EnableSsl = useSsl;
    request.KeepAlive = true;
    request.UseBinary = true;
    request.UsePassive = true;
    request.Method = WebRequestMethods.Ftp.UploadFile;
 
    request.Credentials = new NetworkCredential( username, password );
 
    try
    {
        using ( Stream stream = request.GetRequestStream() )
        {
            stream.Write( file, 0, file.Length );
            stream.Close();
        }
    }
    catch ( System.Net.WebException exception )
    {
        result.Succes = false;
        string message = ( (System.Net.FtpWebResponse) ( exception.Response ) ).StatusDescription.Replace( "\r\n", "" );
        if ( message.IndexOf( ":" ) > 0 )
        {
            message = message.Substring( message.IndexOf( ":" ) + 2 );
        }
        result.Message = message;
    }
    return result;
}
#    Comments [0] |