FtpWebRequest Sınıf

Tanım

Dosya Aktarım Protokolü (FTP) istemcisi uygular.

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
Devralma

Örnekler

Aşağıdaki kod örneği, FTP sunucusundan dosya silme işlemini gösterir.

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

Aşağıdaki kod örneği, sınıfını kullanarak bir FTP sunucusundan dosya indirme işlemini WebClient gösterir.

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

Aşağıdaki kod örneğinde, ftp sunucusuna dosya yüklemek için zaman uyumsuz işlemlerin kullanılması gösterilmektedir.

#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();
            }
        }
    }
}

Açıklamalar

Önemli

Sınıfını yeni geliştirme için kullanmanızı FtpWebRequest önermiyoruz. daha fazla bilgi ve alternatifleri için FtpWebRequestbkz . GitHub'da WebRequest kullanılmamalıdır .

örneğini FtpWebRequestalmak için yöntemini kullanın Create . Ftp sunucusundan WebClient bilgileri karşıya yüklemek ve indirmek için de sınıfını kullanabilirsiniz. Bu yaklaşımlardan birini kullanarak, FTP şemasını kullanan bir ağ kaynağı belirttiğinizde (örneğin, "ftp://contoso.com") FtpWebRequest sınıfı FTP sunucularıyla program aracılığıyla etkileşim kurma olanağı sağlar.

URI göreli veya mutlak olabilir. URI (%2f) biçimindeyse "ftp://contoso.com/%2fpath" kaçış '/' ise, URI mutlaktır ve geçerli dizin olur /path. Ancak, URI biçimindeyse"ftp://contoso.com/path", önce .NET Framework FTP sunucusunda oturum açar (özelliği tarafından Credentials ayarlanan kullanıcı adını ve parolayı kullanarak), geçerli dizin olarak <UserLoginDirectory>/pathayarlanır.

Sunucu için geçerli bir kullanıcı adı ve parolanız olmalıdır veya sunucu anonim oturum açmaya izin vermelidir. özelliğini ayarlayarak Credentials sunucuya bağlanmak için kullanılan kimlik bilgilerini belirtebilir veya bunları UserInfo yönteme Create geçirilen URI'nin bölümüne ekleyebilirsiniz. URI'ye bilgi eklerseniz UserInfo , Credentials özelliği belirtilen kullanıcı adı ve parola bilgileriyle yeni bir ağ kimlik bilgilerine ayarlanır.

Dikkat

EnableSsl özelliği olmadığı truesürece, kullanıcı adınız ve parola bilgileriniz de dahil olmak üzere tüm veriler ve komutlar düz metin olarak sunucuya gönderilir. Ağ trafiğini izleyen herkes kimlik bilgilerinizi görüntüleyebilir ve bunları kullanarak sunucuya bağlanabilir. Kimlik bilgileri gerektiren ve Güvenli Yuva Katmanını (SSL) destekleyen bir FTP sunucusuna bağlanıyorsanız olarak ayarlamanız EnableSsltruegerekir.

FTP kaynağına erişmeniz gerekir WebPermission ; aksi takdirde bir SecurityException özel durum oluşturulur.

özelliğini yapıda WebRequestMethods.Ftp tanımlanan bir değere ayarlayarak Method sunucuya gönderilecek FTP komutunu belirtin. Metin verilerini iletmek için özelliğini varsayılan değerinden UseBinary (true) falseolarak değiştirin. Ayrıntılar ve kısıtlamalar için bkz Method. .

Bir dosyayı bir sunucuya yüklemek için bir FtpWebRequest nesne kullanırken, dosya içeriğini yöntemini veya zaman uyumsuz karşılıklarını, ve EndGetRequestStream yöntemlerini çağırarak GetRequestStream alınan istek akışına BeginGetRequestStream yazmanız gerekir. İsteği göndermeden önce akışa yazmanız ve akışı kapatmanız gerekir.

