Microsoft. NET Framework 2.0 summarizes File Transfer Protocol (FTP) Operations (asynchronous uploads, downloads, etc.) 2

Source: Internet
Author: User

RelatedArticleNavigation
  1. SQL server2005 Transact-SQL new weapon learning Summary-Summary
  2. Index of flex and fms3 articles
  3. Flexair open-source edition-global free multi-person video chat room, free network remote multi-person Video Conferencing System (jointly developed by flex and fms3) <video chat, conference Development Instance 8>

 

 

InPreviousThe file upload and download operations described in are based on synchronization operations. This article will summarize asynchronous operations.
This article mainly summarizes the implementation methods of WebClient asynchronous uploads and ftpwebrequest asynchronous uploads. In fact, it understands that asynchronous uploads are the same as Asynchronous downloads.

1. asynchronous WebClient upload
Key knowledge:
The WebClient class provides four asynchronous upload methods, which are similar in usage.
WebClient. uploaddataasync Method
Uploads a data buffer to a specified resource.

WebClient. uploadfileasync Method
Uploads a specified local file to a specified resource.

WebClient. uploadstringasync Method
Uploads a specified string to a specified resource.

WebClient. uploadvaluesasync Method
Uploads a specified name/value set to a specified resource.

One method signature is as follows:
Public void uploaddataasync (
Uri address,
String method,
Byte [] data,
Object usertoken
)
Parameters
Address
Uri of the resource that receives data
Method
The HTTP method used to send files to resources. If it is null, the default HTTP value is post, and the default FTP value is stor.
Data
Data buffer to be sent to the Resource
Usertoken
A user-defined object that will be passed to the method called when asynchronous operations are completed

To receive a notification when data upload is complete, you need to implement the WebClient. uploaddatacompleted event, which is triggered every time asynchronous data upload is completed

Summary WebClient asynchronous upload implementation steps:
Step 1: Define WebClient and set attributes
Step 2: register the complete event uploaddatacompleted to complete the callback during upload.
Step 3: Call the uploaddataasync method to start asynchronous file upload
Step 4: upload a file to complete the callback completion event uploaddatacompleted defined method

InstanceCode:
Upload D: \ n.txt file to ftp://ftp.dygs2b.com

WebClient request =   New WebClient ();

//Registration completion event to receive a notification when the upload is complete
Request. uploaddatacompleted+ = NewUploaddatacompletedeventhandler (request_uploaddatacompleted );

StringFtpuser= "A";
StringFtppassword= "B";
Request. Credentials= NewNetworkcredential (ftpuser, ftppassword );

Filestream mystream=   New Filestream ( @" D: \ n.txt " , Filemode. Open, fileaccess. Read );
Byte [] Databyte =   New   Byte [Mystream. Length];
Mystream. Read (databyte, 0 , Databyte. Length ); // Written to a binary array
Mystream. Close ();

URI = New uri ( " ftp://ftp.dygs2b.com/n.txt " );
request. uploaddataasync (Uri, " stor " , databyte, databyte);

VoidRequest_uploaddatacompleted (ObjectSender, uploaddatacompletedeventargs E)
{
//Receive user-defined objects passed by uploaddataasync
Byte[] Databyte=(Byte[]) E. userstate;

// Asynccompletedeventargs. Error attribute to obtain a value indicating an error occurred during the Asynchronous Operation
If (E. Error =   Null )
{
MessageBox. Show ( String . Format ( " Uploaded successfully! File size {0} " , Databyte. Length ));
}
Else
{
MessageBox. Show (E. Error. Message );
}
}

 

 

2. ftpwebrequest asynchronous upload
If you use an ftpwebrequest object to upload a file to the server, you must write the file content to the request stream. synchronous request streams use the getrequeststream method, while asynchronous methods use the begingetrequeststream and endgetrequeststream methods.

The begingetrequeststream method signature is as follows:
Public override iasyncresult begingetrequeststream (
Asynccallback callback,
Object state
)

Parameters
Callback
An asynccallback delegate that references the method to be called when the operation is completed
State
A user-defined object that contains information about the operation. When the operation is completed, this object will be passed to the callback delegate.

The endgetrequeststream method must be called to complete asynchronous operations. Generally, endgetrequeststream is called by the method referenced by callback.

