FtpWebRequest Clase

Definición

Implementa un cliente de protocolo de transferencia de archivos (FTP).

public ref class FtpWebRequest sealed : System::Net::WebRequest
public sealed class FtpWebRequest : System.Net.WebRequest
type FtpWebRequest = class
    inherit WebRequest
Public NotInheritable Class FtpWebRequest
Inherits WebRequest
Herencia
FtpWebRequest
Herencia

Ejemplos

En el ejemplo de código siguiente se muestra cómo eliminar un archivo de un servidor FTP.

static bool DeleteFileOnServer( Uri^ serverUri )
{
   // The serverUri parameter should use the ftp:// scheme.
   // It contains the name of the server file that is to be deleted.
   // Example: ftp://contoso.com/someFile.txt.
   // 
   if ( serverUri->Scheme != Uri::UriSchemeFtp )
   {
      return false;
   }

   // Get the object used to communicate with the server.
   FtpWebRequest^ request = dynamic_cast<FtpWebRequest^>(WebRequest::Create( serverUri ));
   request->Method = WebRequestMethods::Ftp::DeleteFile;
   FtpWebResponse^ response = dynamic_cast<FtpWebResponse^>(request->GetResponse());
   Console::WriteLine( "Delete status: {0}", response->StatusDescription );
   response->Close();
   return true;
}
public static bool DeleteFileOnServer(Uri serverUri)
{
    // The serverUri parameter should use the ftp:// scheme.
    // It contains the name of the server file that is to be deleted.
    // Example: ftp://contoso.com/someFile.txt.
    //

    if (serverUri.Scheme != Uri.UriSchemeFtp)
    {
        return false;
    }
    // Get the object used to communicate with the server.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
    request.Method = WebRequestMethods.Ftp.DeleteFile;

    FtpWebResponse response = (FtpWebResponse) request.GetResponse();
    Console.WriteLine("Delete status: {0}",response.StatusDescription);
    response.Close();
    return true;
}

En el ejemplo de código siguiente se muestra cómo descargar un archivo de un servidor FTP mediante la WebClient clase .

static bool DisplayFileFromServer( Uri^ serverUri )
{
   // The serverUri parameter should start with the ftp:// scheme.
   if ( serverUri->Scheme != Uri::UriSchemeFtp )
   {
      return false;
   }

   // Get the object used to communicate with the server.
   WebClient^ request = gcnew WebClient;

   // This example assumes the FTP site uses anonymous logon.
   request->Credentials = gcnew NetworkCredential( "anonymous","janeDoe@contoso.com" );
   try
   {
      array<Byte>^newFileData = request->DownloadData( serverUri->ToString() );
      String^ fileString = System::Text::Encoding::UTF8->GetString( newFileData );
      Console::WriteLine( fileString );
   }
   catch ( WebException^ e ) 
   {
      Console::WriteLine( e );
   }

   return true;
}
public static bool DisplayFileFromServer(Uri serverUri)
{
    // The serverUri parameter should start with the ftp:// scheme.
    if (serverUri.Scheme != Uri.UriSchemeFtp)
    {
        return false;
    }
    // Get the object used to communicate with the server.
    WebClient request = new WebClient();

    // This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
    try
    {
        byte [] newFileData = request.DownloadData (serverUri.ToString());
        string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
        Console.WriteLine(fileString);
    }
    catch (WebException e)
    {
        Console.WriteLine(e.ToString());
    }
    return true;
}

En el ejemplo de código siguiente se muestra el uso de operaciones asincrónicas para cargar un archivo en un servidor FTP.

#using <System.dll>

using namespace System;
using namespace System::Net;
using namespace System::Threading;
using namespace System::IO;

