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 the D:/n.txt fileFtp://ftp.dygs2b.com
WebClient request = New WebClient ();
// Registration completion event, when the upload is complete, you will receive a notification
request. uploaddatacompleted += New uploaddatacompletedeventhandler (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 the D:/n.txt fileFtp://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 " );
}