日期:2014-05-18  浏览次数:20776 次

C# 操作ftp求助
class FtpUpDown
  {
  string ftpServerIP;
  string ftpUserID;
  string ftpPassword;
  FtpWebRequest reqFTP;
  private void Connect(String path)//连接ftp
  {
  // 根据uri创建FtpWebRequest对象
  reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
  // 指定数据传输类型
  reqFTP.UseBinary = true;
  // ftp用户名和密码
  reqFTP.Credentials = new NetworkCredential("spftp", "SPFTPspftp123");
  }
  public FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword)
  {
  this.ftpServerIP = ftpServerIP;
  this.ftpUserID = ftpUserID;
  this.ftpPassword = ftpPassword;

  }
  //都调用这个
  private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
  {
  string[] downloadFiles;
  StringBuilder result = new StringBuilder();

  try
  {
  Connect(path);
  reqFTP.Method = WRMethods;
  WebResponse response = reqFTP.GetResponse();
  StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
  string line = reader.ReadLine();
  while (line != null)
  {
  result.Append(line);
  result.Append("\n ");
  line = reader.ReadLine();
  }
  // to remove the trailing '' ''
  //result.Remove(result.ToString().LastIndexOf(""), 1);
  reader.Close();
  response.Close();
  return result.ToString().Split('\n');
  }
  catch (Exception ex)
  {
  System.Windows.Forms.MessageBox.Show(ex.Message);
  downloadFiles = null;
  return downloadFiles;
  }
  }
  public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
  {
  return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);

  }

  public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表
  {
  return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);

  }


  }
  private void button1_Click(object sender, EventArgs e)
  {
  try
  {
  FtpUpDown ftpUpDown = new FtpUpDown("123.139.155.169", "spftp ", "SPFTPspftp123");
  ftpUpDown.GetFileList("/VAC/SubscribeInfo/81559/add/request");
  string[] str = ftpUpDown.GetFileList("/VAC/SubscribeInfo/81559/add/request");
  listBox1.Items.Clear();
  listBox1.Items.AddRange(str);
  }