FtpWebRequest 类
.NET Framework 类库
FtpWebRequest 类

更新:2007 年 11 月

实现文件传输协议 (FTP) 客户端。

命名空间:  System.Net
程序集:  System(在 System.dll 中)

Visual Basic(声明)
Public NotInheritable Class FtpWebRequest _
    Inherits WebRequest
Visual Basic (用法)
Dim instance As FtpWebRequest
C#
public sealed class FtpWebRequest : WebRequest
Visual C++
public ref class FtpWebRequest sealed : public WebRequest
J#
public final class FtpWebRequest extends WebRequest
JScript
public final class FtpWebRequest extends WebRequest

若要获得 FtpWebRequest 的实例,请使用 Create 方法。还可以使用 WebClient 类将信息上载到 FTP 服务器或从 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 属性来指定用于连接服务器的凭据,也可以将它们包含在传递给 Create 方法的 URI 的 UserInfo 部分中。如果 URI 中包含 UserInfo 信息,则使用指定的用户名和密码信息将 Credentials 属性设置为新的网络凭据。

警告:

除非 EnableSsl 属性是 true,否则所有数据和命令(包括您的用户名和密码信息)都会以明文形式发送到服务器。监视网络流量的任何人都可以查看凭据并使用它们连接服务器。如果要连接的 FTP 服务器要求凭据并支持安全套接字层 (SSL),则应将 EnableSsl 设置为 true

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

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

如果使用 FtpWebRequest 对象向服务器上载文件,则必须将文件内容写入请求流,请求流是通过调用 GetRequestStream 方法或其异步对应方法(BeginGetRequestStreamEndGetRequestStream 方法)获取的。必须写入流并在发送请求之前关闭该流。

请求是通过调用 GetResponse 方法或其异步对应方法(BeginGetResponseEndGetResponse 方法)发送到服务器的。请求的操作完成时,会返回一个 FtpWebResponse 对象。FtpWebResponse 对象提供操作的状态以及从服务器下载的所有数据。

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

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

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

仅缓存已下载的二进制内容;也就是说,使用 UseBinary 属性设置为 trueDownloadFile 命令收到内容。

如果可能,多个 FtpWebRequest 重用现有连接。

有关 FTP 协议的更多信息,请参见位于 http://www.rfc-editor.org/ 上的 RFC 959“File Transfer Protocol”(文件传输协议)。

下面的代码示例演示如何从 FTP 服务器上删除文件。

C#
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;
}
Visual C++
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;
}
J#
public static boolean 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://someHost.com/someFile.txt.
    // 
    if (!(serverUri.get_Scheme().Equals(Uri.UriSchemeFtp))) {
        return false;
    }
    // Get the object used to communicate with the server.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
    request.set_Method(WebRequestMethods.Ftp.DeleteFile);

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    Console.WriteLine("Delete status: {0}", 
        response.get_StatusDescription());

    response.Close();
    return true;
} //DeleteFileOnServer

下面的代码示例演示如何使用 WebClient 类从 FTP 服务器下载文件。

C#
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;
}
Visual C++
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;
}
J#
public static boolean DisplayFileFromServer(Uri serverUri)
{
    // The serverUri parameter should start with the ftp:// scheme.
    if (!(serverUri.get_Scheme().Equals(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.set_Credentials(new NetworkCredential("anonymous",
        "janeDoe@contoso.com"));
    try {
        ubyte newFileData[] = request.DownloadData(serverUri.ToString());
        String fileString = 
            System.Text.Encoding.get_UTF8().GetString(newFileData);
        Console.WriteLine(fileString);
    }
    catch (WebException e) {
        Console.WriteLine(e.ToString());
    }
    return true;
} //DisplayFileFromServer

下面的代码示例演示如何使用异步操作将文件上载到 FTP 服务器。

C#
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();
            }
        }
    }
}
Visual C++
#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();
}
J#
package Examples.System.Net;
import System.*;
import System.Net.*;
import System.Threading.*;
import System.IO.*;

