操作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. 汉诺塔IV---hdu2077

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2077 #include <stdio.h> #include <stdlib.h&g ...

  2. restfull规范

    web服务交互 我们在浏览器中能看到的每个网站,都是一个web服务.那么我们在提供每个web服务的时候, 都需要前后端交互,前后端交互就一定有一些实现方案,我们通常叫web服务交互方案. 目前主流的三 ...

  3. java.util.Calendar

    package day14; import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer; import java.util.Cal ...

  4. 360UI 界面框架 即QUI框架与EXT比较

    EXTJS框架是非常全面和成熟的,这是因为它发展的年头久远,并且有全世界的EXTJS爱好者为其出谋献策,它的组件库尤其是DataGrid组件无人能出其右.我在最初也考虑过使用EXTJS来做项目,学习了 ...

  5. Java-小技巧-004-jdk时间,jdk8时间,joda,calendar,获取当前时间前一周、前一月、前一年的时间

    1.推荐使用java8 localdate等 线程安全 支持较好 地址 2.joda 一.简述 查看SampleDateFormat源码,叙述有: * Date formats are not syn ...

  6. linux的虚拟机时间和物理机时间同步

    1.查看和设置物理机硬件时间 查看硬件时间# hwclock --show或# clock --show 设置硬件时间# hwclock --set --date=”01/14/19 10:19″(月 ...

  7. 【源码分享】仿网易客户端源码效果 apkbus的~

    http://www.apkbus.com/forum.php?mod=viewthread&tid=184867 内容我就不说了,直接点开看吧.

  8. IDEA 编译报错: 未结束的字符串文字

    最近在搞新项目,同事用的eclipse开发,而我用的是ide,项目初始是由同事创建的,项目编码是UTF-8,而我开发的ide工具默认是GBK编码,导致在编译的时候报错: 未结束的字符串文字 这个问题就 ...

  9. Core ML 入门

    1.下载Xcode 9 2.下载模型,https://developer.apple.com/machine-learning/ 3.开动.. 4.待续 模拟器66的

  10. Linux查看本机登陆用户信息(w、who、last和lastlog命令)

    w 命令 查看 Linux 服务器上目前已经登录的用户信息 [root@localhost ~]# w :: up :, users, load average:0.00, 0.00, 0.00 US ...