博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# FTPHelper(搬运)
阅读量:4941 次
发布时间:2019-06-11

本文共 9390 字,大约阅读时间需要 31 分钟。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using System.IO;namespace Utils{    public class FTPHelper    {        ///           /// FTP请求对象          ///           FtpWebRequest request = null;        ///           /// FTP响应对象          ///           FtpWebResponse response = null;        ///           /// FTP服务器地址          ///           public string ftpURI { get; private set; }        ///           /// FTP服务器IP          ///           public string ftpServerIP { get; private set; }        ///           /// FTP服务器默认目录          ///           public string ftpRemotePath { get; private set; }        ///           /// FTP服务器登录用户名          ///           public string ftpUserID { get; private set; }        ///           /// FTP服务器登录密码          ///           public string ftpPassword { get; private set; }        ///             /// 初始化          ///             /// FTP连接地址            /// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录            /// 用户名            /// 密码            public FTPHelper(string ftpServerIP, string ftpRemotePath, string ftpUserID, string ftpPassword)        {            this.ftpServerIP = ftpServerIP;            this.ftpRemotePath = ftpRemotePath;            this.ftpUserID = ftpUserID;            this.ftpPassword = ftpPassword;            this.ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";        }        ///         /// 析构函数        ///         ~FTPHelper()        {            if (response != null)            {                response.Close();                response = null;            }            if (request != null)            {                request.Abort();                request = null;            }        }        ///           /// 建立FTP链接,返回响应对象          ///           /// FTP地址          /// 操作命令          /// 
private FtpWebResponse Open(Uri uri, string ftpMethod) { request = (FtpWebRequest)FtpWebRequest.Create(uri); request.Method = ftpMethod; request.UseBinary = true; request.KeepAlive = false; request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword); return (FtpWebResponse)request.GetResponse(); } /// /// 建立FTP链接,返回请求对象 /// /// FTP地址 /// 操作命令 private FtpWebRequest OpenRequest(Uri uri, string ftpMethod) { request = (FtpWebRequest)WebRequest.Create(uri); request.Method = ftpMethod; request.UseBinary = true; request.KeepAlive = false; request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword); return request; } /// /// 创建目录 /// /// 目录名 public void CreateDirectory(string remoteDirectoryName) { response = Open(new Uri(ftpURI + remoteDirectoryName), WebRequestMethods.Ftp.MakeDirectory); } /// /// 更改目录或文件名 /// /// 当前名称 /// 修改后新名称 public void ReName(string currentName, string newName) { request = OpenRequest(new Uri(ftpURI + currentName), WebRequestMethods.Ftp.Rename); request.RenameTo = newName; response = (FtpWebResponse)request.GetResponse(); } /// /// 切换当前目录 /// /// true:绝对路径 false:相对路径 public void GotoDirectory(string DirectoryName, bool IsRoot) { if (IsRoot) ftpRemotePath = DirectoryName; else ftpRemotePath += "/" + DirectoryName; ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; } /// /// 删除目录(包括下面所有子目录和子文件) /// /// 要删除的带路径目录名:如web/test /* * 例:删除test目录 FTPHelper helper = new FTPHelper("x.x.x.x", "web", "user", "password"); helper.RemoveDirectory("web/test"); */ public void RemoveDirectory(string remoteDirectoryName) { GotoDirectory(remoteDirectoryName, true); var listAll = ListFilesAndDirectories(); foreach (var m in listAll) { if (m.IsDirectory) RemoveDirectory(m.Path); else DeleteFile(m.Name); } GotoDirectory(remoteDirectoryName, true); response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.RemoveDirectory); } /// /// 文件上传 /// /// 本地文件路径 public void Upload(string localFilePath) { FileInfo fileInf = new FileInfo(localFilePath); request = OpenRequest(new Uri(ftpURI + fileInf.Name), WebRequestMethods.Ftp.UploadFile); request.ContentLength = fileInf.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; using (var fs = fileInf.OpenRead()) { using (var strm = request.GetRequestStream()) { contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } } } } /// /// 删除文件 /// /// 要删除的文件名 public void DeleteFile(string remoteFileName) { response = Open(new Uri(ftpURI + remoteFileName), WebRequestMethods.Ftp.DeleteFile); } /// /// 获取当前目录的文件和一级子目录信息 /// ///
public List
ListFilesAndDirectories() { var fileList = new List
(); response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.ListDirectoryDetails); using (var stream = response.GetResponseStream()) { using (var sr = new StreamReader(stream)) { string line = null; while ((line = sr.ReadLine()) != null) { //line的格式如下: //08-18-13 11:05PM
aspnet_client //09-22-13 11:39PM 2946 Default.aspx DateTime dtDate = DateTime.ParseExact(line.Substring(0, 8), "MM-dd-yy", null); DateTime dtDateTime = DateTime.Parse(dtDate.ToString("yyyy-MM-dd") + line.Substring(8, 9)); string[] arrs = line.Split(' '); var model = new FileStruct() { IsDirectory = line.IndexOf("
") > 0 ? true : false, CreateTime = dtDateTime, Name = arrs[arrs.Length - 1], Path = ftpRemotePath + "/" + arrs[arrs.Length - 1] }; fileList.Add(model); } } } return fileList; } ///
/// 列出当前目录的所有文件 /// public List
ListFiles() { var listAll = ListFilesAndDirectories(); var listFile = listAll.Where(m => m.IsDirectory == false).ToList(); return listFile; } ///
/// 列出当前目录的所有一级子目录 /// public List
ListDirectories() { var listAll = ListFilesAndDirectories(); var listFile = listAll.Where(m => m.IsDirectory == true).ToList(); return listFile; } ///
/// 判断当前目录下指定的子目录或文件是否存在 /// ///
指定的目录或文件名 public bool IsExist(string remoteName) { var list = ListFilesAndDirectories(); if (list.Count(m => m.Name == remoteName) > 0) return true; return false; } ///
/// 判断当前目录下指定的一级子目录是否存在 /// ///
指定的目录名 public bool IsDirectoryExist(string remoteDirectoryName) { var listDir = ListDirectories(); if (listDir.Count(m => m.Name == remoteDirectoryName) > 0) return true; return false; } ///
/// 判断当前目录下指定的子文件是否存在 /// ///
远程文件名 public bool IsFileExist(string remoteFileName) { var listFile = ListFiles(); if (listFile.Count(m => m.Name == remoteFileName) > 0) return true; return false; } ///
/// 下载 /// ///
下载后的保存路径 ///
要下载的文件名 public void Download(string saveFilePath, string downloadFileName) { using (FileStream outputStream = new FileStream(saveFilePath + "\\" + downloadFileName, FileMode.Create)) { response = Open(new Uri(ftpURI + downloadFileName), WebRequestMethods.Ftp.DownloadFile); using (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); } } } } } public class FileStruct { ///
/// 是否为目录 /// public bool IsDirectory { get; set; } ///
/// 创建时间 /// public DateTime CreateTime { get; set; } ///
/// 文件或目录名称 /// public string Name { get; set; } ///
/// 路径 /// public string Path { get; set; } }}
View Code

 

转载于:https://www.cnblogs.com/ariter/p/6112581.html

你可能感兴趣的文章
设置登录MacOSX WebView 对 iframe 设置cookie 有可能失败
查看>>
Debian下的'aptitude update'失败处理
查看>>
gcc 常用命令-Wall
查看>>
落实制度靠流程<摘自平安50万人的执行力>
查看>>
Citrix 服务器虚拟化之一 网络部署Xenserver 6.2
查看>>
java连接mysql批量写入数据
查看>>
回顾 Exchange 2007 SCC 安装-供需要的人参考!
查看>>
.Net下SQLite的DBHelp
查看>>
分布式文件系统之GPFS
查看>>
HDU 4577 X-Boxes
查看>>
开发者必备的6款源码搜索引擎
查看>>
绝杀600元以下智能手机的夏新小V二代-专栏-速途网
查看>>
Backbone模型
查看>>
Android LayoutInflater的使用
查看>>
阿里面试的一点感受
查看>>
Redis-持久化
查看>>
Android自定义UI
查看>>
您该选择PRINCE2 还是 PMP认证
查看>>
ActionBar +Tab+ViewPager +Fragment 支持侧滑动完成办税工具的页面展示
查看>>
诺基亚S40手机联系人导入安卓手机
查看>>