About c connection ftp upload download implementation principle and code

  • 2020-05-24 05:29:48
  • OfStack

 
using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Net; 
using System.IO; 
namespace ftponload 
{ 
class Program 
{ 
static void Main(string[] args) 
{ 
// Method of uploading files  
onload("D://outPut.txt"); 
// How to download files  
fload(); 
} 
public static void onload(string file) 
{ 
// structure 1 a web The server's request object  
FtpWebRequest ftp; 
// instantiation 1 File object  
FileInfo f = new FileInfo(file); 
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://192.168.0.150/" + f.Name)); 
// Create a username 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 
{ 
// Gets 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 a username 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 articles: