FtpWebRequest Classe

Definizione

Implementa un client FTP (File Transfer Protocol).

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
Ereditarietà

Esempio

Nell'esempio di codice seguente viene illustrato l'eliminazione di un file da un server 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;
}

Nell'esempio di codice seguente viene illustrato il download di un file da un server FTP usando la WebClient classe .

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;
}

L'esempio di codice seguente illustra l'uso di operazioni asincrone per caricare un file in un server 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();
            }
        }
    }
}

Commenti

Importante

Non è consigliabile usare la FtpWebRequest classe per il nuovo sviluppo. Per altre informazioni e alternative a FtpWebRequest, vedere WebRequest non deve essere usato in GitHub.

Per ottenere un'istanza di FtpWebRequest, usare il Create metodo . È anche possibile usare la WebClient classe per caricare e scaricare informazioni da un server FTP. Usando uno di questi approcci, quando si specifica una risorsa di rete che usa lo schema FTP ,ad esempio , "ftp://contoso.com"la FtpWebRequest classe offre la possibilità di interagire a livello di codice con i server FTP.

L'URI può essere relativo o assoluto. Se l'URI è del modulo "ftp://contoso.com/%2fpath" (%2f è un oggetto escape '/'), l'URI è assoluto e la directory corrente è /path. Se, tuttavia, l'URI è del modulo "ftp://contoso.com/path", prima .NET Framework accede al server FTP (usando il nome utente e la password impostata dalla Credentials proprietà), la directory corrente è impostata su <UserLoginDirectory>/path.

È necessario disporre di un nome utente e una password validi per il server o il server deve consentire l'accesso anonimo. È possibile specificare le credenziali usate per connettersi al server impostando la Credentials proprietà oppure è possibile includerle nella UserInfo parte dell'URI passato al Create metodo. Se si includono UserInfo informazioni nell'URI, la Credentials proprietà è impostata su una nuova credenziale di rete con il nome utente e le informazioni sulla password specificate.

Attenzione

A meno che la EnableSsl proprietà non sia true, tutti i dati e i comandi, inclusi il nome utente e le informazioni sulla password, vengono inviati al server in testo chiaro. Chiunque monitora il traffico di rete può visualizzare le credenziali e usarle per connettersi al server. Se ci si connette a un server FTP che richiede credenziali e supporta Secure Sockets Layer (SSL), è necessario impostare EnableSsl su true.

È necessario WebPermission accedere alla risorsa FTP. In caso contrario, viene generata un'eccezione SecurityException .

Specificare il comando FTP da inviare al server impostando la Method proprietà su un valore definito nella WebRequestMethods.Ftp struttura. Per trasmettere dati di testo, modificare la UseBinary proprietà dal valore predefinito (true) a false. Per informazioni dettagliate e restrizioni, vedere Method.

Quando si usa un oggetto per caricare un FtpWebRequest file in un server, è necessario scrivere il contenuto del file nel flusso di richiesta ottenuto chiamando il GetRequestStream metodo o le relative controparti asincrone, i BeginGetRequestStream metodi e EndGetRequestStream . È necessario scrivere nel flusso e chiudere il flusso prima di inviare la richiesta.

Le richieste vengono inviate al server chiamando il GetResponse metodo o le relative controparti asincrone, i BeginGetResponse metodi e EndGetResponse . Al termine dell'operazione richiesta, viene restituito un FtpWebResponse oggetto. L'oggetto FtpWebResponse fornisce lo stato dell'operazione e tutti i dati scaricati dal server.

È possibile impostare un valore di timeout per la lettura o la scrittura nel server usando la ReadWriteTimeout proprietà . Se il periodo di timeout viene superato, il metodo chiamante genera un WebException oggetto con WebExceptionStatus impostato su Timeout.

Quando si scarica un file da un server FTP, se il comando ha esito positivo, il contenuto del file richiesto è disponibile nel flusso dell'oggetto risposta. È possibile accedere a questo flusso chiamando il GetResponseStream metodo . Per altre informazioni, vedere FtpWebResponse.

Se la Proxy proprietà è impostata, direttamente o in un file di configurazione, le comunicazioni con il server FTP vengono eseguite tramite il proxy specificato. Se il proxy specificato è un proxy HTTP, sono supportati solo i DownloadFilecomandi , ListDirectorye ListDirectoryDetails .

Viene memorizzato nella cache solo il contenuto binario scaricato; ovvero, il contenuto ricevuto usando il DownloadFile comando con la UseBinary proprietà impostata su true.

Se possibile, è possibile riutilizzare più FtpWebRequestconnessioni esistenti.

Per altre informazioni sul protocollo FTP, vedere RFC 959: File Transfer Protocol.

Proprietà

AuthenticationLevel

Ottiene o imposta i valori che indicano il livello di autenticazione e di rappresentazione usati per la richiesta.

(Ereditato da WebRequest)
CachePolicy

Ottiene o imposta i criteri della cache per la richiesta.

