public bool Upload(string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);            reqFTP.KeepAlive = false;            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;            reqFTP.UseBinary = true;            reqFTP.ContentLength = fileInf.Length;            int buffLength = 2048;            byte[] buff = new byte[buffLength];
            int contentLen;            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                // 每次读文件流的2kb
                contentLen = fs.Read(buff, 0, buffLength);                // 流内容没有结束
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream
                    strm.Write(buff, 0, contentLen);                    contentLen = fs.Read(buff, 0, buffLength);
                }                strm.Close();
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Upload Error");
                return false;
            }        }
以上代码FTP的URL为IP地址时通过,为域名时,在执行到 Stream strm = reqFTP.GetRequestStream();
时会报以下错误
“应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址”
何解?

解决方案 »

  1.   


    private static void UploadFile(string localFile) 

    FileInfo fi = new FileInfo(localFile); 
    FileStream fs = fi.OpenRead(); 
    long length = fs.Length; 
    FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://" + FtpAddress +  FtpRemotePath + fi.Name); 
    req.Credentials = new NetworkCredential(FtpUid, FtpPwd); 
    req.Method = WebRequestMethods.Ftp.UploadFile; 
    req.UseBinary = true; 
    req.ContentLength = length; 
    req.Timeout = 10 * 1000; 
    try 

    Stream stream = req.GetRequestStream(); 
    int BufferLength = 2048; 
    byte[] b = new byte[BufferLength]; 
    int i; 
    while ((i = fs.Read(b, 0, BufferLength)) > 0) 

    stream.Write(b, 0, i); 

    stream.Close(); 
    stream.Dispose();  } 
    catch (Exception ex) 

    Console.WriteLine(ex.ToString()); 
    } } 
      

  2.   

    补充一下:
     reqFTP.UsePassive = true;     
     错误信息:操作超时 reqFTP.UsePassive = false;
     错误信息:应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址还是 Stream stream = req.GetRequestStream(); 
    这句代码报错
      

  3.   

    up help!问题的原因好像是 FtpWebRequest请求地址为ftp公网ip  但返回的却是内网ip
    所以出现以下错误:
    “应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址”请教这个问题该如何解决?
      

  4.   

    参考一个这个using System;
    using log4net;
    using System.Collections;
    using System.Text;
    using System.IO;
    using System.Net;
    using log4net.Config;
    using Chxp.Business;namespace Chxp.Service
    {
       public class FileLib
        {
            #region 属性
            private string fileName = "";
            public string FileName
            {
                get { return fileName; }
                set { fileName = value; }
            }
          
            #endregion  
          
           private static readonly ILog LOG = LogManager.GetLogger(typeof(FileLib));        #region 文件上传
           
           /// <summary>
           /// 上传文件(自动分割)
           /// </summary>
           /// <param name="filePath">待上传的文件全路径名称(@"E:\FTP\ftproot\20070228DQCK.zip")</param>
           /// <param name="hostURL">服务器的地址</param>
           /// <param name="byteCount">分割的字节大小</param>        
           /// <param name="userID">主机用户ID</param>
           /// <param name="cruuent">当前字节指针</param>
           /// <returns>成功返回"";失败则返回错误信息</returns>
            public string UpLoadFile(string filePath, string hostURL, int byteCount,string userID,long cruuent)
            {
                string tmpURL = hostURL;
                byteCount = byteCount * 1024;
                //http://localhost:8080/fism/app?service=fileupload&beanId=com.cfcc.fism.service.upload.CollFileSaveServiceImpl&action=upload&filename=AI1215900000020051130411.zip&userid=test&npos=333
                //action=length            System.Net.WebClient WebClientObj = new System.Net.WebClient();
                FileStream fStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                BinaryReader bReader = new BinaryReader(fStream);
                long length = fStream.Length;           
                string sMsg = "版式上传成功";
                string fileName = filePath.Substring(filePath.LastIndexOf('\\') + 1);           
                try
                {                #region 续传处理
                    byte[] data;
                    if (cruuent > 0)
                    {
                        fStream.Seek(cruuent, SeekOrigin.Current);
                    }
                    #endregion                 #region 分割文件上传
                    for (; cruuent <= length; cruuent = cruuent + byteCount)
                    { 
                        if (cruuent + byteCount > length)  //current>length 是这个吗
                        {
                            data = new byte[Convert.ToInt64((length - cruuent))];
                            bReader.Read(data, 0, Convert.ToInt32((length - cruuent)));
                        }
                        else
                        {
                            data = new byte[byteCount];
                            bReader.Read(data, 0, byteCount);
                        }                    try
                        { 
                            LOG.Debug(data);                        //***
                            hostURL = tmpURL + "&action=upload" + "&filename=" + fileName + "&userid=" + userID + "&npos=" + cruuent.ToString();
                            byte[] byRemoteInfo = WebClientObj.UploadData(hostURL, "POST", data);
                            string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo);                      //  获取返回信息
                            if (sRemoteInfo.Trim() != "")
                            {
                                sMsg =  sRemoteInfo;
                                break;                        }
                        }
                        catch (Exception ex)
                        {
                            sMsg =  ex.ToString();
                            break;
                        }
                    #endregion                }
                }
                catch (Exception ex)
                {
                    sMsg = sMsg + ex.ToString(); 
                }
                try
                { 
                    bReader.Close();
                    fStream.Close();
                }
                catch (Exception exMsg)
                {
                    sMsg =  exMsg.ToString();
                }            GC.Collect();
                return sMsg;
            } 
            #endregion        #region 获取文件大小
           /// <summary>
           /// 获取远程服务器文件字节大小
           /// </summary>
           /// <param name="filePath">待上传的文件全路径名称</param>
           /// <param name="hostURL">服务器的地址</param>
           /// <param name="userID">主机用户ID</param>
           /// <returns>远程文件大小</returns>
            public long GetRemoteFileLength(string filePath, string hostURL, string userID)
           {
               long length = 0; 
               System.Net.WebClient WebClientObj = new System.Net.WebClient();  
               
               string fileName = filePath.Substring(filePath.LastIndexOf('\\') + 1);
               
               hostURL = hostURL +"&action=length" + "&filename=" + fileName + "&userid=" + userID + "&npos=0" ;
               
               byte[] data = new byte[0];
               byte[] byRemoteInfo = WebClientObj.UploadData(hostURL , "POST", data);
               string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo);//主系统没有作异常处理
               try
               {
                   length = Convert.ToInt64(sRemoteInfo);
               }
               catch (Exception exx)
               {
                   LOG.Error("FileLib类GetRemoteFileLength()中length = Convert.ToInt64(sRemoteInfo)语句异常:" + exx.Message);//我们强制处理异常
                   length = 0;
               }
               GC.Collect();           return length;       }       /// <summary>
           /// 获得本地文件字节大小
           /// </summary>
           /// <param name="filePath">本地文件全路径</param>
           /// <returns>本地文件字节大小</returns>
           public long GetLocalFileLength(string filePath)
           {
               long length = 0;
               try
               {
                   string fileName = filePath.Substring(filePath.LastIndexOf('\\') + 1);
                   FileStream s = new FileStream(filePath, FileMode.Open);
                   length = s.Length;
                   s.Close();
               }
               catch(Exception ex)
               {
                   LOG.Error("FileLib类中获取本地文件大小异常:"+ex.Message);
               }
               return length;       }
            #endregion       #region 文件下载
           public bool DownLoadFile(string localPath, string hostURL, int byteCount, string userID, long cruuent)
           {
               
               bool result = true;
               
               
               string tmpURL = hostURL;
              
               byteCount = byteCount * 1024;
               hostURL = tmpURL + "&npos=" + cruuent.ToString();
               
               System.IO.FileStream fs;  
               fs = new FileStream(localPath, FileMode.OpenOrCreate);
               if (cruuent > 0)
               {
                   //偏移指针
                   fs.Seek(cruuent, System.IO.SeekOrigin.Current); 
               }
               System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(hostURL);
               if (cruuent > 0)
               {
                   request.AddRange(Convert.ToInt32(cruuent));    //设置Range值
               }           try
               {
                   //向服务器请求,获得服务器回应数据流
                   System.IO.Stream ns = request.GetResponse().GetResponseStream();               byte[] nbytes = new byte[byteCount];
                   int nReadSize = 0;
                   nReadSize = ns.Read(nbytes, 0, byteCount);
                  
                   while (nReadSize > 0)
                   {
                       fs.Write(nbytes, 0, nReadSize);
                       nReadSize = ns.Read(nbytes, 0, byteCount);
                      
                   }
                   fs.Close();
                   ns.Close();
               }
               catch(Exception ex)
               {
                   LOG.Error("下载" + localPath + "的时候失败!" + "原因是:" + ex.Message);
                   fs.Close();
                   result = false;
               }
                      return result;
             
           }
           #endregion
       }
    }
     
      

  5.   

    谢谢 blogtjf但貌似你这个不是FTP上传吧
      

  6.   

    using System.Net;
    using System.IO;
      

  7.   

    出现这个错误的原因貌似是FTP服务器处于内网之中,
    用公网IP请求时,返回的是内网IP,才报:
    “应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址”这个问题不知道该如何解决?
      

  8.   

    用这个FTP来做,如果你的客户上网使用代理,将会死的很难看
    一使用代理,MS的这个类根本就没有办法使用了。
      

  9.   

    看了些资料是蛮头疼的。
    改用Xceed.Ftp的上传,发现能连接,但无法传送数据。FTP生成0KB的文件用Xceed.Ftp的DEMO试了下   发现连接上后连目录列表都载不下来