FtpWebRequest クラスとは? わかりやすく解説

FtpWebRequest クラス

メモ : このクラスは、.NET Framework version 2.0新しく追加されたものです。

ファイル転送プロトコル (FTP: File Transfer Protocol) クライアント実装ます。

名前空間: System.Net
アセンブリ: System (system.dll 内)
構文構文

Public NotInheritable Class
 FtpWebRequest
    Inherits WebRequest
Dim instance As FtpWebRequest
public sealed class FtpWebRequest : WebRequest
public ref class FtpWebRequest sealed : public
 WebRequest
public final class FtpWebRequest extends WebRequest
public final class FtpWebRequest extends
 WebRequest
解説解説

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 FrameworkFTP サーバーログインし (Credentials プロパティ設定されているユーザー名パスワード使用)、その後現在のディレクトリ<UserLoginDirectory>/path設定されます。

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

注意に関するメモ注意

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

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();
}
.NET Framework のセキュリティ.NET Frameworkセキュリティ
継承階層継承階層
System.Object
   System.MarshalByRefObject
     System.Net.WebRequest
      System.Net.FtpWebRequest
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
FtpWebRequest メンバ
System.Net 名前空間
FtpWebResponse
FtpStatusCode 列挙
WebRequestMethods.Ftp
WebRequest
WebResponse
WebClient


このページでは「.NET Framework クラス ライブラリ リファレンス」からFtpWebRequest クラスを検索した結果を表示しています。
Weblioに収録されているすべての辞書からFtpWebRequest クラスを検索する場合は、下記のリンクをクリックしてください。
 全ての辞書からFtpWebRequest クラスを検索

英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「FtpWebRequest クラス」の関連用語

FtpWebRequest クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



FtpWebRequest クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS