Use the ftpwebrequest class to upload files to FTP. First, create an FTP site on the local machine and create a file on another machine .....
Write the FTP address, account, password, and other information in Web. config to facilitate management. Here, the filecontent attribute of fileupload is used to write the file stream to the FTP server.
Use an enumeration to record the file storage method Enum Fileuploadmethod
{
File = 1 ,
FTP = 2
}
Next, we will use the ftpwebrequest class to implement communication with the FTP server.Ftpwebrequest request;
Try
{
Request = (Ftpwebrequest) webrequest. Create (geturi (server, port, path, " FTP " ));
}
Catch
{
Backmsg = " An error occurred while creating the FTP request. " ;
Return False ;
}
Request. Method = Webrequestmethods. FTP. uploadfile;
If (Isanoymous)
{
Request. Credentials = New Networkcredential ( " Anonymous " , Useremail );
}
Else If ( ! String . Isnullorempty (domain ))
{
Request. Credentials = New Networkcredential (username, password, domain );
}
Else
{
Request. Credentials = New Networkcredential (username, password );
}
After the ftpwebrequest object is set up, the rest is to write the file stream to the FTP server. Stream requeststream = Null ;
Bool Success = False ;
Request. contentlength = Inputstream. length;
Try
{
Requeststream = Request. getrequeststream ();
Success = True ;
}
Catch (Exception ex)
{
Success = False ;
If (EX Is Webexception)
{
Webexception Wex = Ex As Webexception;
If (Ftpwebresponse) wex. Response). statuscode = Ftpstatuscode. actionnottakenfileunavailable)
Backmsg = String . Format ( " The specified file path does not exist. The error is \ n \ t {0} " , Ex. Message );
}
Else If (EX Is Protocolviolationexception)
Backmsg = String . Format ( " Protocol wrong: \ n {0} \ n " , Ex. Message );
Else
Backmsg = String . Format ( " Invalidoperation: \ n {0} \ n " , Ex. Message );
}
If (SUCCESS)
{
Try
{
Int Count = 0 ;
Byte [] Buffer = New Byte [ 1024 ];
While (Count = Inputstream. Read (buffer, 0 , 1024 )) > 0 )
{
Requeststream. Write (buffer, 0 , Count );
}
}
Catch (Exception ex)
{
Success = False ;
Backmsg = String . Format ( " Write uploadstream wrong: \ n {0} " , Ex. tostring ());
}
Finally
{
Requeststream. Close ();
Requeststream. Dispose ();
}
}
You can download the complete demo here.