1 ftp (File Transfer Protocol): 文件傳輸協議服務器
2 原理: 基於TCP生成虛擬鏈接信息控制器(帳戶,密碼,權限),再另外基於tcp生成文件傳輸控制器。網絡
3 開發基礎知識tcp
下載:將文件從其餘的遠程主機(服務器)複製到本地計算機的過程server
上傳:將本地文件複製到遠程主機(服務器)的過程blog
a URL ,URI,URN資源
URL 統一資源定位符開發
URL格式 :scheme://host.port/path?#fragament文件上傳
URI :統一資源標識符string
URN:統一資源名稱it
b 用的類
文件:
Fileinfo ,FileStream,Stream,NetwokStream ,StreamReader
網絡:WebCilent RequestWeb ,WebResponse, FtpWebRequest
c 下載文件和上傳文件的過程
上傳
//上傳文件
public void UpLoad(string pathname) {
FileInfo finf = new FileInfo(pathname);
//實現文件傳輸協議
FtpWebRequest reqftp;
reqftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp:\\"+ftpserverIP+"/"+pathname));
//建立通訊憑證
reqftp.Credentials = new NetworkCredential(uname,upwd);
//去掉包活技術
reqftp.KeepAlive = false;
//爲上傳的方法
reqftp.Method = WebRequestMethods.Ftp.UploadFile;
reqftp.UseBinary = true;
//設置上傳文件的大小
reqftp.ContentLength = finf.Length;
int buffer = 2048;
byte [] dat=new byte[buffer];
int contentlent;
//上傳數據
FileStream fs = finf.OpenRead();
try
{
Stream strm = reqftp.GetRequestStream();
//讀取數據流
contentlent = fs.Read(dat, 0, buffer);
while (contentlent != 0)
{
strm.Write(dat,0,contentlent);
contentlent = fs.Read(dat, 0, buffer);
}
//結束關閉數據流
strm.Close();
fs.Close();
}
catch (IOException ioe)
{
MessageBox.Show(ioe.Message+"文件上傳出錯");
}
}
下載
//下載文件
public void DownLoad(string select,string fname) {
FtpWebRequest reqftp;
try
{
FileStream output = new FileStream(fname, FileMode.Create);
reqftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://"+ftpserverIP+"/"+fname));
reqftp.Method = WebRequestMethods.Ftp.DownloadFile;
reqftp.UseBinary = true;
reqftp.Credentials = new NetworkCredential(uname,upwd);
//響應數據
FtpWebResponse response = (FtpWebResponse)reqftp.GetResponse();
Stream ftpstream = response.GetResponseStream();
long cl = response.ContentLength;
int buffersize = 2048;
int readcount;
byte[] buffer = new byte[buffersize];
readcount = ftpstream.Read(buffer,0,buffersize);
//繼續讀取數據
while (readcount > 0)
{
output.Write(buffer,0,readcount); readcount = ftpstream.Read(buffer, 0, buffersize); } //關閉數據流 output.Close(); ftpstream.Close(); } catch(Exception e) { } }