Thursday, October 11, 2012

FTP File Upload using FtpWebRequest in .Net C#


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();
    }

Function can be used as 

ftpfile(@"/testfolder/testfile.xml", @"c:\testfile.xml");

No comments:

Post a Comment