欢迎来到天天文库
浏览记录
ID:42603384
大小:19.69 KB
页数:19页
时间:2019-09-18
《c# 实现ftp下载》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、publicstringDownload(stringfilePath,stringfileName)////上面的代码实现了从ftp服务器下载文件的功能{try{StringonlyFileName=Path.GetFileName(fileName);stringnewFileName=filePath+"\"+onlyFileName;if(File.Exists(newFileName)){return"本地文件"+newFileName+"已存在,无法下载";}stringurl="ftp://"+ft
2、pServerIP+"/"+fileName;Connect(url);//连接reqFTP.Credentials=newNetworkCredential(ftpUserID,ftpPassword);FtpWebResponseresponse=(FtpWebResponse)reqFTP.GetResponse();StreamftpStream=response.GetResponseStream();longcl=response.ContentLength;intbufferSize=2048;int
3、readCount;byte[]buffer=newbyte[bufferSize];readCount=ftpStream.Read(buffer,0,bufferSize);FileStreamoutputStream=newFileStream(newFileName,FileMode.Create);while(readCount>0){outputStream.Write(buffer,0,readCount);readCount=ftpStream.Read(buffer,0,bufferSize);}
4、ftpStream.Close();outputStream.Close();response.Close();return"";}catch(Exceptionex){return"因"+ex.Message+",无法下载";}}C#codestringTempFolderPath=System.Configuration.ConfigurationManager.AppSettings["TempFolderPath"].ToString();//本地保存目录stringFtpUserName=System.C
5、onfiguration.ConfigurationManager.AppSettings["FtpUserName"].ToString();stringFtpPassWord=System.Configuration.ConfigurationManager.AppSettings["FtpPassWord"].ToString();stringLocalFileExistsOperation=System.Configuration.ConfigurationManager.AppSettings//是否允许
6、写入["LocalFileExistsOperation"].ToString();Uriuri=newUri("202.156.37.21");stringFileName=Path.GetFullPath(TempFolderPath)+Path.DirectorySeparatorChar.ToString()+Path.GetFileName(uri.LocalPath);//创建一个文件流FileStreamfs=null;StreamresponseStream=null;try{//创建一个与FTP服
7、务器联系的FtpWebRequest对象FtpWebRequestrequest=(FtpWebRequest)WebRequest.Create(uri);//设置请求的方法是FTP文件下载request.Method=WebRequestMethods.Ftp.DownloadFile;//连接登录FTP服务器request.Credentials=newNetworkCredential(FtpUserName,FtpPassWord);//获取一个请求响应对象FtpWebResponseresponse=(
8、FtpWebResponse)request.GetResponse();//获取请求的响应流responseStream=response.GetResponseStream();//判断本地文件是否存在,如果存在,则打开和重写本地文件if(File.Exists(FileName)){if(LocalFileExistsOperation=="write
此文档下载收益归作者所有