Operaciones FTP en C# con FtpWebRequest

Para interactuar con servidores FTP en C#, la clase FtpWebRequest del espacio de nombres System.Net es fundamental. El proceso general implica varios pasos:

  1. Crear una instancia de FtpWebRequest apuntando a la URI del servidor FTP.
  2. Definir la operación a realizar (subir, descargar, listar, etc.) mediante el método Method.
  3. Configurar propiedades importantes como credenciales, modo de transferencia (binario/ASCII), y uso de SSL.
  4. Establecer las credenciales de autenticación (usuario y contraseña).
  5. Ejecutar la solicitud y procesar la respuesta.

Los detalles de configuración del servidor FTP se manejan a través de las propiedades de FtpWebRequest:

  • Credentials: Permite especificar el nombre de usuario y la contraseña para la autenticación.
  • KeepAlive: Controla si la conexión debe permanecer abierta después de completar una operación (por defecto es true).
  • UseBinary: Determina el modo de transferencia. true para modo binario (recomendado para la mayoría de los archivos), false para modo ASCII (apropiado para archivos de texto plano que se pueden editar con un editor de texto simple).
  • UsePassive: Define si se utiliza el modo pasivo (true) o activo (false). El modo pasivo es generalmente preferible debido a las restricciones de firewall que pueden afectar al modo activo.
  • ContentLength: Útil para que el servidor sepa el tamaño del archivo antes de la transferencia (principalmente para cargas), aunque FtpWebRequest lo ignora en el lado del cliente.
  • Method: Especifica la operación FTP a ejecutar. Los comandos disponibles se encuentran en la enumeración WebRequestMethods.Ftp (ej. UploadFile, DownloadFile, ListDirectory).

Ejemplo de Carga de Archivos

El siguiente código demuestra cómo subir un archivo a un servidor FTP:


