The recent project requires operations on the FTP server. The implementation is summarized as follows:
It is intended to be summarized in two parts:
1st summary some conventional Ftp operations (such as uploading, downloading, creating, deleting, and transferring files between FTP)
Article 1 summarizes some other Ftp operations (for example, asynchronous uploads, asynchronous downloads, and other operations)
Microsoft. NET Framework 2.0 adds three new classes, which makes it easy for us to operate the file transfer protocol (FTP) server.
FtpWebRequest class: Implements the file transfer protocol (FTP) Client
Public sealed class FtpWebRequest: WebRequest
FtpWebResponse class: Encapsulate the response of the file transfer protocol (FTP) server to the request
Public class FtpWebResponse: WebResponse, IDisposable
WebRequestMethods. Ftp class: Indicates the type of the FTP protocol method that can be used together with the FTP request. This type cannot be inherited.
Public static class Ftp
Class Relationship Diagram
The general procedure for ftp operations is summarized as follows::
Step 1: Obtain the FtpWebRequest instance using the WebRequest. Create method
Step 2: Use WebRequestMethods. Ftp to set the Method attribute of FtpWebRequest and specify the FTP protocol Method type used.
Step 3: Set the Credentials attribute of FtpWebRequest to specify the user name and password.
Step 4: send a request
Step 5: receive response data streams (some ftp operations may not take this step, such as renaming folders)
Step 6: Close the stream
The following code shows the different ftp operations:
1. folder and file information
Key knowledge:
A. The FtpWebRequest class has no public constructor. We use the WebRequest. Create method to obtain the FtpWebRequest instance.
B. Obtain the file list on the Ftp server through WebRequestMethods. Ftp. ListDirectoryDetails (detailed list) or WebRequestMethods. FTP. ListDirectory (short list ).
C. The data returned by the request is in the stream returned by the GetResponseStream method.
D. Please use System. Text. Encoding. Default for character Encoding, or garbled characters in Chinese names
E. FtpWebRequest. Credentials Attribute Set login user name and password
F. FtpWebRequest. UseBinary attribute. true indicates that the server is transmitting binary data. false indicates that the data is text. The default value is true.
G. FtpWebRequest. EnableSsl attribute. If the control and data transmission are encrypted, true is used. Otherwise, false is used. The default value is false.
Instance code:
Obtain the file information on ftp: // 218.16.229.120
Uri uri = new Uri ("ftp: // 218.16.229.120 ");
FtpWebRequest listRequest = (FtpWebRequest) WebRequest. Create (uri );
ListRequest. Method = WebRequestMethods. Ftp. ListDirectoryDetails;
// ListRequest. Method = WebRequestMethods. Ftp. ListDirectory;
String ftpUser = "";
String ftpPassWord = "";
ListRequest. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
FtpWebResponse listResponse = (FtpWebResponse) listRequest. GetResponse ();
Stream responseStream = listResponse. GetResponseStream ();
StreamReader readStream = new StreamReader (responseStream, System. Text. Encoding. Default );
If (readStream! = Null)
{
MessageBox. Show (readStream. ReadToEnd ());
}
MessageBox. Show (string. Format ("status: {0}, {1}", listResponse. StatusCode, listResponse. StatusDescription ));
ListResponse. Close ();
ResponseStream. Close ();
ReadStream. Close ();
The results returned by WebRequestMethods. Ftp. ListDirectoryDetails (detailed list) or WebRequestMethods. Ftp. ListDirectory (short list) are different. See the figure below.
Use WebRequestMethods. ftp. listDirectoryDetails, readStream. the strings returned by ReadToEnd () are complex (different types of Ftp return results in different forms). It is complicated to differentiate the folders and files in the strings and list the codes, so I did not write it out. If you are interested, you can leave a message and send it via email.
2. Obtain the welcome information after ftp login authentication is completed
Key knowledge:
A. FtpWebResponse. WelcomeMessage attribute get the message sent by the FTP server when the authentication is complete
Instance code:
Obtain the welcome information after ftp: // 218.16.229.120 logon identity verification is complete.
Uri uri = new Uri ("ftp: // 218.16.229.120 ");
FtpWebRequest listRequest = (FtpWebRequest) WebRequest. Create (uri );
ListRequest. Method = WebRequestMethods. Ftp. ListDirectoryDetails;
String ftpUser = "";
String ftpPassWord = "";
ListRequest. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
FtpWebResponse listResponse = (FtpWebResponse) listRequest. GetResponse ();
MessageBox. Show (listResponse. WelcomeMessage );
Note: If the FTP server's welcome information contains Chinese characters, an exception may occur when running this Code (the basic connection has been closed: the server has submitted the Protocol ).
Solution: patch Microsoft. NET Framework 2.0 Service Pack 1
3. Rename the Directory
Key knowledge:
A. WebRequestMethods. Ftp. Rename indicates the FTP protocol Method for renaming the directory.
B. New Name of the FtpWebRequest. RenameTo attribute rename
Instance code:
Rename directory a on ftp: // 218.16.229.120/to av
Uri uri = new Uri ("ftp: // 218.16.229.120/");
FtpWebRequest listRequest = (FtpWebRequest) WebRequest. Create (uri );
ListRequest. Method = WebRequestMethods. Ftp. Rename;
String ftpUser = "";
String ftpPassWord = "";
ListRequest. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
ListRequest. RenameTo = "av ";
FtpWebResponse listResponse = (FtpWebResponse) listRequest. GetResponse ();
MessageBox. Show (listResponse. StatusDescription );
4. delete a directory
Key knowledge:
A. WebRequestMethods. Ftp. RemoveDirectory indicates the FTP protocol to remove the directory.
Instance code:
Delete the av folder on ftp: // 218.16.229.120
Uri uri = new Uri ("ftp: // 218.16.229.120/av ");
FtpWebRequest listRequest = (FtpWebRequest) WebRequest. Create (uri );
ListRequest. Method = WebRequestMethods. Ftp. RemoveDirectory;
String ftpUser = "";
String ftpPassWord = "";
ListRequest. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
FtpWebResponse listResponse = (FtpWebResponse) listRequest. GetResponse ();
MessageBox. Show (listResponse. StatusDescription );
5. Create a directory
Key knowledge:
A. WebRequestMethods. Ftp. MakeDirectory indicates the Protocol method for creating a directory on the FTP server.
Instance code:
Create the directory vb on ftp: // 218.16.229.120
Uri uri = new Uri ("ftp: // 218.16.229.120/vb ");
FtpWebRequest listRequest = (FtpWebRequest) WebRequest. Create (uri );
ListRequest. Method = WebRequestMethods. Ftp. MakeDirectory;
String ftpUser = "";
String ftpPassWord = "";
ListRequest. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
FtpWebResponse listResponse = (FtpWebResponse) listRequest. GetResponse ();
MessageBox. Show (listResponse. StatusDescription );
6. Get the file size
Key knowledge:
A. WebRequestMethods. Ftp. GetFileSize indicates the file size to be used to retrieve the FTP server.
B. The length of the stream data can be obtained from the FtpWebResponse. ContentLength attribute.
Instance code:
Obtain the size of the meeting record .doc file on ftp: // 218.16.229.120
Uri uri = new Uri ("ftp: // 218.16.229.120/conference record .doc ");
FtpWebRequest listRequest = (FtpWebRequest) WebRequest. Create (uri );
ListRequest. Method = WebRequestMethods. Ftp. GetFileSize;
String ftpUser = "";
String ftpPassWord = "";
ListRequest. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
FtpWebResponse listResponse = (FtpWebResponse) listRequest. GetResponse ();
MessageBox. Show (string. Format ("file size: {0}", listResponse. ContentLength ));
7. delete an object
Key knowledge:
A. WebRequestMethods. Ftp. DeleteFile indicates that you want to delete files on the FTP server.
Instance code:
Delete the job security .txt file on ftp: // 218.16.229.120
Uri uri = new Uri ("ftp: // 218.16.229.120/workarrangements .txt ");
FtpWebRequest listRequest = (FtpWebRequest) WebRequest. Create (uri );
ListRequest. Method = WebRequestMethods. Ftp. DeleteFile;
String ftpUser = "";
String ftpPassWord = "";
ListRequest. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
FtpWebResponse listResponse = (FtpWebResponse) listRequest. GetResponse ();
MessageBox. Show (string. Format ("Delete status: {0}", listResponse. StatusDescription ));
8. upload files
Key knowledge:
A. WebRequestMethods. Ftp. UploadFile indicates uploading the file to the FTP server.
B. if you use the FtpWebRequest object to upload files to the server, you must write the file content to the request stream by calling FtpWebRequest. getRequestStream method. if the attribute is not set to UploadFile, the stream cannot be obtained.
C. Asynchronous Method (FtpWebRequest. BeginGetRequestStream method and FtpWebRequest. EndGetRequestStream method). I will write the asynchronous upload implementation in the next summary.
Instance code:
Upload File D:/abc.txt to ftp: // 218.16.229.120
Stream requestStream = null;
FileStream fileStream = null;
FtpWebResponse uploadResponse = null;
Try
{
Uri uri = new Uri ("ftp: // 218.16.229.120/abc.txt ");
FtpWebRequest uploadRequest = (FtpWebRequest) WebRequest. Create (uri );
UploadRequest. Method = WebRequestMethods. Ftp. UploadFile;
String ftpUser = "";
String ftpPassWord = "";
UploadRequest. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
RequestStream = uploadRequest. GetRequestStream ();
FileStream = File. Open (@ "D:/abc.txt", FileMode. Open );
Byte [] buffer = new byte [1024];
Int bytesRead;
While (true)
{
BytesRead = fileStream. Read (buffer, 0, buffer. Length );
If (bytesRead = 0)
Break;
RequestStream. Write (buffer, 0, bytesRead );
}
RequestStream. Close ();
UploadResponse = (FtpWebResponse) uploadRequest. GetResponse ();
MessageBox. Show ("Upload complete .");
}
Finally
{
If (uploadResponse! = Null)
UploadResponse. Close ();
If (fileStream! = Null)
FileStream. Close ();
If (requestStream! = Null)
RequestStream. Close ();
}
In fact, using the WebClient. UploadData method, there is a simpler upload method:
WebClient request = new WebClient ();
String ftpUser = "";
String ftpPassWord = "";
Request. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
FileStream myStream = new FileStream (@ "D:/abcd.txt", FileMode. Open, FileAccess. Read );
Byte [] dataByte = new byte [myStream. Length];
MyStream. Read (dataByte, 0, dataByte. Length); // write it to a binary array.
MyStream. Close ();
Request. UploadData ("ftp: // 218.16.229.120/abcd.txt", dataByte );
9. Download an object
Key knowledge:
A. WebRequestMethods. Ftp. DownloadFile indicates the file to be downloaded from the FTP server.
B. When downloading a file from the FTP server, if the command succeeds, the content of the requested file is in the stream of the response object. You can access this stream by calling the FtpWebResponse. GetResponseStream method.
Instance code:
Download the file from ftp: // 218.16.229.120 and save it to d:/abc.txt.
Stream responseStream = null;
FileStream fileStream = null;
StreamReader reader = null;
Try
{
String downloadUrl = "ftp: // 218.16.229.120/abc.txt ";
FtpWebRequest downloadRequest = (FtpWebRequest) WebRequest. Create (downloadUrl );
DownloadRequest. Method = WebRequestMethods. Ftp. DownloadFile;
String ftpUser = "";
String ftpPassWord = "";
DownloadRequest. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
FtpWebResponse downloadResponse = (FtpWebResponse) downloadRequest. GetResponse ();
ResponseStream = downloadResponse. GetResponseStream ();
FileStream = File. Create (@ "d:/" + "abc.txt ");
Byte [] buffer = new byte [1024];
Int bytesRead;
While (true)
{
BytesRead = responseStream. Read (buffer, 0, buffer. Length );
If (bytesRead = 0)
Break;
FileStream. Write (buffer, 0, bytesRead );
}
MessageBox. Show ("Download complete ");
}
Finally
{
If (reader! = Null)
{
Reader. Close ();
}
Else
{
If (responseStream! = Null)
{
ResponseStream. Close ();
}
If (fileStream! = Null)
{
FileStream. Close ();
}
}
}
In fact, using the WebClient. DownloadData method, there is a simpler download method:
Uri uri = new Uri ("ftp: // 218.16.229.120/abc.txt ");
WebClient request = new WebClient ();
String ftpUser = "";
String ftpPassWord = "";
Request. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
Byte [] newFileData = request. DownloadData (uri. ToString ());
FileStream fs = new FileStream (@ "d:/abc.txt", FileMode. OpenOrCreate, FileAccess. Write );
Fs. Write (newFileData, 0, newFileData. Length );
Fs. Close ();
10.2 files transferred between ftp
Key knowledge:
A. after understanding the download and Upload knowledge mentioned above, we can transfer files between two ftp sites. we can regard the transfer file as a download first and then upload. write the downloaded file response stream data to the upload file request stream.
Instance code:
Transfer the "080124-cost expense project adjustment notice" file in the "Group Company notice" Directory of ftp: // 218.58.58.19 to ftp: // 218.16.229.120
String downloadUrl = "ftp: // 218.58.58.19/group company notification/080124-cost expense project adjustment notice ";
FtpWebRequest downloadRequest = (FtpWebRequest) WebRequest. Create (downloadUrl );
DownloadRequest. Method = WebRequestMethods. Ftp. DownloadFile;
String ftpUser = "download ";
String ftpPassWord = "download ";
DownloadRequest. Credentials = new NetworkCredential (ftpUser, ftpPassWord );
String uploadUrl = "ftp: // 218.16.229.120/080124-cost expense project adjustment notice ";
FtpWebRequest uploadRequest = (FtpWebRequest) WebRequest. Create (uploadUrl );
UploadRequest. Method = WebRequestMethods. Ftp. UploadFile;
String ftpUser1 = "exwangsoft ";
String ftpPassWord1 = "exwangsoft ";
UploadRequest. Credentials = new NetworkCredential (ftpUser1, ftpPassWord1 );
FtpWebResponse downloadResponse = (FtpWebResponse) downloadRequest. GetResponse ();
Stream responseStream = downloadResponse. GetResponseStream ();
Stream fileStream = uploadRequest. GetRequestStream ();
Byte [] buffer = new byte [1024];
Int bytesRead;
While (true)
{
// Read the response stream data of ftp: // 218.58.58.19
BytesRead = responseStream. Read (buffer, 0, buffer. Length );
If (bytesRead = 0)
Break;
// Write to the request stream data of ftp: // 218.16.229.120
FileStream. Write (buffer, 0, bytesRead );
}
FileStream. Close ();
FtpWebResponse uploadResponse = null;
UploadResponse = (FtpWebResponse) uploadRequest. GetResponse ();
MessageBox. Show ("complete ");
Author: aierong
For your security, please only open the URL with reliable source
Open website {
Share. safelink. close (); return false;
} "Href =" http://writeblog.csdn.net/# "> cancel
From: http://hi.baidu.com/caicaihui/blog/item/5df1b21c764df48c87d6b61e.html