FtpWebRequest クラス

定義

ファイル転送プロトコル (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
継承

次のコード例では、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;
}

次のコード例では、 クラスを使用して FTP サーバーからファイルをダウンロードする方法を WebClient 示します。

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については、「 WebRequest を GitHub で使用しないでください」を参照してください。

FtpWebRequestインスタンスを取得するには、 メソッドを使用します Create 。 クラスを WebClient 使用して、FTP サーバーから情報をアップロードおよびダウンロードすることもできます。 これらの方法のいずれかを使用して、FTP スキーム (たとえば) FtpWebRequest を使用するネットワーク リソースを指定すると、 "ftp://contoso.com"クラスは FTP サーバーとプログラムで対話する機能を提供します。

URI は、相対または絶対にすることができます。 URI が 形式 "ftp://contoso.com/%2fpath" の場合 (%2f はエスケープされた '/')、URI は絶対であり、現在のディレクトリは です /path。 ただし、URI が という形式"ftp://contoso.com/path"の場合、最初に.NET Frameworkが FTP サーバーにログインします (プロパティによって設定されたユーザー名とパスワードをCredentials使用)、現在のディレクトリは に<UserLoginDirectory>/path設定されます。

サーバーの有効なユーザー名とパスワードを持っているか、サーバーが匿名ログオンを許可する必要があります。 サーバーへの接続に使用する資格情報を指定するには、 プロパティをCredentials設定するか、 メソッドに渡される URI の部分に資格情報をCreateUserInfoめることができます。 URI に情報を含める UserInfo 場合、 プロパティは、 Credentials 指定されたユーザー名とパスワード情報を持つ新しいネットワーク資格情報に設定されます。

注意事項

プロパティが EnableSsl でない true限り、ユーザー名とパスワード情報を含むすべてのデータとコマンドがクリア テキストでサーバーに送信されます。 ネットワーク トラフィックを監視しているすべてのユーザーは、自身の資格情報を確認し、それらを使用してサーバーに接続できます。 資格情報を必要とし、Secure Sockets Layer (SSL) をサポートする FTP サーバーに接続している場合は、 を に設定 EnableSsl する true必要があります。

FTP リソースにアクセスする必要があります WebPermission 。それ以外の場合は例外 SecurityException がスローされます。

プロパティを 構造体で定義された値に設定 Method して、サーバーに送信する FTP コマンドを WebRequestMethods.Ftp 指定します。 テキスト データを送信するには、 プロパティを UseBinary 既定値 (true) から に false変更します。 詳細と制限については、「」を参照してください Method

オブジェクトをFtpWebRequest使用してサーバーにファイルをアップロードする場合は、 メソッドまたはその非同期に対応する メソッド と EndGetRequestStream メソッドを呼び出GetRequestStreamして取得した要求ストリームにファイルの内容をBeginGetRequestStream書き込む必要があります。 要求を送信する前に、ストリームに書き込み、ストリームを閉じる必要があります。

要求は、 メソッドまたはその非同期に対応する メソッドと EndGetResponse メソッドをGetResponse呼び出すことによってサーバーにBeginGetResponse送信されます。 要求された操作が完了すると、 FtpWebResponse オブジェクトが返されます。 オブジェクトは FtpWebResponse 、操作の状態と、サーバーからダウンロードされたデータを提供します。

プロパティを使用して、サーバーへの読み取りまたは書き込みのタイムアウト値を ReadWriteTimeout 設定できます。 タイムアウト期間を超えた場合、呼び出し元のメソッドは を に設定して をTimeoutスロー WebExceptionWebExceptionStatusします。

FTP サーバーからファイルをダウンロードするときに、コマンドが成功した場合は、要求されたファイルの内容を応答オブジェクトのストリームで使用できます。 このストリームには、 メソッドを GetResponseStream 呼び出すことでアクセスできます。 詳細については、「FtpWebResponse」を参照してください。

プロパティが Proxy 直接または構成ファイルで設定されている場合、FTP サーバーとの通信は、指定されたプロキシを介して行われます。 指定したプロキシが HTTP プロキシの場合は、および ListDirectoryDetails コマンドのみがDownloadFileListDirectoryサポートされます。