public ref class FtpState
{
private:
   ManualResetEvent^ wait;
   FtpWebRequest^ request;
   String^ fileName;
   Exception^ operationException;
   String^ status;

public:
   FtpState()
   {
      wait = gcnew ManualResetEvent( false );
   }

   property ManualResetEvent^ OperationComplete 
   {
      ManualResetEvent^ get()
      {
         return wait;
      }

   }

   property FtpWebRequest^ Request 
   {
      FtpWebRequest^ get()
      {
         return request;
      }

      void set( FtpWebRequest^ value )
      {
         request = value;
      }

   }

   property String^ FileName 
   {
      String^ get()
      {
         return fileName;
      }

      void set( String^ value )
      {
         fileName = value;
      }

   }

   property Exception^ OperationException 
   {
      Exception^ get()
      {
         return operationException;
      }

      void set( Exception^ value )
      {
         operationException = value;
      }

   }

   property String^ StatusDescription 
   {
      String^ get()
      {
         return status;
      }

      void set( String^ value )
      {
         status = value;
      }

   }
};

public ref class AsynchronousFtpUpLoader
{
public:

   // Command line arguments are two strings:
   // 1. The url that is the name of the file being uploaded to the server.
   // 2. The name of the file on the local machine.
   //
   static void Main()
   {
      array<String^>^args = Environment::GetCommandLineArgs();

      // Create a Uri instance with the specified URI string.
      // If the URI is not correctly formed, the Uri constructor
      // will throw an exception.
      ManualResetEvent^ waitObject;
      Uri^ target = gcnew Uri( args[ 1 ] );
      String^ fileName = args[ 2 ];
      FtpState^ state = gcnew FtpState;
      FtpWebRequest ^ request = dynamic_cast<FtpWebRequest^>(WebRequest::Create( target ));
      request->Method = WebRequestMethods::Ftp::UploadFile;

      // This example uses anonymous logon.
      // The request is anonymous by default; the credential does not have to be specified. 
      // The example specifies the credential only to
      // control how actions are logged on the server.
      request->Credentials = gcnew NetworkCredential( "anonymous","janeDoe@contoso.com" );

      // Store the request in the object that we pass into the
      // asynchronous operations.
      state->Request = request;
      state->FileName = fileName;

      // Get the event to wait on.
      waitObject = state->OperationComplete;

      // Asynchronously get the stream for the file contents.
      request->BeginGetRequestStream( gcnew AsyncCallback( EndGetStreamCallback ), state );

      // Block the current thread until all operations are complete.
      waitObject->WaitOne();

      // The operations either completed or threw an exception.
      if ( state->OperationException != nullptr )
      {
         throw state->OperationException;
      }
      else
      {
         Console::WriteLine( "The operation completed - {0}", state->StatusDescription );
      }
   }

private:
   static void EndGetStreamCallback( IAsyncResult^ ar )
   {
      FtpState^ state = dynamic_cast<FtpState^>(ar->AsyncState);
      Stream^ requestStream = nullptr;

      // End the asynchronous call to get the request stream.
      try
      {
         requestStream = state->Request->EndGetRequestStream( ar );

         // Copy the file contents to the request stream.
         const int bufferLength = 2048;
         array<Byte>^buffer = gcnew array<Byte>(bufferLength);
         int count = 0;
         int readBytes = 0;
         FileStream^ stream = File::OpenRead( state->FileName );
         do
         {
            readBytes = stream->Read( buffer, 0, bufferLength );
            requestStream->Write( buffer, 0, bufferLength );
            count += readBytes;
         }
         while ( readBytes != 0 );
         Console::WriteLine( "Writing {0} bytes to the stream.", count );

         // IMPORTANT: Close the request stream before sending the request.
         requestStream->Close();

         // Asynchronously get the response to the upload request.
         state->Request->BeginGetResponse( gcnew AsyncCallback( EndGetResponseCallback ), state );
      }
      // Return exceptions to the main application thread.
      catch ( Exception^ e ) 
      {
         Console::WriteLine( "Could not get the request stream." );
         state->OperationException = e;
         state->OperationComplete->Set();
         return;
      }
   }

   // The EndGetResponseCallback method  
   // completes a call to BeginGetResponse.
   static void EndGetResponseCallback( IAsyncResult^ ar )
   {
      FtpState^ state = dynamic_cast<FtpState^>(ar->AsyncState);
      FtpWebResponse ^ response = nullptr;
      try
      {
         response = dynamic_cast<FtpWebResponse^>(state->Request->EndGetResponse( ar ));
         response->Close();
         state->StatusDescription = response->StatusDescription;

         // Signal the main application thread that 
         // the operation is complete.
         state->OperationComplete->Set();
      }
      // Return exceptions to the main application thread.
      catch ( Exception^ e ) 
      {
         Console::WriteLine( "Error getting response." );
         state->OperationException = e;
         state->OperationComplete->Set();
      }
   }
};

