Share via


FtpWebRequest Kelas

Definisi

Menerapkan klien Protokol Transfer File (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
Warisan

Contoh

Contoh kode berikut menunjukkan penghapusan file dari 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;
}

Contoh kode berikut menunjukkan pengunduhan file dari server FTP dengan menggunakan WebClient kelas .

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

Contoh kode berikut menunjukkan penggunaan operasi asinkron untuk mengunggah file ke 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();
            }
        }
    }
}

Keterangan

Penting

Kami tidak menyarankan Anda menggunakan FtpWebRequest kelas untuk pengembangan baru. Untuk informasi selengkapnya dan alternatif untuk FtpWebRequest, lihat WebRequest tidak boleh digunakan di GitHub.

Untuk mendapatkan instans , FtpWebRequestgunakan Create metode . Anda juga dapat menggunakan WebClient kelas untuk mengunggah dan mengunduh informasi dari server FTP. Menggunakan salah satu pendekatan ini, ketika Anda menentukan sumber daya jaringan yang menggunakan skema FTP (misalnya, "ftp://contoso.com") FtpWebRequest kelas menyediakan kemampuan untuk berinteraksi secara terprogram dengan server FTP.

URI mungkin relatif atau absolut. Jika URI adalah formulir "ftp://contoso.com/%2fpath" (%2f adalah escaped '/'), maka URI adalah absolut, dan direktori saat ini adalah /path. Namun, jika URI adalah formulir "ftp://contoso.com/path", pertama-tama .NET Framework masuk ke server FTP (menggunakan nama pengguna dan kata sandi yang diatur oleh Credentials properti ), maka direktori saat ini diatur ke <UserLoginDirectory>/path.

Anda harus memiliki nama pengguna dan kata sandi yang valid untuk server atau server harus mengizinkan masuk secara anonim. Anda dapat menentukan kredensial yang digunakan untuk menyambungkan ke server dengan mengatur Credentials properti atau Anda dapat menyertakannya dalam UserInfo bagian URI yang diteruskan ke Create metode . Jika Anda menyertakan UserInfo informasi dalam URI, Credentials properti diatur ke kredensial jaringan baru dengan informasi nama pengguna dan kata sandi yang ditentukan.

Perhatian

EnableSsl Kecuali properti adalah true, semua data dan perintah, termasuk informasi nama pengguna dan kata sandi Anda, dikirim ke server dalam teks yang jelas. Siapa pun yang memantau lalu lintas jaringan dapat melihat mandat Anda dan menggunakannya untuk terhubung ke server. Jika Anda menyambungkan ke server FTP yang memerlukan kredensial dan mendukung Secure Sockets Layer (SSL), Anda harus mengatur EnableSsl ke true.

Anda harus WebPermission mengakses sumber daya FTP; jika tidak, SecurityException pengecualian akan dilemparkan.

Tentukan perintah FTP untuk dikirim ke server dengan mengatur Method properti ke nilai yang ditentukan dalam WebRequestMethods.Ftp struktur. Untuk mengirimkan data teks, ubah UseBinary properti dari nilai defaultnya (true) menjadi false. Untuk detail dan batasan, lihat Method.

Saat menggunakan FtpWebRequest objek untuk mengunggah file ke server, Anda harus menulis konten file ke aliran permintaan yang diperoleh dengan memanggil GetRequestStream metode atau rekan asinkronnya, BeginGetRequestStream metode dan EndGetRequestStream . Anda harus menulis ke aliran dan menutup aliran sebelum mengirim permintaan.

Permintaan dikirim ke server dengan memanggil GetResponse metode atau rekan asinkronnya, BeginGetResponse metode dan EndGetResponse . Ketika operasi yang diminta selesai, objek FtpWebResponse dikembalikan. Objek FtpWebResponse menyediakan status operasi dan data apa pun yang diunduh dari server.

Anda dapat mengatur nilai waktu habis untuk membaca atau menulis ke server dengan menggunakan ReadWriteTimeout properti . Jika periode waktu habis terlampaui, metode panggilan akan melempar dengan WebExceptionWebExceptionStatus diatur ke Timeout.

Saat mengunduh file dari server FTP, jika perintah berhasil, konten file yang diminta tersedia di aliran objek respons. Anda dapat mengakses aliran ini dengan memanggil GetResponseStream metode . Untuk informasi selengkapnya, lihat FtpWebResponse.

Proxy Jika properti diatur, baik secara langsung atau dalam file konfigurasi, komunikasi dengan server FTP dilakukan melalui proksi yang ditentukan. Jika proksi yang ditentukan adalah proksi HTTP, hanya DownloadFileperintah , ListDirectory, dan ListDirectoryDetails yang didukung.

Hanya konten biner yang diunduh yang di-cache; artinya, konten yang diterima menggunakan DownloadFile perintah dengan properti diatur UseBinary ke true.

Beberapa FtpWebRequests menggunakan kembali koneksi yang ada, jika memungkinkan.

Untuk informasi selengkapnya tentang protokol FTP, lihat RFC 959: Protokol Transfer File.

Properti

AuthenticationLevel

Mendapatkan atau menetapkan nilai yang menunjukkan tingkat autentikasi dan peniruan yang digunakan untuk permintaan ini.

(Diperoleh dari WebRequest)
CachePolicy

Mendapatkan atau menetapkan kebijakan cache untuk permintaan ini.

(Diperoleh dari WebRequest)
ClientCertificates

Mendapatkan atau mengatur sertifikat yang digunakan untuk membuat koneksi terenkripsi ke server FTP.

