C# FTP操作类

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace Utility
{
public class FtpUpDown
{

string ftpServerIP;

string ftpUserID;

string ftpPassword;

FtpWebRequest reqFTP;

private void Connect(String path)//连接ftp
{

// 根据uri创建FtpWebRequest对象

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));

// 指定数据传输类型

reqFTP.UseBinary = true;

//ftp用户名和密码

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

}

public FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword)
{
this.ftpServerIP = ftpServerIP;

this.ftpUserID = ftpUserID;

this.ftpPassword = ftpPassword;
}

//都调用这个

private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
try
{
Connect(path);

reqFTP.Method = WRMethods;

WebResponse response = reqFTP.GetResponse();

StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名

string line = reader.ReadLine();

while (line != null)
{

result.Append(line);

result.Append("\n");

line = reader.ReadLine();

}

// to remove the trailing '\n'

result.Remove(result.ToString().LastIndexOf('\n'), 1);

reader.Close();

response.Close();

return result.ToString().Split('\n');

}

catch (Exception ex)
{
Log.WriteError("Get FileList Error:" + ex.Message);
downloadFiles = null;

return downloadFiles;
}
}

public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
{
return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
}
public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表
{
return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
}

public void Upload(string filename) //上面的代码实现了从ftp服务器上载文件的功能
{
FileInfo fileInf = new FileInfo(filename);

string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

Connect(uri);//连接

// 默认为true,连接不会被关闭

// 在一个命令之后被执行

reqFTP.KeepAlive = false;

// 指定执行什么命令

reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

// 上传文件时通知服务器文件的大小

reqFTP.ContentLength = fileInf.Length;
// 缓冲大小设置为kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];

int contentLen;

// 打开一个文件流(System.IO.FileStream) 去读上传的文件

FileStream fs = fileInf.OpenRead();

try
{

// 把上传的文件写入流

Stream strm = reqFTP.GetRequestStream();

// 每次读文件流的kb

contentLen = fs.Read(buff, 0, buffLength);

// 流内容没有结束

while (contentLen != 0)
{
// 把内容从file stream 写入upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);

}

// 关闭两个流

strm.Close();

fs.Close();

}

catch (Exception ex)
{
Log.WriteError( "Upload Error:" + ex.Message);
}

}

public bool Download(string filePath, string fileName, out string errorinfo)////上面的代码实现了从ftp服务器下载文件的功能
{
try
{
String onlyFileName = Path.GetFileName(fileName);

string newFileName = filePath + "\\" + onlyFileName;

if (File.Exists(newFileName))
{

errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);
return false;
}
string url = "ftp://" + ftpServerIP + "/" + fileName;
Connect(url);//连接
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);

FileStream outputStream = new FileStream(newFileName, FileMode.Create);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();

errorinfo = "";

return true;

}

catch (Exception ex)
{
errorinfo = string.Format("因{0},无法下载", ex.Message);

return false;

}

}

//删除文件

public void DeleteFileName(string fileName)
{
try
{
FileInfo fileInf = new FileInfo(fileName);

string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

Connect(uri);//连接

// 默认为true,连接不会被关闭

// 在一个命令之后被执行

reqFTP.KeepAlive = false;

// 指定执行什么命令

reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();

}

catch (Exception ex)
{
Log.WriteError("删除错误:" + ex.Message);
}

}

//创建目录

public void MakeDir(string dirName)
{
try
{
string uri = "ftp://" + ftpServerIP + "/" + dirName;

Connect(uri);//连接

reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

response.Close();

}

catch (Exception ex)
{
Log.WriteError("创建目录错误:" + ex.Message);
}

}

//删除目录

public void delDir(string dirName)
{
try
{
string uri = "ftp://" + ftpServerIP + "/" + dirName;

Connect(uri);//连接

reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

response.Close();

}

catch (Exception ex)
{
Log.WriteError("删除目录错误:" + ex.Message);
}

}

//获得文件大小

public long GetFileSize(string filename)
{

long fileSize = 0;

try
{

FileInfo fileInf = new FileInfo(filename);

string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

Connect(uri);//连接

reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

fileSize = response.ContentLength;

response.Close();

}

catch (Exception ex)
{
Log.WriteError("获得文件大小错误:" + ex.Message);
}

return fileSize;

}

