C# 操作FTP
操作FTP管理类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms; namespace Demo
{
/// <summary>
/// 用于ftp操作
/// 罗旭成
/// 2014-04-15
/// </summary>
public class FtpUpDown
{
string ftpServerIP;//服务器ip地
string ftpUserID;//用户名
string ftpPassword;//密码
FtpWebRequest reqFTP; public FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword)
{
this.ftpServerIP = ftpServerIP;
this.ftpUserID = ftpUserID;
this.ftpPassword = ftpPassword;
} #region * 连接ftp
private void Connect(string path)
{
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// 指定数据传输类型
reqFTP.UseBinary = true;
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
}
#endregion #region * 从ftp服务器上获得文件列表
private string[] GetFileList(string path, string WRMethods)
{
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'), );
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)
{
return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
} public string[] GetFileList()
{
return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
}
#endregion #region * 上传文件
public void Upload(string filename)
{
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 = ;
byte[] buff = new byte[buffLength]; int contentLen;
// 打开一个文件流(System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead(); try
{
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream();
// 每次读文件流的kb
contentLen = fs.Read(buff, , buffLength);
// 流内容没有结束
while (contentLen != )
{
// 把内容从file stream 写入upload stream
strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , buffLength);
} // 关闭两个流
strm.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Upload Error");
}
}
#endregion #region * 下载文件
public bool Download(string filePath, string fileName, out string errorinfo)
{
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 = ;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, , bufferSize); FileStream outputStream = new FileStream(newFileName, FileMode.Create);
while (readCount > )
{
outputStream.Write(buffer, , readCount);
readCount = ftpStream.Read(buffer, , bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close(); errorinfo = "";
return true;
}
catch (Exception ex)
{
errorinfo = string.Format("因{0},无法下载", ex.Message);
return false;
}
}
#endregion #region * 删除文件
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, "删除错误");
}
}
#endregion #region * 创建目录
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);
}
}
#endregion #region * 删除目录
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);
}
}
#endregion #region * 获得文件大小
public long GetFileSize(string filename)
{
long fileSize = ;
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;
}
#endregion #region * 文件改名
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);
}
}
#endregion #region * 获得文件明细
public string[] GetFilesDetailList()
{
return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
} public string[] GetFilesDetailList(string path)
{
return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
}
#endregion
}
}
下载文件:
#region * 下载文件
private void btnDownload_Click(object sender, EventArgs e)
{
try
{
string ftpServerIP = string.Empty;//服务器ip地
string ftpUserID = string.Empty;//用户名
string ftpPassword = string.Empty;//密码
if (CheckNull(ref ftpServerIP, ref ftpUserID, ref ftpPassword))
{
FtpUpDown ftpUpDown = new FtpUpDown(ftpServerIP, ftpUserID, ftpPassword);
string error = string.Empty;
ftpUpDown.Download(this.txtDir.Text.Trim(), this.txtFile.Text.Trim(), out error);
if (!string.IsNullOrEmpty(error))
{
MessageBox.Show(error);
}
}
}
catch (Exception eMsg)
{
MessageBox.Show("下载文件出错:" + eMsg.ToString());
}
}
#endregion
上传文件:
#region * 上传文件
private void btnUpload_Click(object sender, EventArgs e)
{
try
{
string file = string.Empty;
file = this.txtFile1.Text.Trim();
if (string.IsNullOrEmpty(file))
{
MessageBox.Show("文件名不能为空!");
return;
}
string ftpServerIP = string.Empty;//服务器ip地
string ftpUserID = string.Empty;//用户名
string ftpPassword = string.Empty;//密码
if (CheckNull(ref ftpServerIP, ref ftpUserID, ref ftpPassword))
{
FtpUpDown ftpUpDown = new FtpUpDown(ftpServerIP, ftpUserID, ftpPassword);
ftpUpDown.Upload(this.txtFile1.Text.Trim());
}
}
catch (Exception eMsg)
{
MessageBox.Show("上传文件出错:" + eMsg.ToString());
}
}
#endregion
以上即是操作FTP。
C# 操作FTP的更多相关文章
- 使用python操作FTP上传和下载
函数释义 Python中默认安装的ftplib模块定义了FTP类,其中函数有限,可用来实现简单的ftp客户端,用于上传或下载文件,函数列举如下 ftp登陆连接 from ftplib import F ...
- C#操作FTP报错,远程服务器返回错误:(550)文件不可用(例如,未找到文件,无法访问文件)的解决方法
最近在做项目的时候需要操作ftp进行文件的上传下载,但在调用using (var response = (FtpWebResponse)FtpWebRequest.GetResponse())的时候总 ...
- Asp.Net操作FTP方法
将用户上传的附件(文件.图片等)通过FTP方式传送到另外一台服务器上,从而缓解服务器压力 1.相关的文章如下: Discuz!NT中远程附件的功能实现[FTP协议] http://www.cnblog ...
- java操作FTP的一些工具方法
java操作FTP还是很方便的,有多种开源支持,这里在apache开源的基础上自己进行了一些设计,使用起来更顺手和快捷. 思路: 1.设计FTPHandler接口,可以对ftp,sftp进行统一操作, ...
- 【转】 C#操作FTP
代码不要忘记引入命名空间using System.Net;using System.IO;下面的几个步骤包括了使用FtpWebRequest类实现ftp功能的一般过程1.创建一个FtpWebReque ...
- ftp客户端自动同步 Windows系统简单操作ftp客户端自动同步
服务器管理工具它是一款功能强大的服务器集成管理器,包含win系统和linux系统的批量连接,vnc客户端,ftp客户端等等实用功能.我们可以使用这款软件的ftp客户端定时上传下载的功能来进实现ftp客 ...
- PHP操作FTP类 (上传下载移动创建等)
使用PHP操作FTP-用法 Php代码 收藏代码 <? // 联接FTP服务器 $conn = ftp_connect(ftp.server.com); // 使用username和passwo ...
- C#使用Sockets操作FTP【转载】
using System; using System.Collections; using System.IO; using System.Net; using System.Net.Sockets; ...
- python下操作ftp上传
生产情况:tomcat下业务log备份,目录分多级,然后对应目录格式放到ftp上:所以,结构上 我就是一级一级目录进行判断(因为我没有找到在ftp一次判断其子目录是否存在),还有一个low点就是我没有 ...
随机推荐
- Linux命令(补充)
1.查看已启动服务的端口: netstat -tulnp |grep 80 ss -tulnp|grep 80 2.查看全部已启动的端口:netstat -tulnp 3.查看当前目录:pwd 4.关 ...
- 具体解释linux下的串口通讯开发
串行口是计算机一种经常使用的接口,具有连接线少.通讯简单,得到广泛的使用.经常使用的串口是RS-232-C接口(又称EIA RS-232-C)它是在1970年由美国电子工业协会(EIA)联合贝尔系统. ...
- Spring MVC学习(五)---ModelAndView没有明显申明name
看图不解释: 对于这种写法: new ModelAndView().addObject(XXX)
- 『HTML5实现人工智能』小游戏《井字棋》发布,据说IQ上200才能赢【算法&代码讲解+资源打包下载】
一,什么是TicTacToe(井字棋) 本游戏为在下用lufylegend开发的第二款小游戏.此游戏是大家想必大家小时候都玩过,因为玩它很简单,只需要一张草稿纸和一只笔就能开始游戏,所以广受儿童欢迎. ...
- java 多线程 day07 多线程共享数据
/** * Created by chengtao on 17/12/3. * 多个线程 如何共享数据? * 常见实例:多个窗口同时售卖火车票 */public class Thread0701_Mu ...
- 检查Linux服务器性能命令详解
如果你的Linux服务器突然负载暴增,如何在最短时间内找出Linux性能问题所在? 通过执行以下命令,可以在1分钟内对系统资源使用情况有个大致的了解. uptime dmesg | tail vmst ...
- Java队列存储结构及实现
一.队列(Queue) 队列是一种特殊的线性表,它只允许在表的前段(front)进行删除操作,只允许在表的后端(rear)进行插入操作.进行插入操作的端称为队尾,进行删除操作的端称为队头. 对于一个队 ...
- Oracle记录登录失败的触发器
前言:实现的功能主要是,oracle登录成功记录登录用户ip地址,登录失败记录登录失败ip地址 1,需要建立一个触发器记录登录成功的客户端用户的ip地址 大家都知道在v$session 中记录着客户端 ...
- Angular 笔记系列(二)数据绑定
数据绑定这块儿没啥说的,简单两个例子带过了. Hello World: <!DOCTYPE html> <html ng-app> <head> <title ...
- 参数或变量中有语法错误。 服务器响应为: mail from address must be same as authorization user
企业qq发邮件失败,提示: 参数或变量中有语法错误. 服务器响应为: mail from address must be same as authorization user 解决办法: 登录邮箱,设 ...