C#操作ftp类完整实例

本文实例讲述了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#程序设计有所帮助。

(0)

相关推荐

  • c#操作ftp类分享

    复制代码 代码如下: class ftp{    private string host = null;    private string user = null;    private string pass = null;    private FtpWebRequest ftpRequest = null;    private FtpWebResponse ftpResponse = null;    private Stream ftpStream = null;    privat

  • 分享用于操作FTP的客户端C#类

    这是一个用于操作FTP的客户端C#类,类已经封装好了各种常用的Ftp操作方法,调用非常简单,你不需要关心ftp连接和操作的细节,只要调用这个类里的相关方法就可以了. using System; using System.Net; using System.IO; using System.Text; using System.Net.Sockets; using System.Threading; namespace DotNet.Utilities { public class FTPClie

  • FtpHelper实现ftp服务器文件读写操作(C#)

    最近做了一个项目,需要读取ftp服务器上的文件,于是参考了网上提供的一些帮组方法,使用过程中,出现一些小细节问题,于是本人做了一些修改,拿来分享一下 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Threading; using System.Configuration; na

  • C#操作FTP出现500错误解决办法

    在网上也没有找到好的解决方案,于是自己研究了下给解决了,分享给大家,希望对大家能有所帮助. 一.异常信息 这种情况是因为FTP设置的默认目录引发的,以我现在的项目为例,在程序中我要访问的路径为 ftp://192.168.0.225/2007/35/0037/00001/1.jpg 这个路径,但服务器上设置的默认路径为 E:\pmserver\FTPServer\FTPSERVER , 我们打开相应的ftp目录看下,这个目录下面并没有我要访问的2007这个文件夹 那2007这个文件夹在什么位置呢

  • C#实现FTP客户端的案例

    本文是利用C# 实现FTP客户端的小例子,主要实现上传,下载,删除等功能,以供学习分享使用. 思路: 通过读取FTP站点的目录信息,列出对应的文件及文件夹. 双击目录,则显示子目录,如果是文件,则点击右键,进行下载和删除操作. 通过读取本地电脑的目录,以树状结构展示,选择本地文件,右键进行上传操作. 涉及知识点: FtpWebRequest[实现文件传输协议 (FTP) 客户端] / FtpWebResponse[封装文件传输协议 (FTP) 服务器对请求的响应]Ftp的操作主要集中在两个类中.

  • C#版ftp方法实现类的代码

    /*  FTPFactory.cs  Better view with tab space=4  Written by Jaimon Mathew (jaimonmathew@rediffmail.com)  Rolander,Dan (Dan.Rolander@marriott.com) has modified the  download  method to cope with file name with path information. He also  provided  the 

  • C# FTP,GetResponse(),远程服务器返回错误

    FtpWebRequest类实现ftp功能的一般过程 1.创建一个FtpWebRequest对象,指向ftp服务器的uri 2.设置ftp的执行方法(上传,下载等) 3.给FtpWebRequest对象设置属性(是否支持ssl,是否使用二进制传输等) 4.设置登录验证(用户名,密码) 5.执行请求 6.接收相应流(如果需要的话) 7.如果没有打开的流,则关闭ftp请求 其中一些重要的属性如下: ·Credentials - 指定登录ftp服务器的用户名和密码. ·KeepAlive - 指定连接

  • 关于c#连接ftp进行上传下载实现原理及代码

    复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace ftponload { class Program { static void Main(string[] args) { //上传文件的方法 onload("D://outPut.txt"); //下载文件的方法 fload(); } pub

  • C#实现自定义FTP操作封装类实例

    本文实例讲述了C#实现自定义FTP操作封装类.分享给大家供大家参考.具体如下: 这个C#类封装了FTP的常用操作,包括连接ftp服务器.列表服务器上的目录和文件,从ftp下载文件,上传文件到ftp服务器等等 using System; using System.Text; using System.IO; namespace DotNet.Utilities { public class FTPOperater { #region 属性 private FTPClient ftp; /// <s

  • C# winfrom 模拟ftp文件管理实现代码

    复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; using System.Windows.Forms; namespace ConvertData{    class FtpUpDown    { string ftpServerIP;        string ftpUserID;        string ftp

随机推荐