当前位置:编程学习 > C#/ASP.NET >>

C#从FTP下载文件无法返回文件长度

我要从FTP服务器下载指定文件,比如A.zip  大小100kb,等下载成功,这个文件名,大小等信息会被存入一个数据库,等下次下载的时候会去比较,如果两个文件大小一致,就不下了,现在出了一个问题,返回的contentLength始终为-1,但是东西还是有的,可以下载下来,FTP是我自己临时搭建的,系统为win7,网络为政务外网,但是我家里自己测试的时候,用的清华大学FTP,可以返回文件大小,不知道怎么回事,是FTP设置的问题吗?查了MSDN说如果服务器没有返回长度则是-1,怎么搞?

private void FileDownload()
        {
            FtpWebResponse m_FtpWebResponse = null;

            try
            {
                bLastDownloadFinish = false;
                for (int i = 0; i < downloadList.Count; i++)
                {
                    bFlag = false;
                    WriteLog("准备下载[" + downloadList[i] + "]");
                    WriteLog("开始连接FTP...");
                    m_FtpWebRequest = (FtpWebRequest)FtpWebRequest.Create(sIp + sSourceDir + downloadList[i]);
                    m_FtpWebRequest.Credentials = new NetworkCredential(sUser, sPwd);
                    m_FtpWebRequest.Timeout = 30000;
                    m_FtpWebRequest.UseBinary = true;
                    m_FtpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                    try
                    {
                        m_FtpWebResponse = (FtpWebResponse)m_FtpWebRequest.GetResponse();
                    }
                    catch (Exception ex)
                    {
                        WriteLog("FTP文件大小查询失败,原因:" + ex.Message);
                        continue;
                    }
                    WriteLog("FTP文件大小查询成功");
                    Stream ftpResponseStream = m_FtpWebResponse.GetResponseStream();
                    //sr = new StreamReader(ftpResponseStream);
                    long contentLength = m_FtpWebResponse.ContentLength;   //始终为-1

                    if (!Directory.Exists(sTargetDir))
                    {
                        Directory.CreateDirectory(sTargetDir);
                    }

                    SQLiteDataReader reader = m_DbSqlite.GetReader(string.Format("select * from log where FileName='{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 (Exception ex)
            {
                WriteLog("下载线程发生错误:" + ex.Message);
            }
            finally
            {
                if (m_FtpWebResponse.StatusCode != FtpStatusCode.ConnectionClosed)
                {
                    m_FtpWebResponse.Close();
                }
                bLastDownloadFinish = true;
            }
        }

        private void ReDownLoad(Stream ftpResponseStream, string file)
        {
            try
            {
                try
                {
                    if (File.Exists(sTargetDir + file + ".tmp"))
                    {
                        File.Delete(sTargetDir + file + ".tmp");
                    }
                }
                catch
                {

                }                

                m_BeginTime = FormatTime(DateTime.Now);
                long length = 0;

                using (FileStream outputStream = new FileStream(sTargetDir + file + ".tmp", FileMode.Create))
                {
                    int bufferSize = 2048;
                    byte[] buffer = new byte[bufferSize];

                    List<int> test = new List<int>();

                    int c = 0;
                    while ((c = ftpResponseStream.ReadByte()) != -1)
                    {
                        outputStream.WriteByte(Convert.ToByte(c));
                    }
                    length = outputStream.Length;

                    m_EndTime = FormatTime(DateTime.Now);

                    outputStream.Close();
                }

                string sql = "";
                if (bFlag)
                {
                    sql = string.Format("update log set Length='{0}',BeginTime='{1}',EndTime='{2}' where FileName='{3}'", length.ToString(), m_BeginTime.ToString(), m_EndTime.ToString(), file);
                }
                else
                {
                    sql = string.Format("insert into log(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 (Exception ex)
            {
                WriteLog("下载出错:" + ex.Message);
            }
        }
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,