int main()
{
   AsynchronousFtpUpLoader::Main();
}
using System;
using System.Net;
using System.Threading;

using System.IO;
namespace Examples.System.Net
{
    public class FtpState
    {
        private ManualResetEvent wait;
        private FtpWebRequest request;
        private string fileName;
        private Exception operationException = null;
        string status;

        public FtpState()
        {
            wait = new ManualResetEvent(false);
        }

        public ManualResetEvent OperationComplete
        {
            get {return wait;}
        }

        public FtpWebRequest Request
        {
            get {return request;}
            set {request = value;}
        }

        public string FileName
        {
            get {return fileName;}
            set {fileName = value;}
        }
        public Exception OperationException
        {
            get {return operationException;}
            set {operationException = value;}
        }
        public string StatusDescription
        {
            get {return status;}
            set {status = value;}
        }
    }
    public class AsynchronousFtpUpLoader
    {
        // Command line arguments are two strings:
        // 1. The url that is the name of the file being uploaded to the server.
        // 2. The name of the file on the local machine.
        //
        public static void Main(string[] args)
        {
            // Create a Uri instance with the specified URI string.
            // If the URI is not correctly formed, the Uri constructor
            // will throw an exception.
            ManualResetEvent waitObject;

            Uri target = new Uri (args[0]);
            string fileName = args[1];
            FtpState state = new FtpState();
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example uses anonymous logon.
            // The request is anonymous by default; the credential does not have to be specified.
            // The example specifies the credential only to
            // control how actions are logged on the server.

            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

            // Store the request in the object that we pass into the
            // asynchronous operations.
            state.Request = request;
            state.FileName = fileName;

            // Get the event to wait on.
            waitObject = state.OperationComplete;

            // Asynchronously get the stream for the file contents.
            request.BeginGetRequestStream(
                new AsyncCallback (EndGetStreamCallback),
                state
            );

            // Block the current thread until all operations are complete.
            waitObject.WaitOne();

            // The operations either completed or threw an exception.
            if (state.OperationException != null)
            {
                throw state.OperationException;
            }
            else
            {
                Console.WriteLine("The operation completed - {0}", state.StatusDescription);
            }
        }
        private static void EndGetStreamCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;

            Stream requestStream = null;
            // End the asynchronous call to get the request stream.
            try
            {
                requestStream = state.Request.EndGetRequestStream(ar);
                // Copy the file contents to the request stream.
                const int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];
                int count = 0;
                int readBytes = 0;
                FileStream stream = File.OpenRead(state.FileName);
                do
                {
                    readBytes = stream.Read(buffer, 0, bufferLength);
                    requestStream.Write(buffer, 0, readBytes);
                    count += readBytes;
                }
                while (readBytes != 0);
                Console.WriteLine ("Writing {0} bytes to the stream.", count);
                // IMPORTANT: Close the request stream before sending the request.
                requestStream.Close();
                // Asynchronously get the response to the upload request.
                state.Request.BeginGetResponse(
                    new AsyncCallback (EndGetResponseCallback),
                    state
                );
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine("Could not get the request stream.");
                state.OperationException = e;
                state.OperationComplete.Set();
                return;
            }
        }

        // The EndGetResponseCallback method
        // completes a call to BeginGetResponse.
        private static void EndGetResponseCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;
            FtpWebResponse response = null;
            try
            {
                response = (FtpWebResponse) state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;
                // Signal the main application thread that
                // the operation is complete.
                state.OperationComplete.Set();
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine ("Error getting response.");
                state.OperationException = e;
                state.OperationComplete.Set();
            }
        }
    }
}

Comentarios

Importante

No se recomienda usar la FtpWebRequest clase para el nuevo desarrollo. Para obtener más información y alternativas a FtpWebRequest, consulte WebRequest no se debe usar en GitHub.

