C# Ftp基础操作

来源:互联网 发布:看韩国电影的软件 编辑:程序博客网 时间:2024/06/08 04:28

C# Ftp基础操作

原创 2013年07月24日 10:07:50

概念

FTP = File Transfer Protocol 文件传输协议

使得主机间可以共享文件。 FTP 使用 TCP 生成一个虚拟连接用于控制信息,然后再生成一个单独的 TCP 连接用于数据传输。控制连接使用类似 TELNET 协议在主机间交换命令和消息。文件传输协议是TCP/IP网络上两台计算机传送文件的协议,FTP是在TCP/IP网络和INTERNET上最早使用的协议之一,它属于网络协议组的应用层。FTP客户机可以给服务器发出命令来下载文件,上传文件,创建或改变服务器上的目录。

FTP使用TCP的服务。

FTP有两种使用模式:主动和被动。

FTP服务一般运行在20和21两个端口。端口20用于在客户端和服务器之间传输数据流,而端口21用于传输控制流,并且是命令通向ftp服务器的进口。


操作

(1)下载

[csharp] view plain copy
  1. public void Download()  
  2. <span style="white-space:pre;"> </span>{  
  3.             FtpWebRequest reqFTP;  
  4.             FtpWebResponse response;  
  5.             Stream ftpStream;  
  6.             FileStream fs;  
  7.   
  8.             foreach (string fileName in fileList)  
  9.             {  
  10.                 FileInfo fileInfo = new FileInfo(fileName);  
  11.                 string name = fileInfo.Name;  
  12.                 fs = new FileStream(string.Format("c:\\ftp\\{0}", name), FileMode.Create);  
  13.                 reqFTP = FtpWebRequest.Create(new Uri(string.Format("ftp://{0}/{1}",auth.Server,fileName))) as FtpWebRequest;  
  14.   
  15.                 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;  
  16.   
  17.                 reqFTP.UseBinary = true;  
  18.   
  19.                 if (!string.IsNullOrEmpty(auth.Name))  
  20.                 {  
  21.                     reqFTP.Credentials = new NetworkCredential(auth.Name, auth.Password);  
  22.                 }  
  23.   
  24.                 response = (FtpWebResponse)reqFTP.GetResponse();  
  25.   
  26.                 ftpStream = response.GetResponseStream();  
  27.   
  28.                 int bufferSize = 2048;  
  29.   
  30.                 int readCount;  
  31.   
  32.                 byte[] buffer = new byte[bufferSize];  
  33.   
  34.                 readCount = ftpStream.Read(buffer, 0, bufferSize);  
  35.   
  36.                 while (readCount > 0)  
  37.                 {  
  38.                     fs.Write(buffer, 0, readCount);  
  39.   
  40.                     readCount = ftpStream.Read(buffer, 0, bufferSize);  
  41.                 }  
  42.   
  43.                 response.Close();  
  44.                 fs.Close();  
  45.                 ftpStream.Close();  
  46.             }  
  47.         }  
原创粉丝点击