0

I am trying to upload a file via FTP

The provided format of the path is not supported

Code:

[HttpPost]
    public ActionResult Guardar_registro(Models.CascadingModelLevantamiento model, HttpPostedFileBase file)
    {
      var NombreArchivo = Path.GetFileName(file.FileName);
      string name = Path.Combine("" + NombreArchivo);
      string ftpfullpath = Path.Combine(@"ftp://xxx.xxx.xx.xx:xx" + @"/test/" + name);
      FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
      ftp.Credentials = new NetworkCredential("xxx@xx.com", "xxx");
      ftp.KeepAlive = true;
      ftp.UseBinary = true;
      ftp.Method = WebRequestMethods.Ftp.UploadFile;
      FileStream fs = System.IO.File.OpenRead(ftpfullpath);
      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();
 }
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
Morquecho
  • 37
  • 1
  • 8
  • `System.IO.File.OpenRead(ftpfullpath);` will attempt to read a path on the local machine at the specified path of the FTP server. – Kieran Devlin Oct 11 '19 at 15:55
  • I already do it in `FileStream fs = System.IO.File.OpenRead (ftpfullpath);` ...... the file comes `HttpPostedFileBase` since I use MVC – Morquecho Oct 11 '19 at 15:58
  • Unrelated, but important: you need to [dispose](https://learn.microsoft.com/en-us/dotnet/api/system.idisposable.dispose?view=netframework-4.8) the streams you create and organize your code (instead of putting all in one place) :) – Yeldar Kurmangaliyev Oct 11 '19 at 16:00

2 Answers2

1

Do not re-invent the wheel, try something like this:

using (var client = new WebClient())
{
    client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
    client.UploadFile("ftp://host/path.zip", WebRequestMethods.Ftp.UploadFile, localFile);
}

Resource link: WebClient

0

What goes to File.OpenRead must be a valid local (Windows) path. Not FTP URL.

Something like

string filename = System.IO.Path.Combine(@"C:\local\path", NombreArchivo);
FileStream fs = System.IO.File.OpenRead(filename);

Though as correctly commented in the other answer, way easier is to use WebClient.UploadFile.

See Upload file and download file from FTP.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992