mofdan 发表于 2015-5-26 09:44:26

使用FtpWebRequest 类操作(上传、下载和删除)FTP上的XML文件

  使用如下类来实现ftp上操作xml遇到如下问题:
  1、在公司内网中的服务器上搭建ftp来操作,一切正常;但是,当连接客户的机器的时候,出现乱码;
  2、加上WebProxy后,客户端是xml格式的,下载到本地却是html格式的;
也不晓得问题到底出在哪里?。。。。
  分析客户的ftp和内网中ftp的区别:
  客户方的ftp是采用非标准的ssl端口连接,所以需要开启相应的ssl端口;(已开启了的)
  还请阅读本篇文章的高手多多指点下了~~!
  public class FtpWeb_Delete
    {
      private static log4net.ILog log = log4net.LogManager.GetLogger(typeof(FtpWeb_Delete));
      string ftpServerIP;
      string ftpRemotePath;
      string ftpOutPutPath;
      string ftpUserID;
      string ftpPassword;
      string ftpURI;
      //string proxyName;
      //string proxyPass;
      private WebProxy _proxy = null;
      public WebProxy proxy
      {
            get
            {
                return _proxy;
            }
            set
            {
                _proxy = value;
            }
      }
  ///
      /// 连接FTP
      ///
      /// FTP连接地址
      /// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录
      /// 用户名
      /// 密码
      public FtpWeb_Delete(string FtpServerIP, string FtpRemotePath, string FtpOutPutPath, string FtpUserID, string FtpPassword)
      {
            ftpServerIP = FtpServerIP;
            ftpRemotePath = FtpRemotePath;
            ftpOutPutPath = FtpOutPutPath;
            ftpUserID = FtpUserID;
            ftpPassword = FtpPassword;
            ftpURI = "ftp://" + ftpServerIP + "/";
            //this._proxy = objProxy;
            //objProxy.Credentials = new NetworkCredential(this.proxyName,this.proxyPass);
      }
  ///
      /// 上传
      ///
      ///
      public void Upload(string filename)
      {
            FileInfo fileInf = new FileInfo(filename);
            string uri = GotoDirectory(ftpOutPutPath, true) + fileInf.Name;
            //string uri = ftpURI + fileInf.Name;
            FtpWebRequest reqFTP;
  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.Credentials = new NetworkCredential(this.proxyName,this.proxyPass);
            if (this._proxy != null)
            {
                reqFTP.Proxy = this._proxy;
            }
            reqFTP.ContentLength = fileInf.Length;
            int buffLength = 2048;
            byte[] buff = new byte;
            int contentLen;
            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                  strm.Write(buff, 0, contentLen);
                  contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                log.Error("FtpWeb,Upload Error -->", ex);
            }
      }
  ///
      /// 下载
      ///
      ///
      ///
      public void Download(string filePath, string fileName)
      {
            FtpWebRequest reqFTP;
            try
            {
                string uri = GotoDirectory(ftpRemotePath, true) + fileName;
                FileStream outputStream = new FileStream(filePath + fileName, FileMode.Create);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                if (this._proxy != null)
                {
                  reqFTP.Proxy = this._proxy;
                }
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte;
  readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                  outputStream.Write(buffer, 0, readCount);
                  readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
  ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                log.Error("FtpWeb,Download Error --> ", ex);
            }
      }
  ///
      /// 删除文件
      ///
      ///
      public void Delete(string fileName)
      {
            try
            {
                string uri = GotoDirectory(ftpRemotePath, true) + "/" + fileName;
                //string uri = ftpURI + fileName;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                //reqFTP.EnableSsl = true;//用户名加密
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
  string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                log.Error("FtpWeb,Delete Error --> ", ex);
  }
      }
  ///
      /// 获取当前目录下明细(包含文件和文件夹)
      ///
      ///
      public string[] GetFilesDetailList()
      {
            string[] downloadFiles;
            try
            {
                StringBuilder result = new StringBuilder();
                FtpWebRequest ftp;
                //ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
                ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
                ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string line = reader.ReadLine();
                while (line != null)
                {
                  result.Append(line);
                  result.Append("\n");
                  line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf("\n"), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                downloadFiles = null;
                log.Error("FtpWeb,GetFilesDetailList Error --> ", ex);
                return downloadFiles;
            }
      }
      ///
      /// 获取文件
      ///
      ///
  public string[] GetFileList()
      {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            string uri = GotoDirectory(ftpRemotePath, true);
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                  result.Append(line);
                  result.Append("\n");
                  line = reader.ReadLine();
                }
                // to remove the trailing 'n'
                if (result.Length != 0)
                {
                  result.Remove(result.ToString().LastIndexOf('\n'), 1);//提醒
                }
                reader.Close();
                response.Close();
                if (result.Length != 0)
                {
                  return result.ToString().Split('\n');
                }
                else
                {
                  return null;
                }
  }
            catch (Exception ex)
            {
                log.Error("FtpWeb,GetFileList Error --> ", ex);
                downloadFiles = null;
                return downloadFiles;
            }
      }
  ///
      /// 获取当前目录下所有的文件夹列表(仅文件夹)
      ///
      ///
      public string[] GetDirectoryList()
      {
            string[] drectory = GetFilesDetailList();
            string m = string.Empty;
            foreach (string str in drectory)
            {
                int dirPos = str.IndexOf("");
                if (dirPos > 0)
                {
                  /*判断 Windows 风格*/
                  m += str.Substring(dirPos + 5).Trim() + "\n";
                }
                else if (str.Trim().Substring(0, 1).ToUpper() == "D")
                {
                  /*判断 Unix 风格*/
                  string dir = str.Substring(54).Trim();
                  if (dir != "." && dir != "..")
                  {
                        m += dir + "\n";
                  }
                }
            }
  char[] n = new char[] { '\n' };
            return m.Split(n);
      }
  ///
      /// 判断当前目录下指定的文件是否存在
      ///
      /// 远程文件名
      public bool FileExist(string RemoteFileName)
      {
            string[] fileList = GetDirectoryList();
            foreach (string str in fileList)
            {
                if (str.Trim() == RemoteFileName.Trim())
                {
                  return true;
                }
            }
            return false;
      }
  ///
      /// 切换当前目录
      ///
      ///
      /// true 绝对路径   false 相对路径
      public string GotoDirectory(string DirectoryName, bool IsRoot)
      {
            if (IsRoot)
            {
                ftpRemotePath = DirectoryName;
            }
            else
            {
                ftpRemotePath += DirectoryName + "/";
            }
            ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
            return ftpURI;
      }
页: [1]
查看完整版本: 使用FtpWebRequest 类操作(上传、下载和删除)FTP上的XML文件