c# 操作FTP文件类
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)
{
System.Windows.Forms.MessageBox.Show(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, String directory, String newFileName) //上面的代码实现了从ftp服务器上载文件的功能
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + directory + "/" + newFileName;
if (!DirectoryIsExist(directory))
{
MakeDir(directory);
}
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)
{
MessageBox.Show(ex.Message, "Upload Error");
}
}
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)
{
MessageBox.Show(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)
{
MessageBox.Show(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)
{
MessageBox.Show(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)
{
MessageBox.Show(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();
//Stream ftpStream = response.GetResponseStream();
//ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//获得文件明晰
public string[] GetFilesDetailList()
{
return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
}
//获得文件明晰
public string[] GetFilesDetailList(string path)
{
return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
}
/// <summary>
/// 检测目录是否存在
/// </summary>
/// <param name="dirName"></param>
/// <returns>false不存在,true存在</returns>
public Boolean DirectoryIsExist(string dirName)
{
string[] value = GetFileList(dirName);
if (value == null)
{
return false;
}
else
{
return true;
}
}
转载于:https://www.cnblogs.com/gengaixue/archive/2012/11/28/2792893.html
c# 操作FTP文件类相关推荐
- java ftp connect_java操作Ftp文件的一些方式(一)
public class FtpUtil { private Log log = LogFactory.getLog(getClass()) ; private String userName; p ...
- C#操作ini文件类
类的代码如下: using System; using System.Text; using System.Runtime.InteropServices; using System.Globaliz ...
- C++ 学习笔记之——文件操作和文件流
1. 文件的概念 对于用户来说,常用到的文件有两大类:程序文件和数据文件.而根据文件中数据的组织方式,则可以将文件分为 ASCII 文件和二进制文件. ASCII 文件,又称字符文件或者文本文件,它的 ...
- 十、封装python3读写ini文件类
自己编写封装的python3读写ini文件类. main.py # -*- coding: utf-8 -*- import os import configparserclass OperateIn ...
- 权限问题导致无法删除ftp文件
首先吐槽一下,使用新版编辑器,发了两遍愣是time out,果断放弃 这个文章也是一件小事,大致说一下: 有一个java操作ftp文件的程序,运行删除时,总是返回false,也没有报错.開始考虑是没有 ...
- 【FTP工具类】提供FTP服务器的连接, 查找文件目录,及读取文件内容等操作
介绍:FTP工具类,提供FTP服务器的连接, 查找文件目录,及读取文件内容等操作. 应用场景: 通过FTP连接需要获取文件目录列表 通过FTP连接读取指定文件内容 递归读取遍历服务器上所有文件 其他功 ...
- php vsftpd文件上传类,php ftp文件上传函数(基础版)
php ftp文件上传函数(基础版) 复制代码 代码如下: // 定义变量 $local_file = 'local.zip'; $server_file = 'server.zip'; // 连接F ...
- 解决修改properties 属性文件存在缓存问题,附带操作properties文件工具类
2019独角兽企业重金招聘Python工程师标准>>> 在做项目的时候有些数据不一定需要在数据库管理,例如数据库连接,定时任务等等的配置..有时候需要动态修改这些数据,但在修改完后, ...
- java中文件操作的工具类
代码: package com.lky.pojo;import java.io.BufferedReader; import java.io.BufferedWriter; import java.i ...
- C#操作FTP报错,远程服务器返回错误:(550)文件不可用(例如,未找到文件,无法访问文件)的解决方法
C#操作FTP报错,远程服务器返回错误:(550)文件不可用(例如,未找到文件,无法访问文件)的解决方法 参考文章: (1)C#操作FTP报错,远程服务器返回错误:(550)文件不可用(例如,未找到文 ...
最新文章
- 原创:去繁存简,回归本源:微信小程序公开课信息分析《一》
- DPU加持下的阿里云如何做加密计算?
- javascript-数据类型,json与数组,获取非行间样式
- 基于JSP实现人力资源管理系统
- Selenium 反反爬检测方案(利用js隐藏浏览器特征)
- Linux通过文件大小查找,linux 根据文件大小查找文件
- RN子组件获取redux数据
- 抛开当下的迷惘,IT技术人的发展之路该怎么走?
- Kernel Method: 6.再生核希尔伯特空间理论
- 2021年安全员-C证(山东省-2020版)考试及安全员-C证(山东省-2020版)模拟试题
- 爬取当当网评论(1)
- python爬取LOL皮肤
- 与老公的情人同居一室很尴尬
- 天干地支与阴阳五行的关系
- Convex Optimization
- 协方差意味着什么_微服务意味着我们可以使用所需的任何语言? 真?
- 交通违章查询接口代码示例
- 选中一次格式刷,即可多次使用WPS格式刷的办法
- 6.2 新浪财经——资产负债表获取(打印js渲染后的网页表格)
- 配置基于IPv6的单节点Ceph
热门文章
- java string 空间_java堆与栈 java String分配内存空间(详解)
- TSAP(4) : 时间序列采样[asfreq( ) VS resample( )]
- mysql union all 等效_Mysql联合查询UNION和UNION ALL的使用介绍
- 2021-08-3126. 删除有序数组中的重复项 数组
- GBDT, Gradient Boost Decision Tree,梯度提升决策树
- 212.单词搜索II
- JSTL迭代操作--c:forEach,c:forTokens
- php重写mysql类_如何成功重写旧的mysql-php代码与已弃用的mysql_ *函数?
- c语言语句结束的标准,C语言的语句要求以哪种符号结束?
- windows上jupyter notebook主题背景、字体及扩展插件配置(集成vim环境)