If the server is going to download, implement the methods:
public ActionResult DownloadFile()
{
FtpWebRequest objFTP = null;
try
{
objFTP = FTPDetail("Arquivo.txt");
objFTP.Method = WebRequestMethods.Ftp.DownloadFile;
using (FtpWebResponse response = (FtpWebResponse)objFTP.GetResponse())
{
using (Stream ftpStream = response.GetResponseStream())
{
int contentLen;
// Não precisa usar necessariamente uma variável.
// Pode ser uma String fixa.
using (FileStream fs = new FileStream(variavelQueApontaOndeOArquivoVaiserSalvo, FileMode.OpenOrCreate))
{
byte[] buff = new byte[2048];
contentLen = ftpStream.Read(buff, 0, buff.Length);
while (contentLen != 0)
{
fs.Write(buff, 0, buff.Length);
contentLen = ftpStream.Read(buff, 0, buff.Length);
}
objFTP = null;
}
}
}
// Aqui você retorna uma View de Sucesso, seu lá como você quer fazer.
return View();
}
catch (Exception Ex)
{
if (objFTP!= null)
{
objFTP.Abort();
}
throw Ex;
}
}
private FtpWebRequest FTPDetail(string FileName)
{
string uri = "";
string serverIp = "255.255.255.1";
string Username = "usuario";
string Password = "teste123";
uri = "ftp://" + serverIp + "/root/" + FileName;
FtpWebRequest objFTP;
objFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
objFTP.Credentials = new NetworkCredential(Username, Password);
objFTP.UsePassive = true;
objFTP.KeepAlive = false;
objFTP.Proxy = null;
objFTP.UseBinary = false;
objFTP.Timeout = 90000;
return objFTP;
}
Now, if the server is going to send the files to an FTP server, implement the following:
[HttpPost]
public ActionResult Create(HttpPostedFileBase file)
{
if (file == null)
ModelState.AddModelError("Arquivo", "Arquivo deve ser válido.");
else
{
string nomeArquivo = DateTime.Now.ToLongTimeString().Replace("/", "").Replace(":", "") + file.FileName.Substring(file.FileName.LastIndexOf("."));
string path = Path.Combine(Server.MapPath("~/arquivos"),
Path.GetFileName(nomeArquivo));
file.SaveAs(path);
}
FtpWebRequest objFTP= null;
try
{
objFTP= FTPDetail(path);
objFTP.Method = WebRequestMethods.Ftp.UploadFile;
using (FileStream fs = File.OpenRead(CompletePath))
{
byte[] buff = new byte[fs.Length];
using (Stream strm = objFTP.GetRequestStream())
{
contentLen = fs.Read(buff, 0, buff.Length);
while (contentLen != 0)
{
strm.Write(buff, 0, buff.Length);
contentLen = fs.Read(buff, 0, buff.Length);
}
objFTP = null;
}
}
return true;
}
catch (Exception Ex)
{
if (objFTP!= null)
{
objFTP.Abort();
}
throw Ex;
}
return View();
}