FtpWebRequest 類別

定義

實作檔案傳輸通訊協定 (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
繼承

範例

下列程式碼範例示範如何從 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;
}

下列程式碼範例示範如何使用 WebClient 類別,從 FTP 伺服器下載檔案。

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

下列程式碼範例示範如何使用非同步作業將檔案上傳至 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();
            }
        }
    }
}

備註

重要

不建議您將 類別用於 FtpWebRequest 新的開發。 如需 的詳細資訊和替代方案 FtpWebRequest ,請參閱不應該在 GitHub 上使用 WebRequest

若要取得 的 FtpWebRequest 實例,請使用 Create 方法。 您也可以使用 WebClient 類別,從 FTP 伺服器上傳和下載資訊。 使用上述其中一種方法時,當您指定使用 FTP 配置的網路資源 (時,例如, "ftp://contoso.com") FtpWebRequest 類別提供以程式設計方式與 FTP 伺服器互動的能力。

URI 可以是相對或絕對。 如果 URI 的格式 "ftp://contoso.com/%2fpath" 為 (%2f 是逸出 '/') ,則 URI 是絕對的,而目前的目錄為 /path 。 不過,如果 URI 的格式 "ftp://contoso.com/path" 為 ,首先,.NET Framework會使用屬性所設定的使用者名稱和密碼 Credentials (登入 FTP 伺服器) ,然後將目前的目錄設定為 <UserLoginDirectory>/path

您必須擁有伺服器的有效使用者名稱和密碼,或伺服器必須允許匿名登入。 您可以藉由設定 Credentials 屬性來指定用來連線到伺服器的認證,也可以將它們包含在 UserInfo 傳遞至 Create 方法的 URI 部分。 如果您在 UserInfo URI 中包含資訊,屬性 Credentials 會設定為具有指定使用者名稱和密碼資訊的新網路認證。

警告

EnableSsl除非 屬性是 true ,否則所有資料和命令,包括您的使用者名稱和密碼資訊,都會以純文字傳送至伺服器。 任何監視流量的任何人都可檢視您的認證,並使用它們連線到伺服器。 如果您要連線到需要認證的 FTP 伺服器,且支援安全通訊端層 (SSL) ,您應該將 設定 EnableSsltrue

您必須必須 WebPermission 存取 FTP 資源, SecurityException 否則會擲回例外狀況。

將 屬性設定 Method 為 結構中 WebRequestMethods.Ftp 定義的值,以指定要傳送至伺服器的 FTP 命令。 若要傳輸文字資料,請將 UseBinary 屬性從其預設值 (true) 變更為 false 。 如需詳細資料和限制,請參閱 Method

使用 FtpWebRequest 物件將檔案上傳至伺服器時,您必須呼叫 GetRequestStream 方法或其非同步對應專案和 BeginGetRequestStreamEndGetRequestStream 方法,將檔案內容寫入要求資料流程中。 您必須先寫入資料流程,然後關閉資料流程,才能傳送要求。

要求會藉由呼叫 GetResponse 方法或其非同步對應專案和 BeginGetResponseEndGetResponse 方法,傳送至伺服器。 當要求的作業完成時, FtpWebResponse 會傳回 物件。 物件 FtpWebResponse 提供作業的狀態,以及從伺服器下載的任何資料。

您可以使用 屬性,設定讀取或寫入伺服器的 ReadWriteTimeout 逾時值。 如果超過逾時期間,呼叫方法會 WebException 擲回 設定為 TimeoutWebExceptionStatus

從 FTP 伺服器下載檔案時,如果命令成功,回應物件的資料流程中就會提供要求檔案的內容。 您可以呼叫 GetResponseStream 方法來存取此資料流程。 如需詳細資訊,請參閱FtpWebResponse

Proxy如果已設定 屬性,則直接或在組態檔中,會透過指定的 Proxy 與 FTP 伺服器進行通訊。 如果指定的 Proxy 是 HTTP Proxy,則只 DownloadFile 支援 、 ListDirectoryListDirectoryDetails 命令。

只會快取下載的二進位內容;也就是說,使用 DownloadFile 命令接收的內容, UseBinary 並將 屬性設定為 true