İstekler, yöntemi veya zaman uyumsuz karşılıkları olan ve EndGetResponse yöntemleri çağrılarak GetResponse sunucuya BeginGetResponse gönderilir. İstenen işlem tamamlandığında bir FtpWebResponse nesne döndürülür. nesnesi, FtpWebResponse işlemin durumunu ve sunucudan indirilen tüm verileri sağlar.

özelliğini kullanarak ReadWriteTimeout sunucuya okumak veya yazmak için bir zaman aşımı değeri ayarlayabilirsiniz. Zaman aşımı süresi aşılırsa, çağıran yöntem olarak ayarlanmış Timeoutbir WebExceptionWebExceptionStatus oluşturur.

FTP sunucusundan bir dosya indirilirken, komut başarılı olursa, istenen dosyanın içeriği yanıt nesnesinin akışında kullanılabilir. yöntemini çağırarak bu akışa GetResponseStream erişebilirsiniz. Daha fazla bilgi için bkz. FtpWebResponse.

Proxy Özellik doğrudan veya bir yapılandırma dosyasında ayarlanırsa, FTP sunucusuyla iletişim belirtilen ara sunucu üzerinden yapılır. Belirtilen proxy bir HTTP ara sunucusuysa, yalnızca DownloadFile, ListDirectoryve ListDirectoryDetails komutları desteklenir.

Yalnızca indirilen ikili içerik önbelleğe alınır; yani, özelliği olarak ayarlanmış truekomutu UseBinary kullanılarak DownloadFile alınan içerik.

Mümkünse, birden çok FtpWebRequestvar olan bağlantıları yeniden kullanın.

FTP protokolü hakkında daha fazla bilgi için bkz. RFC 959: Dosya Aktarım Protokolü.

Özellikler

AuthenticationLevel

Bu istek için kullanılan kimlik doğrulama ve kimliğe bürünme düzeyini gösteren değerleri alır veya ayarlar.

(Devralındığı yer: WebRequest)
CachePolicy

Bu istek için önbellek ilkesini alır veya ayarlar.

(Devralındığı yer: WebRequest)
ClientCertificates

FTP sunucusuna şifreli bağlantı kurmak için kullanılan sertifikaları alır veya ayarlar.

ConnectionGroupName

Geçerli isteği göndermek için kullanılan hizmet noktasını içeren bağlantı grubunun adını alır veya ayarlar.

ContentLength

sınıfı tarafından FtpWebRequest yoksayılan bir değeri alır veya ayarlar.

ContentOffset

Bu istek tarafından indirilen dosyaya bayt uzaklığını alır veya ayarlar.

ContentType

Her zaman bir NotSupportedExceptionatar.

CreatorInstance
Geçersiz.

Bir alt sınıfta geçersiz kılındığında, belirtilen URI'ye istekte bulunmak için örneği oluşturulmuş oluşturmak WebRequest için kullanılan sınıftan türetilen IWebRequestCreate fabrika nesnesini alır.

(Devralındığı yer: WebRequest)
Credentials

FTP sunucusuyla iletişim kurmak için kullanılan kimlik bilgilerini alır veya ayarlar.

DefaultCachePolicy

Tüm FTP istekleri için varsayılan önbellek ilkesini tanımlar.

EnableSsl

SSL bağlantısının kullanılması gerektiğini belirten bir alır veya ayarlar Boolean .

Headers

Boş WebHeaderCollection bir nesne alır.

ImpersonationLevel

Geçerli istek için kimliğe bürünme düzeyini alır veya ayarlar.

(Devralındığı yer: WebRequest)
KeepAlive

İstek tamamlandıktan sonra FTP sunucusuna yönelik denetim bağlantısının kapatılıp kapatılmayacağını belirten bir Boolean değer alır veya ayarlar.

Method

FTP sunucusuna gönderilecek komutu alır veya ayarlar.

PreAuthenticate

Her zaman bir NotSupportedExceptionatar.

Proxy

FTP sunucusuyla iletişim kurmak için kullanılan ara sunucuyu alır veya ayarlar.

ReadWriteTimeout

Bir akıştan okurken veya akışa yazarken zaman aşımını alır veya ayarlar.

