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

다음 코드 예제에서는 사용 하 여 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 사용하지 않는 것이 좋습니다. 에 대한 자세한 내용과 대안은 FtpWebRequestGitHub에서 WebRequest를 사용하면 안 됨을 참조하세요.

FtpWebRequestinstance 가져오려면 메서드를 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 FTP 서버에 로그인합니다(속성에서 설정한 Credentials 사용자 이름 및 암호 사용). 그러면 현재 디렉터리가 로 <UserLoginDirectory>/path설정됩니다.

서버에 대한 유효한 사용자 이름과 암호가 있어야 합니다. 그렇지 않으면 서버에서 익명 로그온을 허용해야 합니다. 속성을 설정하여 서버에 연결하는 데 사용되는 자격 증명을 Credentials 지정하거나 메서드에 UserInfo 전달된 URI 부분에 포함할 Create 수 있습니다. URI Credentials 에 정보를 포함하는 UserInfo 경우 속성은 지정된 사용자 이름 및 암호 정보를 사용하여 새 네트워크 자격 증명으로 설정됩니다.

주의

속성true이 이 EnableSsl 아니면 사용자 이름 및 암호 정보를 포함한 모든 데이터와 명령이 서버로 명확한 텍스트로 전송됩니다. 네트워크 트래픽을 모니터링하는 사람은 누구나 자격 증명을 보고 이를 사용하여 서버에 연결할 수 있습니다. 자격 증명이 필요하고 SSL(Secure Sockets Layer)을 지원하는 FTP 서버에 연결하는 경우 를 로 true설정 EnableSsl 해야 합니다.

FTP 리소스에 액세스해야 WebPermission 합니다. 그렇지 않으면 예외가 SecurityException throw됩니다.

속성을 구조체에 정의된 WebRequestMethods.Ftp 값으로 설정 Method 하여 서버에 보낼 FTP 명령을 지정합니다. 텍스트 데이터를 전송하려면 속성을 기본값(true)false에서 로 변경 UseBinary 합니다. 자세한 내용 및 제한 사항은 을 참조하세요 Method.

개체를 FtpWebRequest 사용하여 서버에 파일을 업로드하는 경우 메서드 또는 해당 비동기 대응 항목인 및 EndGetRequestStream 메서드를 호출 GetRequestStream 하여 얻은 요청 스트림에 BeginGetRequestStream 파일 콘텐츠를 작성해야 합니다. 요청을 보내기 전에 스트림에 쓰고 스트림을 닫아야 합니다.

요청은 메서드 또는 해당 비동기 대응, 및 EndGetResponse 메서드를 호출 GetResponse 하여 서버로 전송됩니다BeginGetResponse. 요청된 작업이 완료되면 개체가 FtpWebResponse 반환됩니다. 개체는 FtpWebResponse 작업의 상태 서버에서 다운로드한 모든 데이터를 제공합니다.

사용 하 여 서버에 대 한 읽기 또는 쓰기에 대 한 제한 시간 값을 설정할 수 있습니다는 ReadWriteTimeout 속성입니다. 제한 시간을 초과하면 호출 메서드는 로 설정된 TimeoutWebExceptionWebExceptionStatus throw합니다.

FTP 서버에서 파일을 다운로드할 때 명령이 성공하면 요청된 파일의 내용을 응답 개체의 스트림에서 사용할 수 있습니다. 메서드를 호출 GetResponseStream 하여 이 스트림에 액세스할 수 있습니다. 자세한 내용은 FtpWebResponse를 참조하세요.

속성이 Proxy 직접 또는 구성 파일에서 설정된 경우 FTP 서버와의 통신은 지정된 프록시를 통해 이루어집니다. 지정된 프록시가 HTTP 프록시인 경우 , ListDirectoryListDirectoryDetails 명령만 DownloadFile지원됩니다.

다운로드한 이진 콘텐츠만 캐시됩니다. 즉, 속성이 로 설정된 true명령을 UseBinary 사용하여 DownloadFile 받은 콘텐츠입니다.

가능하면 여러 FtpWebRequest개의 기존 연결을 다시 사용합니다.

FTP 프로토콜에 대한 자세한 내용은 RFC 959: 파일 전송 프로토콜을 참조하세요.

속성

AuthenticationLevel

이 요청에 사용되는 인증 및 가장 수준을 나타내는 값을 가져오거나 설정합니다.

(다음에서 상속됨 WebRequest)
CachePolicy

이 요청에 대한 캐시 정책을 가져오거나 설정합니다.

(다음에서 상속됨 WebRequest)
ClientCertificates

FTP 서버에 대해 암호화된 연결을 설정하는 데 사용되는 자격 증명을 가져오거나 설정합니다.

ConnectionGroupName

현재 요청을 보내는 데 사용되는 서비스 지점이 들어 있는 연결 그룹의 이름을 가져오거나 설정합니다.

ContentLength

FtpWebRequest 클래스에서 무시되는 값을 가져오거나 설정합니다.

ContentOffset

이 요청으로 다운로드할 파일의 바이트 오프셋을 가져오거나 설정합니다.

ContentType

항상 NotSupportedException을 버립니다.

CreatorInstance
사용되지 않음.

하위 클래스에서 재정의될 때, 지정된 URI 에 요청하기 위해 인스턴스화된 WebRequest를 만드는 데 사용되는 IWebRequestCreate 클래스에서 파생된 팩터리 개체를 가져옵니다.

(다음에서 상속됨 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를 serialize하는 데 필요한 데이터로 WebRequest 인스턴스를 채웁니다.

(다음에서 상속됨 WebRequest)

적용 대상

추가 정보