ダウンロードしたバイナリ コンテンツのみがキャッシュされます。つまり、 プロパティが にtrue設定された コマンドをDownloadFile使用して受信したUseBinaryコンテンツです。

可能であれば、複数 FtpWebRequestのが既存の接続を再利用します。

FTP プロトコルの詳細については、「 RFC 959: ファイル転送プロトコル」を参照してください。

プロパティ

AuthenticationLevel

この要求で使用する認証レベルおよび偽装レベルを示す値を取得または設定します。

(継承元 WebRequest)
CachePolicy

この要求のキャッシュ ポリシーを取得または設定します。

(継承元 WebRequest)
ClientCertificates

FTP サーバーへの暗号化接続を確立するために使用する証明書を取得または設定します。

ConnectionGroupName

現在の要求を送信するために使用するサービス ポイントが含まれる接続グループの名前を取得または設定します。

ContentLength

FtpWebRequest クラスによって無視される値を取得または設定します。

ContentOffset

この要求でダウンロードされるファイル内のバイト オフセットを取得または設定します。

ContentType

常に NotSupportedException をスローします。

CreatorInstance
古い.

派生クラスでオーバーライドされると、IWebRequestCreate クラスから派生するファクトリ オブジェクトを取得します。このクラスは、指定 URI に対して要求を行うためにインスタンス化される WebRequest を作成するために使用されます。

(継承元 WebRequest)
Credentials

FTP サーバーとの通信に使用する資格情報を取得または設定します。

DefaultCachePolicy

すべての FTP 要求に対する既定のキャッシュ ポリシーを定義します。

EnableSsl

SSL 接続を使用する必要があるかどうかを指定する Boolean を取得または設定します。

Headers

空の WebHeaderCollection オブジェクトを取得します。

ImpersonationLevel

現在の要求に対する偽装レベルを取得または設定します。

(継承元 WebRequest)
KeepAlive

要求の完了後に FTP サーバーへの制御接続を閉じるかどうかを指定する Boolean 値を取得または設定します。

Method

FTP サーバーに送信するためのコマンドを取得または設定します。

PreAuthenticate

常に NotSupportedException をスローします。

Proxy

FTP サーバーとの通信に使用するプロキシを取得または設定します。

ReadWriteTimeout

ストリームからの読み取り時またはストリームへの書き込み時のタイムアウトを取得または設定します。

RenameTo

名前を変更されたファイルの新しい名前を取得または設定します。

RequestUri

このインスタンスで要求された URI を取得します。

ServicePoint

FTP サーバーに接続するために使用する ServicePoint オブジェクトを取得します。

Timeout

要求に対するミリ秒単位の待機時間を取得または設定します。

UseBinary

ファイル転送のデータ型を指定する Boolean 値を取得または設定します。

UseDefaultCredentials

常に NotSupportedException をスローします。

UsePassive

クライアント アプリケーションのデータ転送処理の動作を取得または設定します。

メソッド

Abort()

非同期の FTP 操作を終了します。

BeginGetRequestStream(AsyncCallback, Object)

書き込み用に、要求のコンテンツ ストリームの非同期的なオープンを開始します。

BeginGetResponse(AsyncCallback, Object)

要求の非同期的な送信と、FTP サーバーからの応答の非同期的な受信を開始します。

CreateObjRef(Type)

リモート オブジェクトとの通信に使用するプロキシの生成に必要な情報をすべて格納しているオブジェクトを作成します。

(継承元 MarshalByRefObject)
EndGetRequestStream(IAsyncResult)

BeginGetRequestStream(AsyncCallback, Object) で開始された保留中の非同期操作を終了します。

EndGetResponse(IAsyncResult)

BeginGetResponse(AsyncCallback, Object) で開始された保留中の非同期操作を終了します。

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetLifetimeService()
古い.

対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。

(継承元 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)
古い.

派生クラスでオーバーライドされる場合、SerializationInfo インスタンスに、WebRequest をシリアル化するために必要なデータを設定します。

(継承元 WebRequest)

適用対象

こちらもご覧ください