Download file
1 /// <summary> 2 ///Download File3 /// </summary> 4 /// <param name= "filename" ></param> 5 Private Static voidDownLoadFile (stringfilename)6 { 7FtpWebRequest req = (ftpwebrequest) webrequest.create ("ftp://"+ FTPAddress +"/"+filename); 8Req. Method =WebRequestMethods.Ftp.DownloadFile; 9Req. Usebinary =true; TenReq. Usepassive =true; OneReq. Credentials =NewNetworkCredential (Ftpuid, ftppwd); A Try - { - using(FtpWebResponse res =(FtpWebResponse) req. GetResponse ()) the { - stringLocalFile =path.combine (LocalPath, filename); -FileStream fs =NewFileStream (LocalFile, FileMode.Create, FileAccess.Write); - intBuffer =1024x768;//1K Buffering + byte[] B =New byte[buffer]; - inti =0; +Stream stream =Res. GetResponseStream (); A while((i = stream.) Read (b,0, buffer)) >0) at { -Fs. Write (b,0, i); - } - } -Console.WriteLine (filename +"download!"); -Log (filename +"Download Successful"); in - } to Catch(Exception ex) + { - Console.WriteLine (ex. ToString ()); the Log (ex. ToString ()); * } $ finally Panax Notoginseng { - the } +}
Get a list of files
1 /// <summary> 2 ///get a list of FTP files3 /// </summary> 4 /// <returns></returns> 5 Private StaticList<string>getfilelist ()6 { 7list<string> list =Newlist<string>(); 8FtpWebRequest req = (ftpwebrequest) webrequest.create (NewUri ("ftp://"+ FTPAddress +Ftpremotepath)); 9Req. Credentials =NewNetworkCredential (Ftpuid, ftppwd); TenReq. Method =WebRequestMethods.Ftp.ListDirectory; OneReq. Usebinary =true; AReq. Usepassive =true; - Try - { the using(FtpWebResponse res =(FtpWebResponse) req. GetResponse ()) - { - using(StreamReader sr =NewStreamReader (Res. GetResponseStream ())) - { + strings; - while(s = Sr. ReadLine ())! =NULL) + { A at list. ADD (s); - } - } - } - } - Catch(Exception ex) in { - Console.WriteLine (ex. ToString ()); toLog ("failed to download file list:"); + Log (ex. ToString ()); - } the returnlist; * $}
Uploading files
1 Private Static voidUploadFile (stringLocalFile)2 { 3FileInfo fi =NewFileInfo (LocalFile); 4FileStream fs =fi. OpenRead (); 5 LongLength =FS. Length; 6FtpWebRequest req = (ftpwebrequest) webrequest.create ("ftp://"+ ftpaddress + Ftpremotepath +fi. Name); 7Req. Credentials =NewNetworkCredential (Ftpuid, ftppwd); 8Req. Method =WebRequestMethods.Ftp.UploadFile; 9Req. Usebinary =true; TenReq. ContentLength =length; OneReq. Timeout =Ten* +; A Try - { -Stream stream =req. GetRequestStream (); the - intBufferlength =2048;//2K - byte[] B =New byte[Bufferlength]; - inti; + while((i = fs.) Read (b,0, bufferlength)) >0) - { +Stream. Write (b,0, i); A } at Stream. Close (); - Stream. Dispose (); - - } - Catch(Exception ex) - { in Console.WriteLine (ex. ToString ()); - } to +}
"12" ftpwebrequest upload download