private void UploadFileToServer(string localFilePath)
{
 FileInfo fileInfo = new FileInfo(localFilePath);
 string ftpPath = $"ftp://{ftpServerAddress}/{fileInfo.Name}";
 FtpWebRequest ftpRequest;

 try
 {
  ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
  ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
  ftpRequest.KeepAlive = false;
  ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
  ftpRequest.UseBinary = true;
  ftpRequest.ContentLength = fileInfo.Length;

  int bufferSize = 2048;
  byte[] buffer = new byte[bufferSize];

  using (FileStream fileStream = fileInfo.OpenRead())
  using (Stream requestStream = ftpRequest.GetRequestStream())
  {
   int bytesRead;
   while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
   {
    requestStream.Write(buffer, 0, bytesRead);
   }
  }
  MessageBox.Show("Archivo subido exitosamente.", "Éxito", MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
 catch (Exception ex)
 {
  MessageBox.Show($"Error al subir archivo: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
 }
}

Este fragmento configura la solicitud FTP, establece las credenciales y el método de carga. Luego, lee el archivo local en bloques y los escribe en el flujo de solicitud del servidor FTP.

Ejemplo de Descarga de Archivos

Para descargar un archivo desde un sevridor FTP, el proceso es similar, pero se requiere obtener un flujo de respuesta:


private void DownloadFileFromServer(string remoteFileName, string localDirectoryPath)
{
 string localFilePath = Path.Combine(localDirectoryPath, remoteFileName);
 FtpWebRequest ftpRequest;

 try
 {
  string ftpPath = $"ftp://{ftpServerAddress}/{remoteFileName}";
  ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
  ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
  ftpRequest.UseBinary = true;
  ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);

  using (FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse())
  using (Stream ftpStream = response.GetResponseStream())
  using (FileStream outputStream = new FileStream(localFilePath, FileMode.Create))
  {
   int bufferSize = 2048;
   byte[] buffer = new byte[bufferSize];
   int bytesRead;
   while ((bytesRead = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
   {
    outputStream.Write(buffer, 0, bytesRead);
   }
  }
  MessageBox.Show($"Archivo '{remoteFileName}' descargado exitosamente.", "Éxito", MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
 catch (Exception ex)
 {
  MessageBox.Show($"Error al descargar archivo: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
 }
}

Aquí, la solicitud se configura para descargar, se obtienen los datos del servidor a través de GetResponseStream() y se guardan en un archivo local.

Ejemplo de Listado de Directorios

Para obtener una lista de archivos y directorios en una ubicación FTP:


public string[] GetFileListFromDirectory(string directoryPath = "")
{
 string ftpPath = $"ftp://{ftpServerAddress}/{directoryPath}";
 FtpWebRequest ftpRequest;
 StringBuilder fileListBuilder = new StringBuilder();

 try
 {
  ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
  ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
  ftpRequest.UseBinary = true;
  ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);

  using (WebResponse response = ftpRequest.GetResponse())
  using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8)) // Usar UTF8 para nombres de archivo comunes
  {
   string line;
   while ((line = reader.ReadLine()) != null)
   {
    fileListBuilder.AppendLine(line);
   }
  }

  if (fileListBuilder.Length > 0)
  {
   // Eliminar el último salto de línea si existe
   if (fileListBuilder[fileListBuilder.Length - 1] == '\n')
   {
    fileListBuilder.Remove(fileListBuilder.Length - 1, 1);
   }
   return fileListBuilder.ToString().Split('\n');
  }
  else
  {
   return new string[0]; // Retorna un array vacío si no hay archivos
  }
 }
 catch (Exception ex)
 {
  MessageBox.Show($"Error al obtener lista de archivos: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  return null;
 }
}

Este método utiliza WebRequestMethods.Ftp.ListDirectory para obtener la lista y la procesa línea por línea. Se recomienda el uso de Encoding.UTF8 para asegurar la corercta interpretación de nombres de archivo con caracteres especiales.

Consideraciones de Seguridad y Operaciones Adicionales

Es crucial tener en cuenta la seguridad:

  • EnableSsl: Si el servidor FTP soporta SSL/TLS, habilite esta propiedad (true) para cifrar la comunicación, protegiendo credenciales y datos. De lo contrario, la información se transmite en texto plano.
  • SecurityException: Se lanzará si no se tienen los permisos necesarios para acceder al servidor FTP.

Para operaciones como renombrar, eliminar, crear directorios o listar detalles de archivos, se utilizan métodos correspondientes en WebRequestMethods.Ftp, similar a los ejemplos anteriores. Por ejemplo, para renombrar, se usa WebRequestMethods.Ftp.Rename y se especifica el nuevo nombre en la propiedad RenameTo del objeto FtpWebRequest.

El manejo de errores es esencial. Siempre envuelva las operaciones FTP en bloques try-catch para gestionar excepciones como problemas de red, permisos incorrectos o errores del servidor.

Un enfoque más organizado implica encapsular estas operaciones dentro de una clase de utilidad, como se sugiere en el código de ejemplo original, lo que mejora la reutilización y la matnenibilidad del código.


using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

public class FtpClientHelper
{
 private readonly string _ftpServerIp;
 private readonly string _ftpUserId;
 private readonly string _ftpPassword;

 public FtpClientHelper(string serverIp, string userId, string password)
 {
  _ftpServerIp = serverIp;
  _ftpUserId = userId;
  _ftpPassword = password;
 }

 public bool UploadFile(string localFilePath, string remoteDirectory = "", string newRemoteFileName = "")
 {
  FileInfo fileInfo = new FileInfo(localFilePath);
  string remoteFileName = string.IsNullOrEmpty(newRemoteFileName) ? fileInfo.Name : newRemoteFileName;
  string ftpPath = $"ftp://{_ftpServerIp}/{remoteDirectory.Replace("\\", "/")}/{remoteFileName}";

  try
  {
   FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
   request.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
   request.Method = WebRequestMethods.Ftp.UploadFile;
   request.UseBinary = true;
   request.ContentLength = fileInfo.Length;
   request.KeepAlive = false;

   using (FileStream fileStream = fileInfo.OpenRead())
   using (Stream requestStream = request.GetRequestStream())
   {
    fileStream.CopyTo(requestStream);
   }
   return true;
  }
  catch (Exception ex)
  {
   MessageBox.Show($"Upload Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   return false;
  }
 }

 public bool DownloadFile(string remoteFileName, string localDirectoryPath)
 {
  string localFilePath = Path.Combine(localDirectoryPath, Path.GetFileName(remoteFileName));
  string ftpPath = $"ftp://{_ftpServerIp}/{remoteFileName.Replace("\\", "/")}";

  try
  {
   FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
   request.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
   request.Method = WebRequestMethods.Ftp.DownloadFile;
   request.UseBinary = true;
   request.KeepAlive = false;

   using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
   using (Stream ftpStream = response.GetResponseStream())
   using (FileStream outputStream = new FileStream(localFilePath, FileMode.Create))
   {
    ftpStream.CopyTo(outputStream);
   }
   return true;
  }
  catch (Exception ex)
  {
   MessageBox.Show($"Download Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   return false;
  }
 }

 public string[] ListDirectory(string directoryPath = "")
 {
  string ftpPath = $"ftp://{_ftpServerIp}/{directoryPath.Replace("\\", "/")}";
  StringBuilder result = new StringBuilder();

  try
  {
   FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
   request.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
   request.Method = WebRequestMethods.Ftp.ListDirectory;
   request.UseBinary = true;
   request.KeepAlive = false;

   using (WebResponse response = request.GetResponse())
   using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
   {
    string line;
    while ((line = reader.ReadLine()) != null)
    {
     result.Append(line).Append("\n");
    }
   }

   if (result.Length > 0)
   {
    if (result[result.Length - 1] == '\n')
    {
     result.Remove(result.Length - 1, 1);
    }
    return result.ToString().Split('\n');
   }
   else
   {
    return new string[0];
   }
  }
  catch (Exception ex)
  {
   MessageBox.Show($"List Directory Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   return null;
  }
 }

 public bool CreateDirectory(string directoryName)
 {
  string ftpPath = $"ftp://{_ftpServerIp}/{directoryName.Replace("\\", "/")}";
  try
  {
   FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
   request.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
   request.Method = WebRequestMethods.Ftp.MakeDirectory;
   request.KeepAlive = false;

   using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { }
   return true;
  }
  catch (Exception ex)
  {
   MessageBox.Show($"Create Directory Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   return false;
  }
 }

 public bool DeleteFile(string remoteFileName)
 {
  string ftpPath = $"ftp://{_ftpServerIp}/{remoteFileName.Replace("\\", "/")}";
  try
  {
   FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
   request.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
   request.Method = WebRequestMethods.Ftp.DeleteFile;
   request.KeepAlive = false;

   using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { }
   return true;
  }
  catch (Exception ex)
  {
   MessageBox.Show($"Delete File Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   return false;
  }
 }

 public bool RenameFile(string currentRemoteFileName, string newRemoteFileName)
 {
  string ftpPath = $"ftp://{_ftpServerIp}/{currentRemoteFileName.Replace("\\", "/")}";
  try
  {
   FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
   request.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
   request.Method = WebRequestMethods.Ftp.Rename;
   request.RenameTo = newRemoteFileName;
   request.KeepAlive = false;

   using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { }
   return true;
  }
  catch (Exception ex)
  {
   MessageBox.Show($"Rename File Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   return false;
  }
 }
}

Etiquetas: C# FTP FtpWebRequest .NET Red de transferencia de archivos

Publicado el 11-20 04:16