Principle and code of c # connecting to ftp for upload/download

Source: Internet
Author: User

Copy codeThe Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Net;
Using System. IO;
Namespace ftponload
{
Class Program
{
Static void Main (string [] args)
{
// File Upload Method
Onload ("D: // outPut.txt ");
// Method for downloading an object
Fload ();
}
Public static void onload (string file)
{
// Construct a web server request object
FtpWebRequest ftp;
// Instantiate a file object
FileInfo f = new FileInfo (file );
Ftp = (FtpWebRequest) FtpWebRequest. Create (new Uri ("ftp: // 192.168.0.150/" + f. Name ));
// Create a user name and password
Ftp. Credentials = new NetworkCredential ("123", "123 ");
Ftp. KeepAlive = false;
Ftp. Method = WebRequestMethods. Ftp. UploadFile;
Ftp. UseBinary = true;
Ftp. ContentLength = f. Length;
Int buffLength = 20480;
Byte [] buff = new byte [buffLength];
Int contentLen;
Try
{
// Obtain the input stream of the request object
FileStream fs = f. OpenRead ();
Stream sw = ftp. GetRequestStream ();
ContentLen = fs. Read (buff, 0, buffLength );
While (contentLen! = 0)
{
Sw. Write (buff, 0, contentLen );
ContentLen = fs. Read (buff, 0, buffLength );
}
Sw. Close ();
Fs. Close ();
}
Catch (Exception e)
{
Console. WriteLine (e. Message );
}
}
Public static void fload ()
{
FtpWebRequest ftp;
Ftp = (FtpWebRequest) FtpWebRequest. Create (new Uri ("ftp: // 192.168.0.6/connect to the file you specified "));
// Specify the user name and password
Ftp. Credentials = new NetworkCredential ("123", "123456 ");
WebResponse wr = ftp. GetResponse ();
StreamReader sr = new StreamReader (wr. GetResponseStream (), System. Text. Encoding. Default );
String s = sr. ReadLine ();
While (s. Equals (""))
{
S = sr. ReadLine ();
}
}
}
}

Related Article

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.