注意:這個類別是 .NET Framework 2.0 版的新功能。
實作檔案傳輸通訊協定 (FTP) 用戶端。
命名空間: 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 配置 (例如,"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 屬性,指定連接到伺服器時使用的認證,或將它們包含在 URI 的 UserInfo 部分,傳遞至 Create 方法。如果在 URI 中包含 UserInfo 資訊,Credentials 屬性會設為具有指定使用者名稱和密碼資訊的新網路認證。
警告 |
|---|
| 除非 EnableSsl 屬性為 true,否則所有資料和命令 (包括使用者名稱和密碼資訊) 都會以純文字方式傳送至伺服器。監視網路流量的任何人,都可以檢視這些認證並使用它們來連接到伺服器。如果連接的 FTP 伺服器需要認證並支援 Secure Sockets Layer (SSL),您就應該將 EnableSsl 設為 true。 |
您必須擁有存取 FTP 資源的 WebPermission,否則會擲回 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 伺服器的通訊都會透過指定的 Proxy 進行。如果指定的 Proxy 是 HTTP Proxy,只支援 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();
}
- 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