Para obtener una instancia de FtpWebRequest, use el Create método . También puede usar la WebClient clase para cargar y descargar información desde un servidor FTP. Con cualquiera de estos enfoques, cuando se especifica un recurso de red que usa el esquema FTP (por ejemplo, "ftp://contoso.com"), la FtpWebRequest clase proporciona la capacidad de interactuar mediante programación con servidores FTP.

El URI puede ser relativo o absoluto. Si el URI tiene el formato "ftp://contoso.com/%2fpath" (%2f es un escape '/'), el URI es absoluto y el directorio actual es /path. Sin embargo, si el URI tiene el formato "ftp://contoso.com/path", primero .NET Framework inicia sesión en el servidor FTP (con el nombre de usuario y la contraseña establecidos por la Credentials propiedad ), el directorio actual se establece <UserLoginDirectory>/pathen .

Debe tener un nombre de usuario y una contraseña válidos para el servidor o el servidor debe permitir el inicio de sesión anónimo. Puede especificar las credenciales usadas para conectarse al servidor estableciendo la Credentials propiedad o puede incluirlas en la UserInfo parte del URI pasado al Create método . Si incluye UserInfo información en el URI, la Credentials propiedad se establece en una nueva credencial de red con el nombre de usuario y la información de contraseña especificados.

Precaución

A menos que la EnableSsl propiedad sea true, todos los datos y comandos, incluidos el nombre de usuario y la información de contraseña, se envían al servidor en texto no cifrado. Cualquier persona que supervise el tráfico de red puede ver sus credenciales y usarlas para conectarse al servidor. Si se conecta a un servidor FTP que requiere credenciales y admite Capa de sockets seguros (SSL), debe establecer en EnableSsltrue.

Debe tener WebPermission acceso al recurso FTP; de lo contrario, se produce una SecurityException excepción.

Especifique el comando FTP que se va a enviar al servidor estableciendo la Method propiedad en un valor definido en la WebRequestMethods.Ftp estructura . Para transmitir datos de texto, cambie la UseBinary propiedad de su valor predeterminado (true) a false. Para más información y restricciones, consulte Method.

Cuando se usa un FtpWebRequest objeto para cargar un archivo en un servidor, debe escribir el contenido del archivo en el flujo de solicitud obtenido llamando al GetRequestStream método o a sus homólogos asincrónicos, los BeginGetRequestStream métodos y EndGetRequestStream . Debe escribir en la secuencia y cerrar la secuencia antes de enviar la solicitud.

Las solicitudes se envían al servidor llamando al GetResponse método o a sus homólogos asincrónicos, los BeginGetResponse métodos y EndGetResponse . Cuando se completa la operación solicitada, se devuelve un FtpWebResponse objeto . El FtpWebResponse objeto proporciona el estado de la operación y los datos descargados del servidor.

Puede establecer un valor de tiempo de espera para leer o escribir en el servidor mediante la ReadWriteTimeout propiedad . Si se supera el período de tiempo de espera, el método de llamada produce un WebException con WebExceptionStatus establecido en Timeout.

Al descargar un archivo desde un servidor FTP, si el comando se realizó correctamente, el contenido del archivo solicitado está disponible en la secuencia del objeto de respuesta. Para acceder a esta secuencia, llame al GetResponseStream método . Para obtener más información, vea FtpWebResponse.

Si se establece la Proxy propiedad, ya sea directamente o en un archivo de configuración, las comunicaciones con el servidor FTP se realizan a través del proxy especificado. Si el proxy especificado es un proxy HTTP, solo se admiten los DownloadFilecomandos , ListDirectoryy ListDirectoryDetails .

Solo se almacena en caché el contenido binario descargado; es decir, el contenido recibido mediante el DownloadFile comando con la UseBinary propiedad establecida en true.

Si es posible, se reutilizan varias FtpWebRequestconexiones existentes.

Para obtener más información sobre el protocolo FTP, vea RFC 959: Protocolo de transferencia de archivos.

Propiedades

AuthenticationLevel

Obtiene o establece valores que indican el nivel de autenticación y de suplantación utilizados para esta solicitud.

(Heredado de WebRequest)
CachePolicy

Obtiene o establece la directiva de caché para esta solicitud.

(Heredado de WebRequest)
ClientCertificates

Obtiene o establece los certificados usados para establecer una conexión cifrada con el servidor FTP.

