Pregunta

El siguiente código se pretende recuperar un archivo a través de FTP. Sin embargo, estoy recibiendo un error con él.

serverPath = "ftp://x.x.x.x/tmp/myfile.txt";

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);

request.KeepAlive = true;
request.UsePassive = true;
request.UseBinary = true;

request.Method = WebRequestMethods.Ftp.DownloadFile;                
request.Credentials = new NetworkCredential(username, password);

// Read the file from the server & write to destination                
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) // Error here
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))            
using (StreamWriter destination = new StreamWriter(destinationFile))
{
    destination.Write(reader.ReadToEnd());
    destination.Flush();
}

El error es:

El servidor remoto devolvió un error: (550) del archivo no disponible (por ejemplo, archivo no encontrado, sin acceso)

El archivo sin duda existe en la máquina remota y yo soy capaz de realizar esta ftp manualmente (es decir, no tengo permisos). ¿Puede alguien decirme por qué Podría estar recibiendo este error?

¿Fue útil?

Solución

Este párrafo de la fuerza href="http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx" rel="noreferrer"> FptWebRequest referencia de clase ser de interés para usted:

El URI puede ser relativa o absoluta. Si el URI es de la forma " ftp://contoso.com/%2fpath " (% 2f es Una fugaron '/'), entonces el URI es absoluta, y el directorio actual es /camino. Si, sin embargo, el URI es del formar " ftp://contoso.com/path ", primera .NET Framework inicia sesión en el FTP servidor (utilizando el nombre de usuario y contraseña establecida por las credenciales propiedad), entonces el directorio actual se establece en ruta /.

Otros consejos

Sé que esto es una entrada antigua, pero añado aquí para referencia futura. Aquí es una solución que he encontrado:

    private void DownloadFileFTP()
    {
        string inputfilepath = @"C:\Temp\FileName.exe";
        string ftphost = "xxx.xx.x.xxx";
        string ftpfilepath = "/Updater/Dir1/FileName.exe";

        string ftpfullpath = "ftp://" + ftphost + ftpfilepath;

        using (WebClient request = new WebClient())
        {
            request.Credentials = new NetworkCredential("UserName", "P@55w0rd");
            byte[] fileData = request.DownloadData(ftpfullpath);

            using (FileStream file = File.Create(inputfilepath))
            {
                file.Write(fileData, 0, fileData.Length);
                file.Close();
            }
            MessageBox.Show("Download Complete");
        }
    }

actualizados basados ??en un excelente sugerencia de Ilya Kogan

La manera más fácil

La forma más trivial para descargar un archivo binario desde un servidor FTP utilizando el framework .NET está usando WebClient.DownloadFile :

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

Opciones avanzadas

FtpWebRequest , sólo si es necesario un mayor control, que no ofrece WebClient (como TLS / SSL cifrado , monitoreo del progreso, etc.). forma fácil es simplemente copiar una secuencia de respuesta FTP para FileStream usando Stream.CopyTo :

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    ftpStream.CopyTo(fileStream);
}

Seguimiento de los progresos

Si usted necesita para controlar un progreso de la descarga, usted tiene que copiar el contenido de trozos de sí mismo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

Para el Progreso (interfaz gráfica de usuario de Windows Forms ProgressBar), véase:
FtpWebRequest FTP con ProgressBar


Descarga de carpeta

Si desea descargar todos los archivos de una carpeta remota, ver
C # Descargar todos los archivos y subdirectorios a través de FTP .

Yo tenía el mismo problema!

Mi solución fue insertar la carpeta public_html en la URL de descarga.

ubicación del archivo real en el servidor:

myhost.com/public_html/myimages/image.png

Web URL:

www.myhost.com/myimages/image.png

    private static DataTable ReadFTP_CSV()
    {
        String ftpserver = "ftp://servername/ImportData/xxxx.csv";
        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));

        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

        Stream responseStream = response.GetResponseStream();

        // use the stream to read file from FTP 
        StreamReader sr = new StreamReader(responseStream);
        DataTable dt_csvFile = new DataTable();

        #region Code
        //Add Code Here To Loop txt or CSV file
        #endregion

        return dt_csvFile;

    }

espero que le puede ayudar.

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);

Después de esto se puede utilizar el siguiente línea a un error evitar .. (acceso denegado etc.)

request.Proxy = null;
   public void download(string remoteFile, string localFile)
    {
       private string host = "yourhost";
       private string user = "username";
       private string pass = "passwd";
       private FtpWebRequest ftpRequest = null;
       private FtpWebResponse ftpResponse = null;
       private Stream ftpStream = null;
       private int bufferSize = 2048;

        try
        {
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);

            ftpRequest.Credentials = new NetworkCredential(user, pass);

            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;

            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            ftpStream = ftpResponse.GetResponseStream();

            FileStream localFileStream = new FileStream(localFile, FileMode.Create);

            byte[] byteBuffer = new byte[bufferSize];
            int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);

            try
            {
                while (bytesRead > 0)
                {
                    localFileStream.Write(byteBuffer, 0, bytesRead);
                    bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                }
            }

            catch (Exception) {  }

            localFileStream.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }

        catch (Exception) {  }
        return;
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top