(Ereditato da WebRequest)
ClientCertificates

Ottiene o imposta i certificati usati per stabilire una connessione crittografata al server FTP.

ConnectionGroupName

Ottiene o imposta il nome del gruppo di connessione che contiene il punto di servizio usato per inviare la richiesta corrente.

ContentLength

Ottiene o imposta un valore ignorato dalla classe FtpWebRequest.

ContentOffset

Ottiene o imposta un offset di byte nel file che viene scaricato da questa richiesta.

ContentType

Genera sempre un'eccezione NotSupportedException.

CreatorInstance
Obsoleti.

Quando ne viene eseguito l'override in una classe discendente, ottiene l'oggetto factory derivato dalla classe IWebRequestCreate usato per creare l'oggetto WebRequest di cui è stata creata un'istanza per effettuare la richiesta all'URI specificato.

(Ereditato da WebRequest)
Credentials

Ottiene o imposta le credenziali usate per comunicare con il server FTP.

DefaultCachePolicy

Definisce i criteri della cache predefiniti per tutte le richieste FTP.

EnableSsl

Ottiene o imposta una struttura Boolean che specifica che deve essere usata una connessione SSL.

Headers

Ottiene un oggetto WebHeaderCollection vuoto.

ImpersonationLevel

Ottiene o imposta il livello di rappresentazione per la richiesta corrente.

(Ereditato da WebRequest)
KeepAlive

Ottiene o imposta un valore Boolean che specifica se la connessione di controllo sul server FTP viene chiusa dopo il completamento della richiesta

Method

Ottiene o imposta il comando da inviare al server FTP.

PreAuthenticate

Genera sempre un'eccezione NotSupportedException.

Proxy

Ottiene o imposta il proxy usato per comunicare con il server FTP.

ReadWriteTimeout

Ottiene o imposta un timeout durante la lettura o la scrittura in un flusso.

RenameTo

Ottiene o imposta il nuovo nome di un file che viene rinominato.

RequestUri

Ottiene l'URI richiesto da questa istanza.

ServicePoint

Ottiene l'oggetto ServicePoint usato per la connessione al server FTP.

Timeout

Ottiene o imposta il numero di millisecondi di attesa per una richiesta.

UseBinary

Ottiene o imposta un valore Boolean che specifica il tipo di dati per il trasferimento di file.

UseDefaultCredentials

Genera sempre un'eccezione NotSupportedException.

UsePassive

Ottiene o imposta il comportamento del processo di trasferimento dei dati di un'applicazione client.

Metodi

Abort()

Termina un'operazione FTP asincrona.

BeginGetRequestStream(AsyncCallback, Object)

Avvia l'apertura asincrona del flusso del contenuto di una richiesta per la scrittura.

BeginGetResponse(AsyncCallback, Object)

Inizia l'invio di una richiesta e la ricezione di una risposta da un server FTP in modo asincrono.

CreateObjRef(Type)

Consente di creare un oggetto che contiene tutte le informazioni rilevanti necessarie per la generazione del proxy utilizzato per effettuare la comunicazione con un oggetto remoto.

(Ereditato da MarshalByRefObject)
EndGetRequestStream(IAsyncResult)

Termina un'operazione asincrona in sospeso avviata con il metodo BeginGetRequestStream(AsyncCallback, Object).

EndGetResponse(IAsyncResult)

Termina un'operazione asincrona in sospeso avviata con il metodo BeginGetResponse(AsyncCallback, Object).

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetLifetimeService()
Obsoleti.

Consente di recuperare l'oggetto servizio di durata corrente per controllare i criteri di durata per l'istanza.

(Ereditato da MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)
Obsoleti.

Popola un oggetto SerializationInfo con i dati necessari per serializzare l'oggetto di destinazione.

(Ereditato da WebRequest)
GetRequestStream()

Recupera il flusso usato per caricare i dati su un server FTP.

GetRequestStreamAsync()

Quando ne viene eseguito l'override in una classe discendente, restituisce un oggetto Stream per la scrittura dei dati nella risorse Internet come operazione asincrona.

(Ereditato da WebRequest)
GetResponse()

Restituisce la risposta del server FTP.

GetResponseAsync()

Quando ne viene eseguito l'override in una classe discendente, restituisce una risposta a una richiesta Internet come operazione asincrona.

(Ereditato da WebRequest)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
InitializeLifetimeService()
Obsoleti.

Ottiene un oggetto servizio di durata per controllare i criteri di durata per questa istanza.

(Ereditato da MarshalByRefObject)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
MemberwiseClone(Boolean)

Crea una copia dei riferimenti dell'oggetto MarshalByRefObject corrente.

(Ereditato da MarshalByRefObject)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Implementazioni dell'interfaccia esplicita

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
Obsoleti.

Quando ne viene eseguito l'override in una classe discendente, popola un'istanza di SerializationInfo con i dati necessari per serializzare WebRequest.

(Ereditato da WebRequest)

Si applica a

Vedi anche