问题描述
我要从FTP服务器下载指定文件,比如A.zip大小100kb,等下载成功,这个文件名,大小等信息会被存入一个数据库,等下次下载的时候会去比较,如果两个文件大小一致,就不下了,现在出了一个问题,返回的contentLength始终为-1,但是东西还是有的,可以下载下来,FTP是我自己临时搭建的,系统为win7,网络为政务外网,但是我家里自己测试的时候,用的清华大学FTP,可以返回文件大小,不知道怎么回事,是FTP设置的问题吗?查了MSDN说如果服务器没有返回长度则是-1,怎么搞?privatevoidFileDownload(){FtpWebResponsem_FtpWebResponse=null;try{bLastDownloadFinish=false;for(inti=0;i<downloadList.Count;i++){bFlag=false;WriteLog("准备下载["+downloadList[i]+"]");WriteLog("开始连接FTP...");m_FtpWebRequest=(FtpWebRequest)FtpWebRequest.Create(sIp+sSourceDir+downloadList[i]);m_FtpWebRequest.Credentials=newNetworkCredential(sUser,sPwd);m_FtpWebRequest.Timeout=30000;m_FtpWebRequest.UseBinary=true;m_FtpWebRequest.Method=WebRequestMethods.Ftp.DownloadFile;try{m_FtpWebResponse=(FtpWebResponse)m_FtpWebRequest.GetResponse();}catch(Exceptionex){WriteLog("FTP文件大小查询失败,原因:"+ex.Message);continue;}WriteLog("FTP文件大小查询成功");StreamftpResponseStream=m_FtpWebResponse.GetResponseStream();//sr=newStreamReader(ftpResponseStream);longcontentLength=m_FtpWebResponse.ContentLength;//始终为-1if(!Directory.Exists(sTargetDir)){Directory.CreateDirectory(sTargetDir);}SQLiteDataReaderreader=m_DbSqlite.GetReader(string.Format("select*fromlogwhereFileName='{0}'",downloadList[i]));if(reader.HasRows){bFlag=true;if(reader.Read()){if(reader["Length"].ToString()!=contentLength.ToString()){WriteLog("与原始文件大小不一致,重新下载,大小["+contentLength.ToString()+"]");ReDownLoad(ftpResponseStream,downloadList[i]);}else{WriteLog("已下载过大小一致的此文件,放弃下载!");}}}else{WriteLog("无此文件,开始下载,大小["+contentLength.ToString()+"]");ReDownLoad(ftpResponseStream,downloadList[i]);}reader.Close();ftpResponseStream.Close();//m_FtpWebResponse.Close();//m_FtpWebResponse.Dispose();WriteLog("下载结束!");WriteLog("======================================================");}}catch(Exceptionex){WriteLog("下载线程发生错误:"+ex.Message);}finally{if(m_FtpWebResponse.StatusCode!=FtpStatusCode.ConnectionClosed){m_FtpWebResponse.Close();}bLastDownloadFinish=true;}}privatevoidReDownLoad(StreamftpResponseStream,stringfile){try{try{if(File.Exists(sTargetDir+file+".tmp")){File.Delete(sTargetDir+file+".tmp");}}catch{}m_BeginTime=FormatTime(DateTime.Now);longlength=0;using(FileStreamoutputStream=newFileStream(sTargetDir+file+".tmp",FileMode.Create)){intbufferSize=2048;byte[]buffer=newbyte[bufferSize];List<int>test=newList<int>();intc=0;while((c=ftpResponseStream.ReadByte())!=-1){outputStream.WriteByte(Convert.ToByte(c));}length=outputStream.Length;m_EndTime=FormatTime(DateTime.Now);outputStream.Close();}stringsql="";if(bFlag){sql=string.Format("updatelogsetLength='{0}',BeginTime='{1}',EndTime='{2}'whereFileName='{3}'",length.ToString(),m_BeginTime.ToString(),m_EndTime.ToString(),file);}else{sql=string.Format("insertintolog(FileName,Length,BeginTime,EndTime)values('{0}','{1}','{2}','{3}')",file,length.ToString(),m_BeginTime.ToString(),m_EndTime.ToString());}if(m_DbSqlite.ExcuteSql(sql)!=1){WriteLog("更新数据库信息失败");}WriteLog("下载后文件大小:["+length.ToString()+"]");if(File.Exists(sTargetDir+file)){File.Delete(sTargetDir+file);}File.Move(sTargetDir+file+".tmp",sTargetDir+file);}catch(Exceptionex){WriteLog("下载出错:"+ex.Message);}}
解决方案
解决方案二:
我也造福一下人民吧!outputStream=newFileStream(filePath+"\"+fileName,FileMode.Create);reqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(ftpPath+fileName));reqFTP.Method=WebRequestMethods.Ftp.GetFileSize;reqFTP.UseBinary=true;reqFTP.Credentials=newNetworkCredential(userId,pwd);reqFTP.UsePassive=false;response=(FtpWebResponse)reqFTP.GetResponse();longcl=response.ContentLength;
解决方案三:
///<summary>///获取ftp的文件的长度///</summary>///<paramname="userId"></param>///<paramname="pwd"></param>///<paramname="ftpPath"></param>///<paramname="fileName"></param>///<returns></returns>publiclonggetFileSize(stringuserId,stringpwd,stringftpPath,stringfileName){try{FtpWebRequestreqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(ftpPath+fileName));reqFTP.Method=WebRequestMethods.Ftp.GetFileSize;reqFTP.Credentials=newNetworkCredential(userId,pwd);FtpWebResponseresponse=(FtpWebResponse)reqFTP.GetResponse();longcl=response.ContentLength;response.Close();returncl;}catch(Exceptionex){return-1;}}这句话是关键reqFTP.Method=WebRequestMethods.Ftp.GetFileSize;