FtpRequest

来源:互联网 发布:淘宝客教网站程全集 编辑:程序博客网 时间:2024/05/18 03:42

FtpWebRequest 类

.NET Framework 2.0
其他版本
8(共 14)对本文的评价是有帮助 评价此主题

注意:此类在 .NET Framework 2.0 版中是新增的。

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

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

语法

C#
C++
VB
public sealed class FtpWebRequest : 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 属性设置为新的网络凭据。

Caution note警告

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

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

通过将 Method 属性设置为 WebRequestMethods.Ftp 结构中定义的值,指定要发送到服务器的 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 协议的更多信息,请参见位于 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;}

下面的代码示例演示如何使用 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;}

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

C#
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();            }        }    }}

.NET Framework 安全性

  • WebPermission  用于访问由此请求引用的资源。关联的枚举:Connect。

继承层次结构

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

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

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 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求。

版本信息

.NET Framework

受以下版本支持:2.0

请参见

参考

FtpWebRequest 成员
System.Net 命名空间
FtpWebResponse
FtpStatusCode 枚举
WebRequestMethods.Ftp
WebRequest
WebResponse
WebClient
0 0
原创粉丝点击