C#-FTP帮助类相关操作的简单封装

news/2024/9/25 5:52:35/

目录

1、Ftp帮助类的框架封装

2、初始化Ftp连接 

3、检查Ftp连接

4、Ftp文件上传

5、Ftp文件下载

6、获取Ftp上文件/文件夹列表

7、删除Ftp文件

8、删除Ftp文件夹

9、创建Ftp文件夹

10、更改Ftp文件名

11、获取Ftp文件大小


1、Ftp帮助类的框架封装

 public class FtpHelper
{#region FTPConfigstring ftpUri;string ftpUserID;string ftpServerIP;string ftpPassword;string ftpRemotePath;#endregionprivate static Lazy<FtpHelper> instance = new Lazy<FtpHelper>(() => new FtpHelper());public static FtpHelper Default = instance.Value;private FtpHelper(){}}

2、初始化Ftp连接 

        /// <summary>  /// 初始化FTP连接/// </summary>  /// <param name="FtpServerIP">FTP连接地址</param>  /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>  /// <param name="FtpUserID">用户名</param>  /// <param name="FtpPassword">密码</param>  public void InitFtpConnect(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword){ftpServerIP = FtpServerIP;ftpRemotePath = FtpRemotePath;ftpUserID = FtpUserID;ftpPassword = FtpPassword;ftpUri = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";}

3、检查Ftp连接

        /// <summary>/// 检查Ftp连接/// </summary>/// <returns></returns>public bool CheckFtp(){try{FtpWebRequest ftprequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri));// ftp用户名和密码ftprequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;ftprequest.Timeout = 3000;FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();ftpResponse.Close();return true;}catch (Exception){return false;}}

4、Ftp文件上传

        /// <summary>/// Ftp文件上传/// </summary>/// <param name="localfile">本地文件名</param>/// <param name="ftpfile">Ftp文件名</param>/// <param name="pb">进度条</param>/// <exception cref="Exception"></exception>public void Upload(string localfile, string ftpfile, ProgressBar pb = null){FileInfo fileInf = new FileInfo(localfile);FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri + ftpfile));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.Method = WebRequestMethods.Ftp.UploadFile;reqFTP.KeepAlive = false;reqFTP.UseBinary = true;reqFTP.ContentLength = fileInf.Length;if (pb != null){if (pb.Dispatcher.Thread != Thread.CurrentThread)Application.Current.Dispatcher.Invoke(() =>{pb.Maximum = Convert.ToInt32(reqFTP.ContentLength / 2048);pb.Maximum = pb.Maximum + 1;pb.Minimum = 0;pb.Value = 0;});else{pb.Maximum = Convert.ToInt32(reqFTP.ContentLength / 2048);pb.Maximum = pb.Maximum + 1;pb.Minimum = 0;pb.Value = 0;}}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);if (pb != null){if (pb.Dispatcher.Thread != Thread.CurrentThread)Application.Current.Dispatcher.Invoke(() =>{if (pb.Value != pb.Maximum)pb.Value = pb.Value + 1;});else if (pb.Value != pb.Maximum)pb.Value = pb.Value + 1;}contentLen = fs.Read(buff, 0, buffLength);Thread.Sleep(100);}if (pb != null)if (pb.Dispatcher.Thread != Thread.CurrentThread)Application.Current.Dispatcher.Invoke(() =>{pb.Value = pb.Maximum;});elsepb.Value = pb.Maximum;strm.Close();fs.Close();}catch (Exception ex){throw new Exception(ex.Message);}}

5、Ftp文件下载

