MVC | Upload file from server to FTP
Upload file from server to another Server using FTP detail in mvc C#.
Code:
public static class FileUpload { public static string FTPUpload(HttpPostedFileBase file) { try { string _FileName = Path.GetFileName(file.FileName); string _path = Path.Combine(Server.MapPath("~/Temp"), _FileName); file.SaveAs(_path); string FtpFilePath = ConfigurationManager.AppSettings["ftpFolder"].ToString() + _FileName; string ftpurl = ConfigurationManager.AppSettings["ftpName"].ToString() + FtpFilePath; string ftpusername = ConfigurationManager.AppSettings["ftpUsername"].ToString(); string ftppassword = ConfigurationManager.AppSettings["ftpPassword"].ToString(); string filename = Path.GetFileName(_path); string ftpfullpath = ftpurl; FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new NetworkCredential(ftpusername, ftppassword); ftp.KeepAlive = true; ftp.UseBinary = true; ftp.Method = WebRequestMethods.Ftp.UploadFile; FileStream fs = System.IO.File.OpenRead(_path); 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(); } catch (Exception ex) { throw ex; } return "success"; } }
Configuration settings:
<appSettings> <add key="ftpName" value="ftp://testftp/"></add> <add key="ftpUsername" value="username"></add> <add key="ftpPassword" value="password"></add> <add key="ftpFolder" value="folderpath"></add> </appSettings>
No comments:
Post a Comment