ConnectionGroupName

Mendapatkan atau mengatur nama grup koneksi yang berisi titik layanan yang digunakan untuk mengirim permintaan saat ini.

ContentLength

Mendapatkan atau menetapkan nilai yang diabaikan oleh FtpWebRequest kelas.

ContentOffset

Mendapatkan atau mengatur offset byte ke dalam file yang diunduh oleh permintaan ini.

ContentType

Selalu melempar .NotSupportedException

CreatorInstance
Kedaluwarsa.

Ketika ditimpa di kelas turunan, mendapatkan objek pabrik yang berasal dari kelas yang IWebRequestCreate digunakan untuk membuat WebRequest instans untuk membuat permintaan ke URI yang ditentukan.

(Diperoleh dari WebRequest)
Credentials

Mendapatkan atau mengatur kredensial yang digunakan untuk berkomunikasi dengan server FTP.

DefaultCachePolicy

Menentukan kebijakan cache default untuk semua permintaan FTP.

EnableSsl

Mendapatkan atau mengatur Boolean yang menentukan bahwa koneksi SSL harus digunakan.

Headers

Mendapatkan objek kosong WebHeaderCollection .

ImpersonationLevel

Mendapatkan atau mengatur tingkat peniruan untuk permintaan saat ini.

(Diperoleh dari WebRequest)
KeepAlive

Mendapatkan atau menetapkan Boolean nilai yang menentukan apakah koneksi kontrol ke server FTP ditutup setelah permintaan selesai.

Method

Mendapatkan atau mengatur perintah untuk dikirim ke server FTP.

PreAuthenticate

Selalu melempar .NotSupportedException

Proxy

Mendapatkan atau mengatur proksi yang digunakan untuk berkomunikasi dengan server FTP.

ReadWriteTimeout

Mendapatkan atau mengatur waktu habis saat membaca dari atau menulis ke streaming.

RenameTo

Mendapatkan atau mengatur nama baru file yang diganti namanya.

RequestUri

Mendapatkan URI yang diminta oleh instans ini.

ServicePoint

Mendapatkan objek yang ServicePoint digunakan untuk menyambungkan ke server FTP.

Timeout

Mendapatkan atau mengatur jumlah milidetik untuk menunggu permintaan.

UseBinary

Mendapatkan atau menetapkan Boolean nilai yang menentukan jenis data untuk transfer file.

UseDefaultCredentials

Selalu melempar .NotSupportedException

UsePassive

Mendapatkan atau mengatur perilaku proses transfer data aplikasi klien.

Metode

Abort()

Menghentikan operasi FTP asinkron.

BeginGetRequestStream(AsyncCallback, Object)

Mulai secara asinkron membuka aliran konten permintaan untuk menulis.

BeginGetResponse(AsyncCallback, Object)

Mulai mengirim permintaan dan menerima respons dari server FTP secara asinkron.

CreateObjRef(Type)

Membuat objek yang berisi semua informasi relevan yang diperlukan untuk menghasilkan proksi yang digunakan untuk berkomunikasi dengan objek jarak jauh.

(Diperoleh dari MarshalByRefObject)
EndGetRequestStream(IAsyncResult)

Mengakhiri operasi asinkron yang tertunda dimulai dengan BeginGetRequestStream(AsyncCallback, Object).

EndGetResponse(IAsyncResult)

Mengakhiri operasi asinkron yang tertunda dimulai dengan BeginGetResponse(AsyncCallback, Object).

Equals(Object)

Menentukan apakah objek yang ditentukan sama dengan objek saat ini.

(Diperoleh dari Object)
GetHashCode()

Berfungsi sebagai fungsi hash default.

(Diperoleh dari Object)
GetLifetimeService()
Kedaluwarsa.

Mengambil objek layanan seumur hidup saat ini yang mengontrol kebijakan seumur hidup untuk instans ini.

(Diperoleh dari MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)
Kedaluwarsa.

Mengisi dengan data yang SerializationInfo diperlukan untuk membuat serialisasi objek target.

(Diperoleh dari WebRequest)
GetRequestStream()

Mengambil aliran yang digunakan untuk mengunggah data ke server FTP.

GetRequestStreamAsync()

Saat ditimpa di kelas turunan, mengembalikan Stream untuk menulis data ke sumber daya Internet sebagai operasi asinkron.

(Diperoleh dari WebRequest)
GetResponse()

Mengembalikan respons server FTP.

GetResponseAsync()

Saat ditimpa di kelas turunan, mengembalikan respons terhadap permintaan Internet sebagai operasi asinkron.

(Diperoleh dari WebRequest)
GetType()

Mendapatkan instans Type saat ini.

(Diperoleh dari Object)
InitializeLifetimeService()
Kedaluwarsa.

Mendapatkan objek layanan seumur hidup untuk mengontrol kebijakan seumur hidup untuk instans ini.

(Diperoleh dari MarshalByRefObject)
MemberwiseClone()

Membuat salinan dangkal dari yang saat ini Object.

(Diperoleh dari Object)
MemberwiseClone(Boolean)

Membuat salinan dangkal objek saat ini MarshalByRefObject .

(Diperoleh dari MarshalByRefObject)
ToString()

Mengembalikan string yang mewakili objek saat ini.

(Diperoleh dari Object)

Implementasi Antarmuka Eksplisit

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
Kedaluwarsa.

Ketika ditimpa di kelas turunan, mengisi instans dengan data yang SerializationInfo diperlukan untuk menserialisasikan WebRequest.

(Diperoleh dari WebRequest)

Berlaku untuk

Lihat juga