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,否则所有数据和命令(包括用户名和密码信息)都以明文形式发送到服务器。 监视网络流量的任何人都可以查看你的凭据并使用它们连接到服务器。 如果要连接到需要凭据并支持安全套接字层 (SSL) 的 FTP 服务器,则应将 设置为 EnableSsltrue

必须 WebPermission 访问 FTP 资源;否则会 SecurityException 引发异常。

通过将 属性设置为 Method 结构中 WebRequestMethods.Ftp 定义的值,指定要发送到服务器的 FTP 命令。 若要传输文本数据,请将 UseBinary 属性从其默认值 (true) 更改为 false。 有关详细信息和限制,请参阅 Method

使用 FtpWebRequest 对象将文件上传到服务器时,必须将文件内容写入通过调用 GetRequestStream 方法或其异步对应 BeginGetRequestStream 项 和 EndGetRequestStream 方法获取的请求流。 在发送请求之前,必须写入流并关闭流。

通过调用 GetResponse 方法或其异步对应项 和 EndGetResponse 方法,BeginGetResponse将请求发送到服务器。 请求的操作完成后,将返回 对象 FtpWebResponse 。 对象 FtpWebResponse 提供操作的状态以及从服务器下载的任何数据。

可以使用 属性设置用于读取或写入服务器的 ReadWriteTimeout 超时值。 如果超过超时期限,调用方法将引发 , WebException 并将 WebExceptionStatus 设置为 Timeout

从 FTP 服务器下载文件时,如果命令成功,则请求的文件的内容可在响应对象的流中使用。 可以通过调用 GetResponseStream 方法来访问此流。 有关详细信息,请参阅 FtpWebResponse

Proxy如果直接或在配置文件中设置了 属性,则通过指定的代理与 FTP 服务器的通信。 如果指定的代理是 HTTP 代理,则仅 DownloadFile支持 、 ListDirectoryListDirectoryDetails 命令。

仅缓存下载的二进制内容;也就是说,使用 命令接收的内容,DownloadFileUseBinary并将 属性设置为 true

如果可能,多个 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

获取或设置 Boolean,它指定是否使用 SSL 连接。

Headers

获取空 WebHeaderCollection 对象。

ImpersonationLevel

获取或设置当前请求的模拟级别。

(继承自 WebRequest)
KeepAlive

获取或设置一个 Boolean 值,该值指定在请求完成之后是否关闭到 FTP 服务器的控制连接。

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 服务器发送请求并从 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 作为异步操作返回到 Internet 资源。

(继承自 WebRequest)
GetResponse()

返回 FTP 服务器响应。

GetResponseAsync()

当在子代类中被重写时,将作为异步操作返回对 Internet 请求的响应。

(继承自 WebRequest)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
ToString()

返回表示当前对象的字符串。

(继承自 Object)

显式接口实现

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
已过时.

当在子代类中重写时,使用序列化 WebRequest 所需要的数据来填充 SerializationInfo 实例。

(继承自 WebRequest)

适用于

另请参阅