//文件改名

public void Rename(string currentFilename, string newFilename)
{
try
{
FileInfo fileInf = new FileInfo(currentFilename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();

}

catch (Exception ex)
{
Log.WriteError("文件改名错误:" + ex.Message);
}

}
//读取文件

public Stream ReadFile(string fileName)
{
try
{
string url = "ftp://" + ftpServerIP + "/" + fileName;
Connect(url);//连接
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
return ftpStream;
}

catch (Exception ex)
{
Log.WriteError("读取文件错误:" + ex.Message);
return null;
}

}

//获得文件明晰

public string[] GetFilesDetailList()
{

return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);

}

//获得文件明晰

public string[] GetFilesDetailList(string path)
{

return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);

}

// 文件存在检查
public bool fileCheckExist(string fileName)
{
bool success = false;
FtpWebResponse response = null;
StreamReader reader = null;
try
{
string url = "ftp://" + ftpServerIP + "/" + fileName;
Connect(url);//连接
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
response = (FtpWebResponse)reqFTP.GetResponse();
reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
if (line != null)
{
success = true;
}
}
catch (Exception)
{
success = false;
}
finally
{
if (reader != null)
{
reader.Close();
}

if (response != null)
{
response.Close();
}
}
return success;
}
}
}

匿名登录FTP

用 ftp_connect,ftp_login 匿名登录FTP时,用户名为:anonymous 密码为:空

FTP获取文件路径和子目录路径
 1         /// <summary>
 2         /// 从ftp服务器上获得文件列表
 3         /// </summary>
 4         /// <param name="RequedstPath"></param>
 5         /// <returns></returns>
 6         public static List<string> GetDirctory(string RequedstPath)
 7         {
 8             List<string> strs = new List<string>();
 9             try
10             {
11                 string uri = path + RequedstPath;   //目标路径 path为服务器地址
12                 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
13                 // ftp用户名和密码
14                 reqFTP.Credentials = new NetworkCredential(username, password);
15                 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
16                 WebResponse response = reqFTP.GetResponse();
17                 StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
18 
19                 string line = reader.ReadLine();
20                 while (line != null)
21                 {
22                     if (line.Contains("<DIR>"))
23                     {
24                         string msg = line.Substring(line.LastIndexOf("<DIR>")+5).Trim();
25                         strs.Add(msg);
26                     }
27                     line = reader.ReadLine();
28                 }
29                 reader.Close();
30                 response.Close();
31                 return strs;
32             }
33             catch (Exception ex)
34             {
35                 Console.WriteLine("获取目录出错:" + ex.Message);
36             }
37             return strs;
38         }
39 
40         /// <summary>
41         /// 从ftp服务器上获得文件
42         /// </summary>
43         /// <param name="RequedstPath">相对服务器路径</param>
44         /// <returns></returns>
45         public static List<string> GetFile(string RequedstPath)
46         {
47             List<string> strs = new List<string>();
48             try
49             {
50                 string uri = path + RequedstPath;   //目标路径 path为服务器地址
51                 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
52                 // ftp用户名和密码
53                 reqFTP.Credentials = new NetworkCredential(username, password);
54                 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
55                 WebResponse response = reqFTP.GetResponse();
56                 StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
57 
58                 string line = reader.ReadLine();
59                 while (line != null)
60                 {
61                     if (!line.Contains("<DIR>"))
62                     {
63                         string msg = line.Substring(39).Trim();
64                         strs.Add(msg);
65                         Console.WriteLine(msg);
66                     }
67                     line = reader.ReadLine();
68                 }
69                 reader.Close();
70                 response.Close();
71                 return strs;
72             }
73             catch (Exception ex)
74             {
75                 Console.WriteLine("获取文件出错:" + ex.Message);
76             }
77             return strs;
78         }

知道如何获取文件和目录,剩下的就是一个递归而已。这个很简单,不说明了。递归这东西好玩,但是效率很低。

