FtpWebRequest与FtpWebResponse完成FTP操作
一、WebRequestMethods.Ftp类:
表示可与 FTP 请求一起使用的 FTP 协议方法的类型。
- AppendFile : 表示要用于将文件追加到 FTP 服务器上的现有文件的 FTP APPE 协议方法。
- DeleteFile :表示要用于删除 FTP 服务器上的文件的 FTP DELE 协议方法。
- DownloadFile :表示要用于从 FTP 服务器下载文件的 FTP RETR 协议方法。
- GetDateTimestamp :表示要用于从 FTP 服务器上的文件检索日期时间戳的 FTP MDTM 协议方法。
- GetFileSize :表示要用于检索 FTP 服务器上的文件大小的 FTP SIZE 协议方法。
- ListDirectory :表示获取 FTP 服务器上的文件的简短列表的 FTP NLIST 协议方法。
- ListDirectoryDetails :表示获取 FTP 服务器上的文件的详细列表的 FTP LIST 协议方法。
- MakeDirectory :表示在 FTP 服务器上创建目录的 FTP MKD 协议方法。
- PrintWorkingDirectory :表示打印当前工作目录的名称的 FTP PWD 协议方法。
- RemoveDirectory :表示移除目录的 FTP RMD 协议方法。
- Rename :表示重命名目录的 FTP RENAME 协议方法。
- UploadFile :表示将文件上载到 FTP 服务器的 FTP STOR 协议方法。
- UploadFileWithUniqueName :表示将具有唯一名称的文件上载到 FTP 服务器的 FTP STOU 协议方法。
二、上传文件:
OpenFileDialog opFilDlg = new OpenFileDialog();
if (opFilDlg.ShowDialog() == DialogResult.OK)
{ ftp = new YBBFTPClass("hz.a.cn", "", "csp", "welcome", 0);
ftp.UploadFile(opFilDlg.FileName);
MessageBox.Show("上传成功");
}
/// <summary>
/// 文件上传
/// </summary>
/// <param name="filename">本地文件路径</param>
public void UploadFile(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + RemoteHost + "/" + fileInf.Name;
FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + RemoteHost + "/" + fileInf.Name));// 根据uri创建FtpWebRequest对象
reqFTP.Credentials = new NetworkCredential(RemoteUser, RemotePass); // ftp用户名和密码
reqFTP.KeepAlive = false; // 默认为true,连接不会被关闭, 在一个命令之后被执行
reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // 指定执行什么命令
reqFTP.UseBinary = true; // 指定数据传输类型
reqFTP.ContentLength = fileInf.Length; // 上传文件时通知服务器文件的大小 int contentLen;
FileStream fileStream = fileInf.OpenRead(); // 打开一个文件读取内容到fileStream中
contentLen = fileStream.Read(buffer, 0, buffer.Length); ;//从fileStream读取数据到buffer中 Stream requestStream = reqFTP.GetRequestStream();
// 流内容没有结束
while (contentLen != 0)
{
requestStream.Write(buffer, 0, contentLen);// 把内容从buffer 写入 requestStream中,完成上传。
contentLen = fileStream.Read(buffer, 0, buffer.Length);
} // 关闭两个流
requestStream.Close();
//uploadResponse = (FtpWebResponse)reqFTP.GetResponse();
fileStream.Close();
}
三、下载文件
1、核心代码
/// <summary>
/// 下载文件
/// </summary>
/// <param name="filePath">本地目录</param>
/// <param name="fileName">远程路径</param>
public void DownloadFile(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
FileStream fileStream = new FileStream(filePath + "\\" + fileName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + RemoteHost + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(RemoteUser, RemotePass); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();//从ftp响应中获得响应流 //long cl = response.ContentLength;
byte[] buffer = new byte[1024];
int readCount; readCount = responseStream.Read(buffer, 0, buffer.Length);//从ftp的responseStream读取数据到buffer中
while (readCount > 0)
{
fileStream.Write(buffer, 0, readCount);//从buffer读取数据到fileStream中,完成下载
readCount = responseStream.Read(buffer, 0, buffer.Length);
} responseStream.Close();
fileStream.Close();
response.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
2、winform:、
FolderBrowserDialog fldDlg = new FolderBrowserDialog();
if (txtUpload.Text.Trim().Length > 0)
{
if (fldDlg.ShowDialog() == DialogResult.OK)
{
ftp.DownloadFile(fldDlg.SelectedPath, txtUpload.Text.Trim());
MessageBox.Show("下载成功");
}
}
else
{
MessageBox.Show("Please enter the File name to download");
}
3、webform弹出下载提示:
FtpClient _client = new FtpClient();
Stream stream = _client.OpenRead(FtpFilePath, FtpDataType.Binary); string FtpFilePath = Request.QueryString["FilePath"];
string _fname = Path.GetFileName(FtpFilePath);
Response.ContentType = "application/" + _fname.Split('.')[1];
Response.AddHeader("Content-disposition", "attachment; filename=" + _fname); byte[] buffer = new byte[10240];
int readCount;
do
{
readCount = stream.Read(buffer, 0, buffer.Length);
Response.OutputStream.Write(buffer, 0, readCount);//持续写入流
} while (readCount != 0); Response.OutputStream.Write(buffer, 0, buffer.Length); Response.End();
四、删除文件
string uri = "ftp://" + RemoteHost + "/" + fileName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + RemoteHost + "/" + fileName)); reqFTP.Credentials = new NetworkCredential(RemoteUser, RemotePass);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
完整代码参考:
FtpWebRequest与FtpWebResponse完成FTP操作的更多相关文章
- (转)FTP操作类,从FTP下载文件
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net ...
- C# FTP操作
using System; using System.Collections.Generic; using System.Net; using System.IO; namespace FTP操作 { ...
- 关于FTP操作的功能类
自己在用的FTP类,实现了检查FTP链接以及返回FTP没有反应的情况. public delegate void ShowError(string content, string title); // ...
- FtpHelper ftp操作类库
FtpHelper ftp操作类库 using System; using System.Collections.Generic; using System.Linq; using System.Te ...
- C# FTP操作类的代码
如下代码是关于C# FTP操作类的代码.using System;using System.Collections.Generic;using System.Text;using System.Net ...
- 【转载】C#工具类:FTP操作辅助类FTPHelper
FTP是一个8位的客户端-服务器协议,能操作任何类型的文件而不需要进一步处理,就像MIME或Unicode一样.可以通过C#中的FtpWebRequest类.NetworkCredential类.We ...
- [转]C# FTP操作类
转自 http://www.cnblogs.com/Liyuting/p/7084718.html using System; using System.Collections.Generic; ...
- 【C#】工具类-FTP操作封装类FTPHelper
转载:http://blog.csdn.net/gdjlc/article/details/11968477 using System; using System.Collections.Generi ...
- PHP FTP操作类( 上传、拷贝、移动、删除文件/创建目录 )
/** * 作用:FTP操作类( 拷贝.移动.删除文件/创建目录 ) * 时间:2006/5/9 * 作者:欣然随风 * QQ:276624915 */ class class_ftp { publi ...
随机推荐
- can/socket can
1. 概念 参考:Linux-CAN编程详解 can引脚: cn2: 15:CAN1_H 19 CAN1_L 根据每组报文开头的 11 位标识符(扩展帧为29位标识符.CAN 2.0A 规范)解释数据 ...
- 浅析人脸检测之Haar分类器方法:Haar特征、积分图、 AdaBoost 、级联
浅析人脸检测之Haar分类器方法 一.Haar分类器的前世今生 人脸检测属于计算机视觉的范畴,早期人们的主要研究方向是人脸识别,即根据人脸来识别人物的身份,后来在复杂背景下的人脸检测需求越来越大,人脸 ...
- ant编译apache-nutch-2.2.1结合mysql实现爬虫的安装配置全过程
之前的数据抓取都是用的八爪鱼软件,老大突发奇想要我自己搞个爬虫来抓取数据,网上找找貌似apache的nutch比较合适,于是就开始安装这啥nutch. 对于一个linux零基础的人来说,还要先学学li ...
- ASP.NET Core2,通过反射批量注入程序集
public void ConfigureServices(IServiceCollection services) { string strValue = Con ...
- JS权威指南笔记之数据类型
1.类型分为原始类型和对象. 2.原始类型有:数字类型,字符类型,布尔,和null undefind. 3.JavaScript里的函数都是真值. 4.函数和通过New关键字创建对象.这个样函数称为构 ...
- 转载:sql用逗号连接多张表对应哪个join?
http://blog.csdn.net/huanghanqian/article/details/52847835 四种join的区别已老生常谈: INNER JOIN(也可简写为JOIN): 如果 ...
- 解决post请求乱码问题
将下面配置信息配置在webapp/WEB-INF/web.xml中 <!-- 解决post乱码 --><filter> <filter-name>Character ...
- python学习之老男孩python全栈第九期_数据库day003 -- 作业
数据库: class: course: student: teacher: score: /* Navicat Premium Data Transfer Source Server : local ...
- Codeforces 750 F:New Year and Finding Roots
传送门 首先如果一开始就找到了一个叶子,那么暴力去递归找它的父亲,每次随机一个方向(除了已知的儿子)走深度次,如果走到了一个叶子就不是这个方向 (设根的深度为 \(1\))这样子最后到达深度为 \(3 ...
- 在RecyclerView列表滚动的时候显示或者隐藏Toolbar
先看一下效果: 本文将讲解如何实现类似于Google+应用中,当列表滚动的时候,ToolBar(以及悬浮操作按钮)的显示与隐藏(向下滚动隐藏,向上滚动显示),这种效果在Material Design ...