Sunday, June 10, 2012

File Upload using FtpWebRequest in .Net C#

Namespace used:
  1. using System.Net;   
  2. using System.IO;  

Sample Code:
  1. public void ftpfile(string ftpfilepath, string inputfilepath)   
  2. {   
  3.     string ftphost = "127.0.0.1";   
  4.     //here correct hostname or IP of the ftp server to be given   
  5.   
  6.     string ftpfullpath = "ftp://" + ftphost + ftpfilepath;   
  7.     FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);   
  8.     ftp.Credentials = new NetworkCredential("userid""password");   
  9.     //userid and password for the ftp server to given   
  10.   
  11.     ftp.KeepAlive = true;   
  12.     ftp.UseBinary = true;   
  13.     ftp.Method = WebRequestMethods.Ftp.UploadFile;   
  14.     FileStream fs = File.OpenRead(inputfilepath);   
  15.     byte[] buffer = new byte[fs.Length];   
  16.     fs.Read(buffer, 0, buffer.Length);   
  17.     fs.Close();   
  18.     Stream ftpstream = ftp.GetRequestStream();   
  19.     ftpstream.Write(buffer, 0, buffer.Length);   
  20.     ftpstream.Close();   
  21. }  

Function can be used as
  1. ftpfile(@"/testfolder/testfile.xml", @"c:\testfile.xml");  

Reference :http://blog.logiclabz.com/c/ftp-file-upload-using-ftpwebrequest-in-net-c.aspx


Code to check Directory exists in ftp or not

private void btnCheck_Click(object sender, EventArgs e)
        {
            bool result = FtpDirectoryExists("ftp://micro123/First", "anonymous", "anonymous");
            MessageBox.Show("Folder"+result);
        }
        public bool FtpDirectoryExists(string directoryPath, string ftpUser, string ftpPassword)
        {
            bool IsExists = true;
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(directoryPath);
                request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
                request.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                IsExists = false;
            }
            return IsExists;
        }