public class FtpState
{
    private ManualResetEvent wait;
    private FtpWebRequest request;
    private String fileName;
    private System.Exception operationException = null;
    private String status;

    public FtpState()
    {
        wait = new ManualResetEvent(false);
    } //FtpState

    /** @property 
     */
    public ManualResetEvent get_OperationComplete()
    {
        return wait;
    } //get_OperationComplete

    /** @property 
     */
    public FtpWebRequest get_Request()
    {
        return request;
    } //FtpWebRequest get_Request

    /** @property 
     */
    public void set_Request(FtpWebRequest value)
    {
        request = value;
    } //set_Request

    /** @property 
     */
    public String get_FileName()
    {
        return fileName;
    } //get_FileName

    /** @property 
     */
    public void set_FileName(String value)
    {
        fileName = value;
    } //set_FileName

    /** @property 
     */
    public System.Exception get_OperationException()
    {
        return operationException;
    } //get_OperationException

    /** @property 
     */
    public void set_OperationException(System.Exception value)
    {
        operationException = value;
    } //set_OperationException

    /** @property 
     */
    public String get_StatusDescription()
    {
        return status;
    } //get_StatusDescription

    /** @property 
     */
    public void set_StatusDescription(String value)
    {
        status = value;
    } //set_StatusDescription
} //FtpState

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) throws System.Exception
    {
        // 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.set_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.set_Credentials(new NetworkCredential("anonymous", 
            "janeDoe@contoso.com"));

        // Store the request in the object that we pass into the
        // asynchronous operations.
        state.set_Request(request);
        state.set_FileName(fileName);

        // Get the event to wait on.
        waitObject = state.get_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.get_OperationException() != null) {
            throw state.get_OperationException();
        }
        else {
            Console.WriteLine("The operation completed - {0}", 
                state.get_StatusDescription());
        }
    } //main

    private static void EndGetStreamCallback(IAsyncResult ar)
    {
        FtpState state = (FtpState)ar.get_AsyncState();
        Stream requestStream = null;

        // End the asynchronous call to get the request stream.
        try {
            requestStream = state.get_Request().EndGetRequestStream(ar);
        }
        // Return exceptions to the main application thread.
        catch (System.Exception e) {
            Console.WriteLine("Could not get the request stream.");
            state.set_OperationException(e);
            state.get_OperationComplete().Set();
            return;
        }

         // Copy the file contents to the request stream.
        final int bufferLength = 2048;
        ubyte buffer[] = new ubyte[bufferLength];
        int count = 0;
        int readBytes = 0;
        FileStream stream = File.OpenRead(state.get_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.", (Int32)count);

        // IMPORTANT: Close the request stream before sending the request.
        requestStream.Close();

        // Asynchronously get the response to the upload request.
        state.get_Request().BeginGetResponse(
            new AsyncCallback(EndGetResponseCallback), state);
    } //EndGetStreamCallback  

    // The EndGetResponseCallback method  
    // completes a call to BeginGetResponse.
    private static void EndGetResponseCallback(IAsyncResult ar)
    {
        FtpState state = (FtpState)ar.get_AsyncState();
        FtpWebResponse response = null;
        try {
            response =(FtpWebResponse)state.get_Request().EndGetResponse(ar);
        }
        // Return exceptions to the main application thread.
        catch (System.Exception e) {
            Console.WriteLine("Error getting response.");
            state.set_OperationException(e);
        }
        state.set_StatusDescription(response.get_StatusDescription());

        // Signal the main application thread that 
        // the operation is complete.
        state.get_OperationComplete().Set();
    } //EndGetResponseCallback
} //AsynchronousFtpUpLoader 
System..::.Object
  System..::.MarshalByRefObject
    System.Net..::.WebRequest
      System.Net..::.FtpWebRequest
此类型的任何公共 static(在 Visual Basic 中为 Shared) 成员都是线程安全的。但不保证所有实例成员都是线程安全的。

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

.NET Framework 和 .NET Compact Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求

.NET Framework

受以下版本支持:3.5、3.0、2.0
社区内容   什么是社区内容?
添加新内容 RSS  批注
Processing
Page view tracker