RenameTo

Yeniden adlandırılmakta olan bir dosyanın yeni adını alır veya ayarlar.

RequestUri

Bu örnek tarafından istenen URI'yi alır.

ServicePoint

FTP sunucusuna ServicePoint bağlanmak için kullanılan nesneyi alır.

Timeout

İstek için beklenen milisaniye sayısını alır veya ayarlar.

UseBinary

Dosya aktarımları için veri türünü belirten bir Boolean değer alır veya ayarlar.

UseDefaultCredentials

Her zaman bir NotSupportedExceptionatar.

UsePassive

İstemci uygulamasının veri aktarım işleminin davranışını alır veya ayarlar.

Yöntemler

Abort()

Zaman uyumsuz ftp işlemini sonlandırır.

BeginGetRequestStream(AsyncCallback, Object)

Bir isteğin içerik akışını yazmak için zaman uyumsuz olarak açmaya başlar.

BeginGetResponse(AsyncCallback, Object)

zaman uyumsuz olarak bir FTP sunucusundan istek göndermeye ve yanıt almaya başlar.

CreateObjRef(Type)

Uzak bir nesneyle iletişim kurmak için kullanılan bir ara sunucu oluşturmak için gereken tüm ilgili bilgileri içeren bir nesne oluşturur.

(Devralındığı yer: MarshalByRefObject)
EndGetRequestStream(IAsyncResult)

ile BeginGetRequestStream(AsyncCallback, Object)başlatılan bekleyen zaman uyumsuz işlemi sonlandırır.

EndGetResponse(IAsyncResult)

ile BeginGetResponse(AsyncCallback, Object)başlatılan bekleyen zaman uyumsuz işlemi sonlandırır.

Equals(Object)

Belirtilen nesnenin geçerli nesneye eşit olup olmadığını belirler.

(Devralındığı yer: Object)
GetHashCode()

Varsayılan karma işlevi işlevi görür.

(Devralındığı yer: Object)
GetLifetimeService()
Geçersiz.

Bu örnek için yaşam süresi ilkesini denetleen geçerli yaşam süresi hizmet nesnesini alır.

(Devralındığı yer: MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)
Geçersiz.

hedef nesneyi seri hale getirmek için gereken verilerle doldurur SerializationInfo .

(Devralındığı yer: WebRequest)
GetRequestStream()

Ftp sunucusuna veri yüklemek için kullanılan akışı alır.

GetRequestStreamAsync()

Bir alt sınıfta geçersiz kılındığında, zaman uyumsuz bir işlem olarak İnternet kaynağına veri yazmak için bir döndürür Stream .

(Devralındığı yer: WebRequest)
GetResponse()

FTP sunucusu yanıtını döndürür.

GetResponseAsync()

Bir alt sınıfta geçersiz kılındığında, zaman uyumsuz bir işlem olarak İnternet isteğine bir yanıt döndürür.

(Devralındığı yer: WebRequest)
GetType()

Type Geçerli örneğini alır.

(Devralındığı yer: Object)
InitializeLifetimeService()
Geçersiz.

Bu örneğin yaşam süresi ilkesini denetlemek için bir yaşam süresi hizmet nesnesi alır.

(Devralındığı yer: MarshalByRefObject)
MemberwiseClone()

Geçerli Objectöğesinin sığ bir kopyasını oluşturur.

(Devralındığı yer: Object)
MemberwiseClone(Boolean)

Geçerli MarshalByRefObject nesnenin sığ bir kopyasını oluşturur.

(Devralındığı yer: MarshalByRefObject)
ToString()

Geçerli nesneyi temsil eden dizeyi döndürür.

(Devralındığı yer: Object)

Belirtik Arabirim Kullanımları

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
Geçersiz.

Bir alt sınıfta geçersiz kılındığında, bir SerializationInfo örneği seri hale WebRequestgetirmek için gereken verilerle doldurur.

(Devralındığı yer: WebRequest)

Şunlara uygulanır

Ayrıca bkz.