        /// <summary>/// Ftp文件下载/// </summary>/// <param name="localfilename">本地文件名</param>/// <param name="ftpfileName">Ftp文件名</param>/// <param name="pb">进度条</param>/// <exception cref="Exception"></exception>public void Download(string localfilename, string ftpfileName, ProgressBar pb = null){long fileSize = GetFileSize(ftpfileName);if (pb != null){if (pb.Dispatcher.Thread != Thread.CurrentThread)Application.Current.Dispatcher.Invoke(() =>{pb.Maximum = Convert.ToInt32(fileSize / 2048);pb.Maximum = pb.Maximum + 1;pb.Minimum = 0;pb.Value = 0;});else{pb.Maximum = Convert.ToInt32(fileSize / 2048);pb.Maximum = pb.Maximum + 1;pb.Minimum = 0;pb.Value = 0;}}try{FileStream outputStream = new FileStream(localfilename, FileMode.Create);FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri + ftpfileName));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;reqFTP.UseBinary = true;FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();Stream ftpStream = response.GetResponseStream();int bufferSize = 2048;int readCount;byte[] buffer = new byte[bufferSize];readCount = ftpStream.Read(buffer, 0, bufferSize);while (readCount > 0){outputStream.Write(buffer, 0, readCount);if (pb != null){if (pb.Dispatcher.Thread != Thread.CurrentThread)Application.Current.Dispatcher.Invoke(() =>{if (pb.Value != pb.Maximum)pb.Value = pb.Value + 1;});else if (pb.Value != pb.Maximum)pb.Value = pb.Value + 1;}readCount = ftpStream.Read(buffer, 0, bufferSize);}if (pb != null)if (pb.Dispatcher.Thread != Thread.CurrentThread)Application.Current.Dispatcher.Invoke(() =>{pb.Value = pb.Maximum;});else pb.Value = pb.Maximum;ftpStream.Close();outputStream.Close();response.Close();}catch (Exception ex){File.Delete(localfilename);throw new Exception(ex.Message);}}

6、获取Ftp上文件/文件夹列表

        /// <summary>/// 获取Ftp上文件/文件夹列表/// </summary>/// <param name="ListType">1:文件 2:文件夹 3:文件和文件夹</param>/// <param name="Detail">是否显示详细信息</param>/// <param name="Keyword">关键词</param>/// <returns></returns>/// <exception cref="Exception"></exception>public List<string> GetFileDirectoryList(int ListType, bool Detail, string Keyword = ""){List<string> strs = new List<string>();try{FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri));// ftp用户名和密码reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);if (Detail)reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;elsereqFTP.Method = WebRequestMethods.Ftp.ListDirectory;WebResponse response = reqFTP.GetResponse();StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名string line = reader.ReadLine();while (line != null){if (ListType == 1){if (line.Contains(".")){if (Keyword.Trim() == "*.*" || Keyword.Trim() == ""){strs.Add(line);}else if (line.IndexOf(Keyword.Trim()) > -1){strs.Add(line);}}}else if (ListType == 2){if (!line.Contains(".")){if (Keyword.Trim() == "*" || Keyword.Trim() == ""){strs.Add(line);}else if (line.IndexOf(Keyword.Trim()) > -1){strs.Add(line);}}}else if (ListType == 3){strs.Add(line);}line = reader.ReadLine();}reader.Close();response.Close();return strs;}catch (Exception ex){throw new Exception(ex.Message);}}

7、删除Ftp文件

        /// <summary>/// 删除Ftp文件/// </summary>/// <param name="fileName"></param>/// <exception cref="Exception"></exception>public void DeleteFile(string fileName){try{FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri + fileName));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;reqFTP.KeepAlive = false;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){throw new Exception(ex.Message);}}

8、删除Ftp文件夹

        /// <summary>/// 删除Ftp文件夹/// </summary>/// <param name="urlpath"></param>/// <exception cref="Exception"></exception>public void DeleteDirectory(string urlpath){try{string uri = ftpUri + urlpath;FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.KeepAlive = false;reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;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){throw new Exception(ex.Message);}}

9、创建Ftp文件夹

        /// <summary>/// 创建Ftp文件夹/// </summary>/// <param name="dirName"></param>/// <exception cref="Exception"></exception>public void CreateDir(string dirName){FtpWebRequest reqFTP;try{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){throw new Exception(ex.Message);}}

10、更改Ftp文件名

