热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

C#操作ftp类完整实例

C#操作ftp类完整实例-本文实例讲述了C#操作ftp类。分享给大家供大家参考。具体如下:usingSystem;usingSystem.Collections.Generic;u

本文实例讲述了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;
 /// 
 /// 连接FTP
 /// 
 /// FTP连接地址
 /// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录
 /// 用户名
 /// 密码
 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();
 }
  /// 
 /// 上传文件
 /// 
 /// 
 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 "";
 }
 /// 
 /// 下载
 /// 
 /// 
 /// 
 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);
  }
 }
 /// 
 /// 删除文件
 /// 
 /// 
 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);
  }
 }
 /// 
 /// 获取当前目录下明细(包含文件和文件夹)
 /// 
 /// 
 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;
  }
 }
 /// 
 /// 获取当前目录下文件列表(仅文件)
 /// 
 /// 
 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;
  }
 }
 /// 
 /// 获取当前目录下所有的文件夹列表(仅文件夹)
 /// 
 /// 
 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);
 }
 /// 
 /// 判断当前目录下指定的子目录是否存在
 /// 
 /// 指定的目录名
 public bool DirectoryExist(string RemoteDirectoryName)
 {
  string[] dirList = GetDirectoryList();
  foreach (string str in dirList)
  {
  if (str.Trim() == RemoteDirectoryName.Trim())
  {
   return true;
  }
  }
  return false;
 }
 /// 
 /// 判断当前目录下指定的文件是否存在
 /// 
 /// 远程文件名
 public bool FileExist(string RemoteFileName)
 {
  string[] fileList = GetFileList("*.*");
  foreach (string str in fileList)
  {
  if (str.Trim() == RemoteFileName.Trim())
  {
   return true;
  }
  }
  return false;
 }
 /// 
 /// 创建文件夹
 /// 
 /// 
 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);
  }
 }
 /// 
 /// 获取指定文件大小
 /// 
 /// 
 /// 
 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;
 }
 /// 
 /// 改名
 /// 
 /// 
 /// 
 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);
  }
 }
 /// 
 /// 移动文件
 /// 
 /// 
 /// 
 public void MovieFile(string currentFilename, string newDirectory)
 {
  ReName(currentFilename, newDirectory);
 }

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


推荐阅读
  • 本文详细介绍了如何在Linux系统上安装和配置Smokeping,以实现对网络链路质量的实时监控。通过详细的步骤和必要的依赖包安装,确保用户能够顺利完成部署并优化其网络性能监控。 ... [详细]
  • 本文详细介绍了 Dockerfile 的编写方法及其在网络配置中的应用,涵盖基础指令、镜像构建与发布流程,并深入探讨了 Docker 的默认网络、容器互联及自定义网络的实现。 ... [详细]
  • ImmutableX Poised to Pioneer Web3 Gaming Revolution
    ImmutableX is set to spearhead the evolution of Web3 gaming, with its innovative technologies and strategic partnerships driving significant advancements in the industry. ... [详细]
  • golang常用库:配置文件解析库/管理工具viper使用
    golang常用库:配置文件解析库管理工具-viper使用-一、viper简介viper配置管理解析库,是由大神SteveFrancia开发,他在google领导着golang的 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • 本文详细介绍如何使用Python进行配置文件的读写操作,涵盖常见的配置文件格式(如INI、JSON、TOML和YAML),并提供具体的代码示例。 ... [详细]
  • DNN Community 和 Professional 版本的主要差异
    本文详细解析了 DotNetNuke (DNN) 的两种主要版本:Community 和 Professional。通过对比两者的功能和附加组件,帮助用户选择最适合其需求的版本。 ... [详细]
  • 作为一名新手,您可能会在初次尝试使用Eclipse进行Struts开发时遇到一些挑战。本文将为您提供详细的指导和解决方案,帮助您克服常见的配置和操作难题。 ... [详细]
  • 本文探讨了如何在给定整数N的情况下,找到两个不同的整数a和b,使得它们的和最大,并且满足特定的数学条件。 ... [详细]
  • 本文详细记录了在基于Debian的Deepin 20操作系统上安装MySQL 5.7的具体步骤,包括软件包的选择、依赖项的处理及远程访问权限的配置。 ... [详细]
  • 数据管理权威指南:《DAMA-DMBOK2 数据管理知识体系》
    本书提供了全面的数据管理职能、术语和最佳实践方法的标准行业解释,构建了数据管理的总体框架,为数据管理的发展奠定了坚实的理论基础。适合各类数据管理专业人士和相关领域的从业人员。 ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 将Web服务部署到Tomcat
    本文介绍了如何在JDeveloper 12c中创建一个Java项目,并将其打包为Web服务,然后部署到Tomcat服务器。内容涵盖从项目创建、编写Web服务代码、配置相关XML文件到最终的本地部署和验证。 ... [详细]
  • 如何高效创建和使用字体图标
    在Web和移动开发中,为什么选择字体图标?主要原因是其卓越的性能,可以显著减少HTTP请求并优化页面加载速度。本文详细介绍了从设计到应用的字体图标制作流程,并提供了专业建议。 ... [详细]
author-avatar
经典调剂行570
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有