ConnectionGroupName

Obtiene o establece el nombre del grupo de conexiones que contiene el punto de servicio usado para enviar la solicitud actual.

ContentLength

Obtiene o establece un valor omitido por la clase FtpWebRequest.

ContentOffset

Obtiene o establece un desplazamiento de bytes en el archivo que descargará esta solicitud.

ContentType

Siempre inicia una NotSupportedException.

CreatorInstance
Obsoletos.

Cuando se reemplaza en una clase descendiente, obtiene el objeto generador derivado de la clase IWebRequestCreate usada para crear la instancia de WebRequest para efectuar la solicitud al URI especificado.

(Heredado de WebRequest)
Credentials

Obtiene o establece las credenciales usadas para la comunicación con el servidor FTP.

DefaultCachePolicy

Define la directiva de caché predeterminada para todas las solicitudes FTP.

EnableSsl

Obtiene o establece un valor Boolean que especifica que se debe usar una conexión SSL.

Headers

Obtiene un objeto WebHeaderCollection vacío.

ImpersonationLevel

Obtiene o establece el nivel de suplantación para la solicitud actual.

(Heredado de WebRequest)
KeepAlive

Obtiene o establece un valor Boolean que especifica si la conexión de control al servidor FTP se cierra después de que la solicitud se complete.

Method

Obtiene o establece el comando que se envía al servidor FTP.

PreAuthenticate

Siempre inicia una NotSupportedException.

Proxy

Obtiene o establece el servidor proxy que se usa para la comunicación con el servidor FTP.

ReadWriteTimeout

Obtiene o establece un tiempo de espera para una operación de lectura o escritura en una secuencia.

RenameTo

Obtiene o establece el nuevo nombre de un archivo al que se cambia el nombre.

RequestUri

Obtiene el identificador URI solicitado por esta instancia.

ServicePoint

Obtiene el objeto ServicePoint usado para conectarse al servidor FTP.

Timeout

Obtiene o establece el número de milisegundos de espera para una solicitud.

UseBinary

Obtiene o establece un valor Boolean que especifica el tipo de datos para las transferencias de archivos.

UseDefaultCredentials

Siempre inicia una NotSupportedException.

UsePassive

Obtiene o establece el comportamiento del proceso de transferencia de datos de una aplicación cliente.

Métodos

Abort()

Finaliza una operación FTP asincrónica.

BeginGetRequestStream(AsyncCallback, Object)

Empieza a abrir para escritura de forma asincrónica la secuencia de contenido de una solicitud.

BeginGetResponse(AsyncCallback, Object)

Empieza enviando una solicitud y recibiendo de forma asincrónica una respuesta de un servidor FTP.

CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.

(Heredado de MarshalByRefObject)
EndGetRequestStream(IAsyncResult)

Finaliza una operación asincrónica pendiente iniciada con BeginGetRequestStream(AsyncCallback, Object).

EndGetResponse(IAsyncResult)

Finaliza una operación asincrónica pendiente iniciada con BeginGetResponse(AsyncCallback, Object).

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetLifetimeService()
Obsoletos.

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.

(Heredado de MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)
Obsoletos.

Llena SerializationInfo con los datos necesarios para serializar el objeto de destino.

(Heredado de WebRequest)
GetRequestStream()

Recupera la secuencia usada para cargar datos a un servidor FTP.

GetRequestStreamAsync()

Cuando se invalida en una clase descendiente, devuelve un objeto Stream para escribir datos en el recurso de Internet como una operación asincrónica.

(Heredado de WebRequest)
GetResponse()

Devuelve la respuesta del servidor FTP.

GetResponseAsync()

Cuando se invalida en una clase descendiente, devuelve una respuesta a una solicitud de Internet como una operación asincrónica.

(Heredado de WebRequest)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
InitializeLifetimeService()
Obsoletos.

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.

(Heredado de MarshalByRefObject)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.

(Heredado de MarshalByRefObject)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
Obsoletos.

Cuando se reemplaza en una clase descendiente, rellena una instancia de SerializationInfo con los datos necesarios para serializar el objeto WebRequest.

(Heredado de WebRequest)

Se aplica a

Consulte también