欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#操作ftp类完整实例

程序员文章站 2022-10-15 09:50:20
本文实例讲述了c#操作ftp类。分享给大家供大家参考。具体如下: using system; using system.collections.generic;...

本文实例讲述了c#操作ftp类。分享给大家供大家参考。具体如下:

using system;
using system.collections.generic;
using system.text;
using system.io;
using system.net;
using system.globalization;
namespace ftptest1
{
 public class ftpweb
 {
 string ftpserverip;
 string ftpremotepath;
 string ftpuserid;
 string ftppassword;
 string ftpuri;
 /// <summary>
 /// 连接ftp
 /// </summary>
 /// <param name="ftpserverip">ftp连接地址</param>
 /// <param name="ftpremotepath">指定ftp连接成功后的当前目录, 如果不指定即默认为根目录</param>
 /// <param name="ftpuserid">用户名</param>
 /// <param name="ftppassword">密码</param>
 public ftpweb(string ftpserverip, string ftpremotepath, string ftpuserid, string ftppassword)
 {
  ftpserverip = ftpserverip;
  ftpremotepath = ftpremotepath;
  ftpuserid = ftpuserid;
  ftppassword = ftppassword;
  ftpuri = "ftp://" + ftpserverip + "/" ;
 }
 static void main() {
  //string file = "c:\\aq3.gifa";
  //fileinfo fileinf = new fileinfo(file);
  //if (!fileinf.exists)
  //{
  // console.writeline(file + " no exists");
  //}
  //else {
  // console.writeline("yes");
  //}
  //console.readline();
  ftpweb fw = new ftpweb("121.11.65.10", "", "aa1", "aa");
  string[] filepaths = { "c:\\aq3.gif1", "c:\\aq2.gif1", "c:\\bsmain_runtime.log" };
  console.writeline(fw.uploadfile(filepaths));
  console.readline();
 }
 //上传文件
 public string uploadfile( string[] filepaths ) {
  stringbuilder sb = new stringbuilder();
  if ( filepaths != null && filepaths.length > 0 ){
  foreach( var file in filepaths ){
   sb.append(upload( file ));
  }
  }
  return sb.tostring();
 }
  /// <summary>
 /// 上传文件
 /// </summary>
 /// <param name="filename"></param>
 private string upload(string filename)
 {
  fileinfo fileinf = new fileinfo(filename);
  if ( !fileinf.exists ){
  return filename + " 不存在!\n";
  }
  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.usepassive = false; //选择主动还是被动模式
  //entering passive mode
  reqftp.contentlength = fileinf.length;
  int bufflength = 2048;
  byte[] buff = new byte[bufflength];
  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)
  {
  return "同步 "+filename+"时连接不上服务器!\n";
  //insert_standard_errorlog.insert("ftpweb", "upload error --> " + ex.message);
  }
  return "";
 }
 /// <summary>
 /// 下载
 /// </summary>
 /// <param name="filepath"></param>
 /// <param name="filename"></param>
 public void download(string filepath, string filename)
 {
  ftpwebrequest reqftp;
  try
  {
  filestream outputstream = new filestream(filepath + "\\" + filename, filemode.create);
  reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(ftpuri + filename));
  reqftp.method = webrequestmethods.ftp.downloadfile;
  reqftp.usebinary = true;
  reqftp.credentials = new networkcredential(ftpuserid, ftppassword);
  ftpwebresponse response = (ftpwebresponse)reqftp.getresponse();
  stream ftpstream = response.getresponsestream();
  long cl = response.contentlength;
  int buffersize = 2048;
  int readcount;
  byte[] buffer = new byte[buffersize];
  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)
  {
  insert_standard_errorlog.insert("ftpweb", "download error --> " + ex.message);
  }
 }
 /// <summary>
 /// 删除文件
 /// </summary>
 /// <param name="filename"></param>
 public void delete(string filename)
 {
  try
  {
  string uri = ftpuri + filename;
  ftpwebrequest reqftp;
  reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(uri));
  reqftp.credentials = new networkcredential(ftpuserid, ftppassword);
  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)
  {
  insert_standard_errorlog.insert("ftpweb", "delete error --> " + ex.message + " 文件名:" + filename);
  }
 }
 /// <summary>
 /// 获取当前目录下明细(包含文件和文件夹)
 /// </summary>
 /// <returns></returns>
 public string[] getfilesdetaillist()
 {
  string[] downloadfiles;
  try
  {
  stringbuilder result = new stringbuilder();
  ftpwebrequest ftp;
  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());
  string line = reader.readline();
  line = reader.readline();
  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;
  insert_standard_errorlog.insert("ftpweb", "getfilesdetaillist error --> " + ex.message);
  return downloadfiles;
  }
 }
 /// <summary>
 /// 获取当前目录下文件列表(仅文件)
 /// </summary>
 /// <returns></returns>
 public string[] getfilelist(string mask)
 {
  string[] downloadfiles;
  stringbuilder result = new stringbuilder();
  ftpwebrequest reqftp;
  try
  {
  reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(ftpuri));
  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)
  {
   if (mask.trim() != string.empty && mask.trim() != "*.*")
   {
   string mask_ = mask.substring(0, mask.indexof("*"));
   if (line.substring(0, mask_.length) == mask_)
   {
    result.append(line);
    result.append("\n");
   }
   }
   else
   {
   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;
  if (ex.message.trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。")
  {
   insert_standard_errorlog.insert("ftpweb", "getfilelist error --> " + ex.message.tostring());
  }
  return downloadfiles;
  }
 }
 /// <summary>
 /// 获取当前目录下所有的文件夹列表(仅文件夹)
 /// </summary>
 /// <returns></returns>
 public string[] getdirectorylist()
 {
  string[] drectory = getfilesdetaillist();
  string m = string.empty;
  foreach (string str in drectory)
  {
  if (str.trim().substring(0, 1).toupper() == "d")
  {
   m += str.substring(54).trim() + "\n";
  }
  }
  char[] n = new char[] { '\n' };
  return m.split(n);
 }
 /// <summary>
 /// 判断当前目录下指定的子目录是否存在
 /// </summary>
 /// <param name="remotedirectoryname">指定的目录名</param>
 public bool directoryexist(string remotedirectoryname)
 {
  string[] dirlist = getdirectorylist();
  foreach (string str in dirlist)
  {
  if (str.trim() == remotedirectoryname.trim())
  {
   return true;
  }
  }
  return false;
 }
 /// <summary>
 /// 判断当前目录下指定的文件是否存在
 /// </summary>
 /// <param name="remotefilename">远程文件名</param>
 public bool fileexist(string remotefilename)
 {
  string[] filelist = getfilelist("*.*");
  foreach (string str in filelist)
  {
  if (str.trim() == remotefilename.trim())
  {
   return true;
  }
  }
  return false;
 }
 /// <summary>
 /// 创建文件夹
 /// </summary>
 /// <param name="dirname"></param>
 public void makedir(string dirname)
 {
  ftpwebrequest reqftp;
  try
  {
  // dirname = name of the directory to create.
  reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(ftpuri + dirname));
  reqftp.method = webrequestmethods.ftp.makedirectory;
  reqftp.usebinary = true;
  reqftp.credentials = new networkcredential(ftpuserid, ftppassword);
  ftpwebresponse response = (ftpwebresponse)reqftp.getresponse();
  stream ftpstream = response.getresponsestream();
  ftpstream.close();
  response.close();
  }
  catch (exception ex)
  {
  insert_standard_errorlog.insert("ftpweb", "makedir error --> " + ex.message);
  }
 }
 /// <summary>
 /// 获取指定文件大小
 /// </summary>
 /// <param name="filename"></param>
 /// <returns></returns>
 public long getfilesize(string filename)
 {
  ftpwebrequest reqftp;
  long filesize = 0;
  try
  {
  reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(ftpuri + filename));
  reqftp.method = webrequestmethods.ftp.getfilesize;
  reqftp.usebinary = true;
  reqftp.credentials = new networkcredential(ftpuserid, ftppassword);
  ftpwebresponse response = (ftpwebresponse)reqftp.getresponse();
  stream ftpstream = response.getresponsestream();
  filesize = response.contentlength;
  ftpstream.close();
  response.close();
  }
  catch (exception ex)
  {
  insert_standard_errorlog.insert("ftpweb", "getfilesize error --> " + ex.message);
  }
  return filesize;
 }
 /// <summary>
 /// 改名
 /// </summary>
 /// <param name="currentfilename"></param>
 /// <param name="newfilename"></param>
 public void rename(string currentfilename, string newfilename)
 {
  ftpwebrequest reqftp;
  try
  {
  reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(ftpuri + currentfilename));
  reqftp.method = webrequestmethods.ftp.rename;
  reqftp.renameto = newfilename;
  reqftp.usebinary = true;
  reqftp.credentials = new networkcredential(ftpuserid, ftppassword);
  ftpwebresponse response = (ftpwebresponse)reqftp.getresponse();
  stream ftpstream = response.getresponsestream();
  ftpstream.close();
  response.close();
  }
  catch (exception ex)
  {
  insert_standard_errorlog.insert("ftpweb", "rename error --> " + ex.message);
  }
 }
 /// <summary>
 /// 移动文件
 /// </summary>
 /// <param name="currentfilename"></param>
 /// <param name="newfilename"></param>
 public void moviefile(string currentfilename, string newdirectory)
 {
  rename(currentfilename, newdirectory);
 }

希望本文所述对大家的c#程序设计有所帮助。