Code Sample to Upload file to FTP Server

  • 1

Code Sample to Upload file to FTP Server

Visit: http://www.zonixsoft.com

check out below code to upload file to FTP Server:

 

/// <summary>
/// Code to upload file to FTP Server
/// </summary>
/// <param name=”strFilePath”>Complete physical path of the file to be uploaded</param>
/// <param name=”strFTPPath”>FTP Path</param>
/// <param name=”strUserName”>FTP User account name</param>
/// <param name=”strPassword”>FTP User password</param>
/// <returns>Boolean value based on result</returns>
private bool UploadToFTP(string strFilePath, string strFTPPath, string strUserName, string strPassword)
{
        try
        { 
                //Create a FTP Request Object and Specfiy a Complete Path
                string strFileName = strFilePath.Substring(strFilePath.LastIndexOf(“\”) + 1);
                FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create(strFTPPath + @”/” + strFileName);
                //Call A FileUpload Method of FTP Request Object
                reqObj.Method = WebRequestMethods.Ftp.UploadFile;
                //If you want to access Resourse Protected You need to give User Name and PWD
                reqObj.Credentials = new NetworkCredential(strUserName, strPassword);
                // Copy the contents of the file to the request stream.
                StreamReader sourceStream = new StreamReader(strFilePath);
                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                reqObj.ContentLength = fileContents.Length;
                Stream requestStream = reqObj.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();
                FtpWebResponse response = (FtpWebResponse)reqObj.GetResponse();
                response.Close();
        }
        catch (Exception Ex)
        {       // report error
                throw Ex;
        }
        return true;
}