Ron Ngai |园豆:358 (菜鸟二级) |2012-07-25 18:28
        /// <summary>
        /// 从ftp服务器上获得文件列表
        /// </summary>
        /// <param name="RequedstPath"></param>
        /// <returns></returns>
        public static List<string> GetDirctory(string RequedstPath)
        {
            List<string> strs = new List<string>();
            try
            {
                string uri = path + RequedstPath;   //目标路径 path为服务器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

                string line = reader.ReadLine();
                while (line != null)
                {
                    if (line.Contains("<DIR>"))
                    {
                        string msg = line.Substring(line.LastIndexOf("<DIR>")+5).Trim();
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取目录出错:" + ex.Message);
            }
            return strs;
        }

        /// <summary>
        /// 从ftp服务器上获得文件
        /// </summary>
        /// <param name="RequedstPath">相对服务器路径</param>
        /// <returns></returns>
        public static List<string> GetFile(string RequedstPath)
        {
            List<string> strs = new List<string>();
            try
            {
                string uri = path + RequedstPath;   //目标路径 path为服务器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

                string line = reader.ReadLine();
                while (line != null)
                {
                    if (!line.Contains("<DIR>"))
                    {
                        string msg = line.Substring(39).Trim();
                        strs.Add(msg);
                        Console.WriteLine(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取文件出错:" + ex.Message);
            }
            return strs;
        }

C#开发-FTP操作方法整理 2--C# FTP操作类 C#开发-FTP操作方法整理1.整理简化了下C#的ftp操作,方便使用1.支持创建多级目录 2.批量删除 3.整个目录上传 4.整个目录删除 5.整个目录下载 2.调用方法展示,var ftp = new FtpHelper(“10.136.12.11”, “qdx1213123”, “123ddddf”);//初始化ftp,创建ftp对象 阅读详情

相关推荐

Linux系统下奥比中光Astra Pro相机SDK部署与避坑指南

本文详细指导了在Linux系统下部署奥比中光Astra Pro深度相机SDK的全过程,涵盖系统准备、SDK安装、设备权限配置及常见问题排查。重点解析了USB设备规则配置这一关键步骤,并提供了Python与C++项目的集成方法,旨在帮助开发者快速完成相机配置,避免常见陷阱。

weixin_28455801的博客 300

c#ftp操作全解:创建删除目录,上传下载文件,删除移动文件,文件改名,文件目录查询

全栈工程师开发手册 (作者:栾鹏) c#教程全解 c#实现ftp的操作。包括创建删除目录,上传下载文件,删除移动文件,文件改名,文件目录查询。在调试ftp前,需要在目标主机上开启ftp功能。这里在本机上调试,目标主机也是本机。ftp信息如下表主机地址192.168.8.101,端口号使用默认21端口,开启了匿名登录。所以在代码中登陆ftp账号密码为空。测试代码static void Main

7905

【环境搭建】使用openSfM+MVSNet重建稠密点云

本帖详细介绍了如何使用openSfM+MVSNet对真实采集的数据进行稀疏重建与稠密重建,并针对一些真实场景下可能遇到的问题进行了整理。

YuhsiHu的博客 1973

linuxFTP匿名访问实验步骤

安装vsftp软件包 在客户端安装主配置文件,并且用ftp链接服务器端端额IP 在客户端安装主配置文件,并且用ftp链接服务器端端额IP 然后在服务器端/var/ftp里面创建文件 ,然后在客户端查看 到客户端去看看是不是有这个文件 ...

weixin_43232833的博客 3598

PRIDE数据库20年:2025更新

PRoteomics IDEntifications (PRIDE)数据库(https://www.ebi.ac.uk/pride/)是全球领先的基于质谱(MS)的蛋白质组学数据存储库,也是ProteomeXchange联盟的创始成员之一。本文总结了过去3年中PRIDE资源及相关工具的发展情况。提交到PRIDE存档的数据集数量平均每月达到约534个。主要得益于基础设施的持续改进,如用于超大数据集的新文件传输协议(Globus)、新的数据重新提交流程以及自动数据集验证过程。

多组・学・多组学 2065

lammps案例:聚乙烯和石墨烯界面pull out模拟

大家好,我是小马老师。 本文介绍lammps模拟计算界面结合力的一个案例。 本案例参考论文《The interfacial mechanical properties of functionalized graphene- polymer nanocomposites》,对论文作者表示感谢。 模型共分2层,上层为聚乙烯模型,下次为单层石墨烯,模拟过程共分3部分:建模、弛豫、拉伸。 (1)建模 使用MS建立聚乙烯和石墨烯模型,具体方法可参考之前的推文,使用build layer方法建立聚乙烯和石墨烯组合模型,

lammps_jiayou的博客 3497

从气象预报到灾害监测:卫星覆盖性能如何影响你的日常生活?

本文深入探讨了卫星覆盖性能如何从天气预报到灾害监测深刻影响日常生活。通过解析极地轨道、地球静止轨道及星座协同覆盖模式,揭示卫星技术的黄金指标如何提升天气预报精度和灾害响应速度。文章还展望了下一代卫星网络在智能响应、厘米级服务和全球事件直播方面的突破性应用。

weixin_33686714的博客 1216

【ARM Trace32(劳特巴赫) 高级篇 20 -- SNOOPer 使用介绍】

在 Lauterbach TRACE32 调试系统中,Snooper是一种特殊的监视工具,它能够在不中断处理器执行的情况下监视和记录特定内存地址的数据变化。这对于系统级调试、性能分析、数据流监视以及实时系统的问题追踪特别有用,尤其是在无法使用中断的情况下。当你设置了一个或多个Snooper时,TRACE32 硬件将不断地监视指定的内存地址,一旦发生了读写操作,就会将相关信息记录下来。这样你就可以看到某个地址的数据是什么时候以及如何被修改的,而不会影响目标系统的运行。

CodingCos的博客 2770

C# ftp操作类

using System; using System.Text; using System.IO; using System.Net; namespace Himall.Core.Helper {     public class FtpHelper     {         string ftpServerIP;         string ftpRemot

u012992280的专栏 446

YOLOv8架构革命:通过EfficientViT融合实现精度-速度的帕累托突破

目标检测领域长期存在精度与速度的权衡难题。视觉Transformer(ViT)的引入解决了长距离依赖问题,但其巨大的计算复杂度制约了实时应用。最新研究表明,将轻量级ViT与YOLO架构融合,可在几乎不损失推理速度的前提下,将mAP提升3-8个百分点。这种架构改进方案已在工业检测、自动驾驶、安防监控等多个领域得到验证,在保持实时性的同时显著提升了复杂场景下的检测可靠性。通过模块化设计,可以灵活适配不同规模的YOLOv8模型,为实际应用提供精度-速度的帕累托最优解。

FJN110的博客 149

coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?

🏆本文收录于《优快云问答解惑-专业版》专栏,主要记录项目实战过程中的Bug之前因后果及提供真实有效的解决方案,希望能够助你一臂之力,帮你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!

**My Coding Family** 2670

C# FTP 操作类

using System;using System.Collections.Generic;using System.Text;using System.IO;using System.Net;using System.Windows.Forms; namespace RecoverData{ public class FTPClient { private ...

87

【晶振专题】晶振学习笔记——ST AN2867应用手册 2

通过学习AN2867设计指南,我们知道皮尔斯晶振的基本知识。也了解了晶振的负载电容计算方法、安全因子测试方法和反馈电阻的作用。

一点硬件 1365

C# FTP操作类

可进行FTP的上传,下载等其他功能,支持断点续传: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; n...

206

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

【转载】C#工具类:FTP操作辅助类FTPHelper

FTP是一个8位的客户端-服务器协议,能操作任何类型的文件而不需要进一步处理,就像MIME或Unicode一样。可以通过C#中的FtpWebRequest类、NetworkCredential类、WebRequestMethods类来实现一个FTP操作的相关辅助类FTPHelper。 先来看MSDN关于上述几个类的定义以及解释: FtpWebRequest类:实现文件传输协议 (FTP) 客户...

weixin_30907523的博客 310

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

修订 基于C#的ftp操作类 中的一个问题

一篇 基于C#实现 ftp 文件上传、下载操作的类 的文章在网上流传挺广的。 附两个链接:http://outofmemory.cn/code-snippet/2809/c-achieve-FTP-shangchuan-class,http://www.cnblogs.com/zhangjun1130/archive/2010/03/24/1693932.html 以上两篇文章内容差不多。

wangx89的博客 551
上一篇: C# 的关键字
下一篇: C# FTP操作类
devgis
博客等级 码龄16年 52粉丝 60原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值