操作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的更多相关文章

  1. 使用python操作FTP上传和下载

    函数释义 Python中默认安装的ftplib模块定义了FTP类,其中函数有限,可用来实现简单的ftp客户端,用于上传或下载文件,函数列举如下 ftp登陆连接 from ftplib import F ...

  2. C#操作FTP报错,远程服务器返回错误:(550)文件不可用(例如,未找到文件,无法访问文件)的解决方法

    最近在做项目的时候需要操作ftp进行文件的上传下载,但在调用using (var response = (FtpWebResponse)FtpWebRequest.GetResponse())的时候总 ...

  3. Asp.Net操作FTP方法

    将用户上传的附件(文件.图片等)通过FTP方式传送到另外一台服务器上,从而缓解服务器压力 1.相关的文章如下: Discuz!NT中远程附件的功能实现[FTP协议] http://www.cnblog ...

  4. java操作FTP的一些工具方法

    java操作FTP还是很方便的,有多种开源支持,这里在apache开源的基础上自己进行了一些设计,使用起来更顺手和快捷. 思路: 1.设计FTPHandler接口,可以对ftp,sftp进行统一操作, ...

  5. 【转】 C#操作FTP

    代码不要忘记引入命名空间using System.Net;using System.IO;下面的几个步骤包括了使用FtpWebRequest类实现ftp功能的一般过程1.创建一个FtpWebReque ...

  6. ftp客户端自动同步 Windows系统简单操作ftp客户端自动同步

    服务器管理工具它是一款功能强大的服务器集成管理器,包含win系统和linux系统的批量连接,vnc客户端,ftp客户端等等实用功能.我们可以使用这款软件的ftp客户端定时上传下载的功能来进实现ftp客 ...

  7. PHP操作FTP类 (上传下载移动创建等)

    使用PHP操作FTP-用法 Php代码 收藏代码 <? // 联接FTP服务器 $conn = ftp_connect(ftp.server.com); // 使用username和passwo ...

  8. C#使用Sockets操作FTP【转载】

    using System; using System.Collections; using System.IO; using System.Net; using System.Net.Sockets; ...

  9. python下操作ftp上传

    生产情况:tomcat下业务log备份,目录分多级,然后对应目录格式放到ftp上:所以,结构上 我就是一级一级目录进行判断(因为我没有找到在ftp一次判断其子目录是否存在),还有一个low点就是我没有 ...

随机推荐

  1. 神、上帝以及老天爷--hdu2048(错排,递推)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2048 1. N张字条的所有可能排列自然是N!(分母). 现在的问题就是求N张字条的错排数f(N)(分子 ...

  2. 进程Process之join、daemon(守护)、terminate(关闭)

    一.Process 参数介绍: 1 group参数未使用,值始终为None 2 target表示调用对象,即子进程要执行的任务 3 args表示调用对象的位置参数元组,args=(1,2,'a',) ...

  3. Python高级教程-多重继承

    多重继承 继承是面向对象编程的一个重要的方式,因为通过继承,子类可以扩展父类的功能. Animal类的层次设计,假设要实现以下4中动物: Dog - 狗狗: Bat - 蝙蝠: Parrot - 鹦鹉 ...

  4. SQL事务回滚 写法(转)

    以下是SQL 回滚的语句:方案一:SET   XACT_ABORT   ON--如果产生错误自动回滚GOBEGIN   TRANINSERT   INTO   A   VALUES   (4)INSE ...

  5. mysql 下的命令

    1.查看mysql日志vim /var/log/mysqld.log

  6. 判断是否关注了微信公众号 subscribe 0=未关注 1=已关注

    $appid=''; $secret=''; //微信网页授权获取openid $web_url='http://www.xxxx.com/shouquan.php'; if (!isset($_GE ...

  7. 专项训练知识点与错题整理-nowcoder-c++

    1- 来自:http://www.cskaoyan.com/thread-595813-1-1.html 1.拷贝构造函数 转自:https://www.cnblogs.com/alantu2018/ ...

  8. 不受路径限制的 HALCON开发环境, 并且初始化两个Picture控件;

    知识储备: http://bbs.csdn.net/topics/391829463    关于 添加第三方库的方式 http://www.ihalcon.com/read-3730.html  VS ...

  9. debian 如何切换为root用户

    debian 如何切换为root用户   debian 如何切换为root用户 sudo su 输入命令后提示输入密码,输入密码切换为root用户

  10. windows的cmd命令切换磁盘路径