FtpWebRequest クラス
アセンブリ: System (system.dll 内)


FtpWebRequest のインスタンスを取得するには、Create メソッドを使用します。WebClient クラスを使用して、FTP サーバーとの間で情報をアップロードしたりダウンロードしたりすることもできます。これらの方法のいずれかを使用すると、FTP スキーム (たとえば、"ftp://contoso.com") を使用するネットワーク リソースを指定したときは、FtpWebRequest クラスによって、プログラムから FTP サーバーと対話できます。
URI は相対 URI でも絶対 URI でもかまいません。URI が "ftp://contoso.com/%2fpath" (%2f は "/" をエスケープしたもの) という形式である場合、この URI は絶対 URI であり、現在のディレクトリは /path になります。しかし、URI が "ftp://contoso.com/path" である場合、最初に .NET Framework は FTP サーバーにログインし (Credentials プロパティに設定されているユーザー名とパスワードを使用)、その後、現在のディレクトリは <UserLoginDirectory>/path に設定されます。
サーバーに対して有効なユーザー名とパスワードを持つ必要があります。または、サーバーで匿名ログオンを許可している必要があります。Credentials プロパティの設定によって、サーバーとの接続に使用する資格情報を指定できます。または、Create メソッドに渡される URI のUserInfo 部分に、それらの資格情報を含めることができます。URI に UserInfo 情報を含める場合は、指定したユーザー名とパスワードの情報を使用して、Credentials プロパティに新しいネットワーク資格情報が設定されます。
![]() |
---|
EnableSsl プロパティが true でない限り、ユーザー名とパスワードの情報を含めたすべてのデータとコマンドはクリア テキストでサーバーに送信されます。ネットワーク トラフィックを監視すると、だれでも資格情報を表示したり、それらを使用してサーバーに接続したりできます。SSL (Secure Sockets Layer) をサポートしている、資格情報が必要な FTP サーバーに接続する場合は、EnableSsl を true に設定する必要があります。 |
FTP のリソースにアクセスするためには WebPermission が必要です。これがない場合は SecurityException 例外がスローされます。
サーバーに送信するための FTP コマンドを指定するには、Method プロパティを WebRequestMethods.Ftp 構造体で定義された値に設定します。テキスト データを送信するには、UseBinary プロパティを、既定値 (true) から false に変更します。詳細および制限事項については、Method のトピックを参照してください。
FtpWebRequest オブジェクトを使用してサーバーにファイルをアップロードする場合は、GetRequestStream メソッドを呼び出すか、対応する非同期メソッドの BeginGetRequestStream メソッドと EndGetRequestStream メソッドを呼び出して取得される要求ストリームに、ファイルの内容を書き込む必要があります。要求を送信する前に、ストリームに書き込んでから、そのストリームを閉じる必要があります。
要求は、GetResponse メソッドを呼び出すか、対応する非同期メソッドの BeginGetResponse メソッドと EndGetResponse メソッドを呼び出して、サーバーに送信されます。要求された操作が完了すると、FtpWebResponse オブジェクトが返されます。FtpWebResponse オブジェクトによって、操作の状態とサーバーからダウンロードされたすべてのデータが提供されます。
ReadWriteTimeout プロパティを使用して、サーバーからの読み取りまたはサーバーへの書き込みに対してタイムアウト値を設定できます。タイムアウト期限を超過した場合、呼び出し元のメソッドは WebException をスローすると共に、WebExceptionStatus を Timeout に設定します。
FTP サーバーからファイルをダウンロードする場合は、コマンドが正常に終了すると、要求したファイルの内容が応答オブジェクトのストリームで利用できるようになります。このストリームには、GetResponseStream メソッドを呼び出してアクセスできます。詳細については、「FtpWebResponse」を参照してください。
Proxy プロパティが、直接または構成ファイルのいずれかで設定された場合、FTP サーバーとの通信は、指定したプロキシを経由して行われます。指定したプロキシが HTTP プロキシの場合は、DownloadFile、ListDirectory、および ListDirectoryDetails の各コマンドだけがサポートされます。
キャッシュされるのは、ダウンロードしたバイナリ コンテンツのみです。つまり、UseBinary プロパティを true に設定して DownloadFile コマンドを使用して受信したコンテンツのみがキャッシュされます。
可能な場合には、複数の FtpWebRequest が既存の接続を再利用します。
FTP プロトコルの詳細については、RFC 959 『File Transfer Protocol』 (http://www.rfc-editor.org/) を参照してください。

FTP サーバーからファイルを削除するコード例を次に示します。
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 サーバーからファイルをダウンロードするコード例を次に示します。
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; 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(); } } } }
#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(); }


System.MarshalByRefObject
System.Net.WebRequest
System.Net.FtpWebRequest


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FtpWebRequest メンバ
System.Net 名前空間
FtpWebResponse
FtpStatusCode 列挙体
WebRequestMethods.Ftp
WebRequest
WebResponse
WebClient
FtpWebRequest プロパティ


関連項目
FtpWebRequest クラスSystem.Net 名前空間
FtpWebResponse
FtpStatusCode 列挙体
WebRequestMethods.Ftp
WebRequest
WebResponse
WebClient
FtpWebRequest メソッド


名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 ( Object から継承されます。) |
![]() | MemberwiseClone | オーバーロードされます。 ( MarshalByRefObject から継承されます。) |

関連項目
FtpWebRequest クラスSystem.Net 名前空間
FtpWebResponse
FtpStatusCode 列挙体
WebRequestMethods.Ftp
WebRequest
WebResponse
WebClient
FtpWebRequest メンバ
ファイル転送プロトコル (FTP: File Transfer Protocol) クライアントを実装します。
FtpWebRequest データ型で公開されるメンバを以下の表に示します。



名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 (Object から継承されます。) |
![]() | MemberwiseClone | オーバーロードされます。 ( MarshalByRefObject から継承されます。) |

関連項目
FtpWebRequest クラスSystem.Net 名前空間
FtpWebResponse
FtpStatusCode 列挙体
WebRequestMethods.Ftp
WebRequest
WebResponse
WebClient
Weblioに収録されているすべての辞書からFtpWebRequestを検索する場合は、下記のリンクをクリックしてください。

- FtpWebRequestのページへのリンク