        /// <summary>/// 更改Ftp文件名/// </summary>/// <param name="currentFilename">当前文件名</param>/// <param name="newFilename">新文件名</param>/// <exception cref="Exception"></exception>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){throw new Exception(ex.Message);}}

11、获取Ftp文件大小

        /// <summary>/// 获取Ftp文件大小/// </summary>/// <param name="ftpfileName">Ftp文件名</param>/// <returns></returns>/// <exception cref="Exception"></exception>public long GetFileSize(string ftpfileName){long fileSize = 0;try{FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri + ftpfileName));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;reqFTP.UseBinary = true;FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();Stream ftpStream = response.GetResponseStream();fileSize = response.ContentLength;ftpStream.Close();response.Close();}catch (Exception ex){throw new Exception(ex.Message);}return fileSize;}


http://www.ppmy.cn/news/1452015.html

相关文章

UNIAPP小程序从入门到精通

第一章> 1、如何创建项目 2、项目的基本结构 3、页面组成&#xff08;wxss可以不用&#xff09; 4、组件的使用 5、协同开发与发布 第二章> 6、WXML页面结构渲染 7、style样式美化 8、a…

【Redis】深入理解 Redis 锁:实现原理、应用场景与最佳实践

引言 在分布式系统中&#xff0c;实现数据的并发访问控制是一项至关重要的任务。在这个任务中&#xff0c;锁&#xff08;Lock&#xff09;起到了关键的作用。Redis 是一个流行的内存数据库&#xff0c;它不仅提供了高性能的键值存储&#xff0c;还能通过其强大的特性实现分布…

Oracle23ai来了,23爱,全能、超级巨兽...

&#x1f4e2;&#x1f4e2;&#x1f4e2;&#x1f4e3;&#x1f4e3;&#x1f4e3; 作者&#xff1a;IT邦德 中国DBA联盟(ACDU)成员&#xff0c;10余年DBA工作经验&#xff0c; Oracle、PostgreSQL ACE CSDN博客专家及B站知名UP主&#xff0c;全网粉丝10万 擅长主流Oracle、My…

非接触式光学检测原理介绍

光学测量分为接触式和非接触式&#xff0c;接触式测量&#xff0c;由于要接触物体被测表面&#xff0c;所以对于物体表面有要求的就不适用&#xff0c;并且测量精度会受表面粗糙度的影响导致测量仪器有磨损且测量不准确。所以非接触式测量得到极大的发展&#xff0c;非接触式测…

循环链表 -- c语言实现

#pragma once // 带头双向循环链表增删查改实现 #include<stdlib.h> #include<stdio.h> #include<assert.h>typedef int LTDataType;typedef struct ListNode {LTDataType data;struct ListNode* next;struct ListNode* prev; }ListNode;//双链表申请一个新节…

使用FastGPT+OneAPI在本地使用Llama3

FastGPT 是一个基于 LLM 大语言模型的知识库问答系统&#xff0c;提供开箱即用的数据处理、模型调用等能力。同时可以通过 Flow 可视化进行工作流编排&#xff0c;从而实现复杂的问答场景&#xff01;他的重要特点就是工作流编排。 工作流编排&#xff1a;基于 Flow 模块的工作…

4.2 JavaScript语法

4.2.1 JavaScript大小写 在JavaScript中大小写是严格区分的&#xff0c;无论是变量、函数名称、运算符和其他语法都必须严格按照要求的大小写进行声明和使用。例如变量hello与变量HELLO会被认为是完全不同的内容。 4.2.2 JavaScript分号 很多编程语言&#xff08;例如C、Java和…

Python之字符串,列表,元组,字典之间的转换写法

# 转换函数# 元组与列表之间的转换# 把元组转换成列表 # list() lis1 list(tuple1) print(lis1) # [成龙, 小玉, 老爹, 特鲁, 瓦龙, 布莱特, 圣主]# 把列表转换成元组 # tuple() tup1 tuple(lis1) print(tup1) # (成龙, 小玉, 老爹, 特鲁, 瓦龙, 布莱特, 圣主)# 字符串与列表…