Summary ftpwebrequest asynchronous upload implementation steps:
Step 1: Define ftpwebrequest and set relevant attributes
Step 2: Call the ftpwebrequest. begingetrequeststream method, define the method endgetresponsecallback to be called when the operation is complete, and start to asynchronously open the request content stream for writing.
Step 3: implement the endgetresponsecallback method, in which ftpwebrequest is called. the endgetrequeststream method ends the pending asynchronous operation started by begingetrequeststream, writes the local file stream data to the requeststream, and then ftpwebrequest. the begingetresponse method defines the method endgetresponsecallback to be called when the operation is complete. It starts to send requests asynchronously to the FTP server and receive responses from the FTP server.
Step 4: implement the endgetresponsecallback method. In this method, call the ftpwebrequest. endgetresponse method to end the pending asynchronous operation started by begingetresponse.

Instance code:
Upload D: \ n.txt file to ftp://ftp.dygs2b.com

Uri URI =   New Uri ( " Ftp://ftp.dygs2b.com/n.txt " );

//Define ftpwebrequest and set Related Properties
Ftpwebrequest uploadrequest=(Ftpwebrequest) webrequest. Create (URI );
Uploadrequest. Method=Webrequestmethods. FTP. uploadfile;

string ftpuser = " A " ;
string ftppassword = " B " ;
uploadrequest. credentials = New networkcredential (ftpuser, ftppassword);

//Start opening the requested content stream in asynchronous mode for writing
Uploadrequest. begingetrequeststream (NewAsynccallback (endgetstreamcallback), uploadrequest );

 

Private   Void Endgetstreamcallback (iasyncresult AR)
{
// User-Defined Object, which contains information about the operation. Here, ftpwebrequest is obtained.
Ftpwebrequest uploadrequest = (Ftpwebrequest) Ar. asyncstate;

//End a pending asynchronous operation started by begingetrequeststream
//The endgetrequeststream method must be called to complete asynchronous operations.
//Generally, endgetrequeststream is called by the method referenced by callback.
Stream requeststream=Uploadrequest. endgetrequeststream (AR );

Filestream=File. Open (@"D: \ n.txt", Filemode. Open );

Byte [] Buffer =   New   Byte [ 1024 ];
Int Bytesread;
While ( True )
{
Bytesread = Filestream. Read (buffer, 0 , Buffer. Length );
If (Bytesread =   0 )
Break ;

//Write local file stream data to request stream
Requeststream. Write (buffer,0, Bytesread );
}

Requeststream. Close ();
Filestream. Close ();

//Start sending requests to the FTP server asynchronously and receive responses from the FTP server
Uploadrequest. begingetresponse (NewAsynccallback (endgetresponsecallback), uploadrequest );
}

Private VoidEndgetresponsecallback (iasyncresult AR)
{
Ftpwebrequest uploadrequest=(Ftpwebrequest) Ar. asyncstate;

//End a pending asynchronous operation started by begingetresponse
Ftpwebresponse uploadresponse=(Ftpwebresponse) uploadrequest. endgetresponse (AR );

MessageBox. Show (uploadresponse. statusdescription );
MessageBox. Show ("Upload complete");
}Link to the previous articleMicrosoft. NET Framework 2.0 summarizes File Transfer Protocol (FTP) Operations (upload, download, new, delete, transfer files between FTP, etc.) 1

Http://aierong.cnblogs.com

SQL server2005 Transact-SQL new weapon learning Summary-Summary
Ms SQL database backup and recovery stored procedures (enhanced)
SQL Server Distributed Query essay (sp_addmediaserver) and remote login ing (sp_addmediasrvlogin) use small summary)
Summary of the implementation of ASP. net2.0 internationalization/localization applications (multi-language, multi-cultural page implementation)
WAP development data station (latest update)
Custom Format String (implementation of the three interfaces of iformattable, iformatprovider, and icustomformatter)
Asynchronous programming of mcad learning notes (asynccallback delegation, iasyncresult interface, begininvoke method, and endinvoke method)
Mcad learning notes: Calling class methods through reflection, attention, fields, indexers (2 methods)
Serialization of mcad learning notes (binary and soap serialization)
Delegated re-understanding of mcad learning notes (discussion of Delegate constructor, begininvoke, endinvoke, and invoke4 methods)
Winform development, form display, and form value passing knowledge
Microsoft Windows service using mcad Study Notes
Copy all the objects and files under a certain category to the target category (number of objects)
ASP. NET status management (Summary)

 

 

Favorites and sharing

Add QQ bookmarks to Baidu souzang {
Function onclick ()
{
Window. Open ('HTTP: // myweb.cn.yahoo.com/popadd.html? Url = '+ encodeuricomponent (document. location. href) + '& Title =' + encodeuricomponent (document. title), 'yahoo ', 'scrollbars = Yes, width = 440, Height = 440, Left = 80, Top = 80, status = Yes, resizable = Yes ');
}
} "> Add to Yahoo favorites

RSS subscribe to me What is RSS?




Dongguan. Net Club

Welcome to join

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.