如果可能,多個 會 FtpWebRequest 重複使用現有的連線。

如需 FTP 通訊協定的詳細資訊,請參閱 RFC 959:檔案傳輸通訊協定

屬性

AuthenticationLevel

取得或設定值,指出用於這個要求的驗證和模擬等級。

(繼承來源 WebRequest)
CachePolicy

取得或設定這個要求的快取原則。

(繼承來源 WebRequest)
ClientCertificates

取得或設定用來建立與 FTP 伺服器之加密連接的憑證。

ConnectionGroupName

取得或設定連接群組的名稱,這個連接群組包含用來傳送目前要求的服務點。

ContentLength

取得或設定 FtpWebRequest 類別忽略的值。

ContentOffset

取得或設定這個要求所下載之檔案的位元組位移。

ContentType

永遠擲回 NotSupportedException

CreatorInstance
已淘汰.

在子代類別中覆寫時,取得衍生自 IWebRequestCreate 類別的 Factory 物件,用來建立執行個體化的 WebRequest 以對指定的 URI 提出要求。

(繼承來源 WebRequest)
Credentials

取得或設定用來與 FTP 伺服器通訊的認證。

DefaultCachePolicy

為所有 FTP 要求,定義預設的快取原則。

EnableSsl

取得或設定 Boolean,指定是否應使用 SSL 連線。

Headers

取得空的 WebHeaderCollection 物件。

ImpersonationLevel

取得或設定目前要求的模擬等級。

(繼承來源 WebRequest)
KeepAlive

取得或設定 Boolean 值,指定在要求完成之後,與 FTP 伺服器的控制連接是否關閉。

Method

取得或設定要傳送至 FTP 伺服器的命令。

PreAuthenticate

永遠擲回 NotSupportedException

Proxy

取得或設定用來與 FTP 伺服器通訊的 Proxy。

ReadWriteTimeout

取得或設定讀取或寫入資料流的逾時。

RenameTo

取得或設定重新命名檔案的新名稱。

RequestUri

取得這個執行個體所要求的 URI。

ServicePoint

取得用來連接到 FTP 伺服器的 ServicePoint 物件。

Timeout

取得或設定等待要求的毫秒數。

UseBinary

取得或設定 Boolean 值,指定檔案傳輸的資料型別。

UseDefaultCredentials

永遠擲回 NotSupportedException

UsePassive

取得或設定用戶端應用程式之資料傳輸處理序的行為。

方法

Abort()

結束非同步 FTP 作業。

BeginGetRequestStream(AsyncCallback, Object)

開始非同步開啟要求的內容資料流,以進行寫入。

BeginGetResponse(AsyncCallback, Object)

開始以非同步的方式傳送要求,並且接收來自 FTP 伺服器的回應。

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。

(繼承來源 MarshalByRefObject)
EndGetRequestStream(IAsyncResult)

結束由 BeginGetRequestStream(AsyncCallback, Object) 所啟動的暫止非同步作業。

EndGetResponse(IAsyncResult)

結束由 BeginGetResponse(AsyncCallback, Object) 所啟動的暫止非同步作業。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetLifetimeService()
已淘汰.

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。

(繼承來源 MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)
已淘汰.

將序列化目標物件所需的資料填入 SerializationInfo

(繼承來源 WebRequest)
GetRequestStream()

擷取用來上載資料至 FTP 伺服器的資料流。

GetRequestStreamAsync()

在子代類別中覆寫時,傳回以非同步作業方式將資料寫入網際網路資源的 Stream

(繼承來源 WebRequest)
GetResponse()

傳回 FTP 伺服器回應。

GetResponseAsync()

在子代類別中覆寫時,傳回對網際網路要求的回應,做為非同步作業。

(繼承來源 WebRequest)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
InitializeLifetimeService()
已淘汰.

取得存留期服務物件,以控制這個執行個體的存留期原則。

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。

(繼承來源 MarshalByRefObject)
ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

明確介面實作

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
已淘汰.

在子代類別中覆寫時,以序列化 WebRequest 所需的資料填入 SerializationInfo 執行個體。

(繼承來源 WebRequest)

適用於

另請參閱