文件传输协议FTP操作实现汇总.docx
- 文档编号:30536820
- 上传时间:2023-08-16
- 格式:DOCX
- 页数:30
- 大小:81.64KB
文件传输协议FTP操作实现汇总.docx
《文件传输协议FTP操作实现汇总.docx》由会员分享,可在线阅读,更多相关《文件传输协议FTP操作实现汇总.docx(30页珍藏版)》请在冰豆网上搜索。
文件传输协议FTP操作实现汇总
文件传输协议(FTP)操作(上传,下载,新建,删除,FTP间传送文件等)实现汇总
Microsoft.NETFramework2.0新增加了3个类使我们很方便的对文件传输协议(FTP)服务器进行操作
FtpWebRequest类:
实现文件传输协议(FTP)客户端
publicsealedclassFtpWebRequest:
WebRequest
FtpWebResponse类:
封装文件传输协议(FTP)服务器对请求的响应
publicclassFtpWebResponse:
WebResponse,IDisposable
WebRequestMethods.Ftp类:
表示可与FTP请求一起使用的FTP协议方法的类型,无法继承此类
publicstaticclassFtp
类关系图
操作ftp的一般步骤我总结如下:
第一步:
WebRequest.Create方法,获得FtpWebRequest的实例
第二步:
利用WebRequestMethods.Ftp设置FtpWebRequest的Method属性,指定使用的FTP协议方法的类型
第三步:
设置FtpWebRequest的Credentials属性,指定用户名和密码
第四步:
发出请求
第五步:
接收响应数据流(有些ftp操作可能没这一步,例如给文件夹改名)
第六步:
关闭流
下面从几段代码来分别展示ftp的不同操作:
1.文件夹和文件信息
关键知识说明:
a.FtpWebRequest类没有公开的构造函数,我们通过WebRequest.Create方法,获得FtpWebRequest的实例
b.通过WebRequestMethods.Ftp.ListDirectoryDetails(详细列表)或者WebRequestMethods.Ftp.ListDirectory(简短列表)获取FTP服务器上的文件列表
c.请求返回的数据在GetResponseStream方法返回的流中
d.字符编码请用System.Text.Encoding.Default,要不中文名会乱码
e.FtpWebRequest.Credentials属性设置登陆用户名和密码
f.FtpWebRequest.UseBinary属性,true,指示服务器要传输的是二进制数据.false,指示数据为文本。
默认值为true
g.FtpWebRequest.EnableSsl属性,如果控制和数据传输是加密的,则为true.否则为false.默认值为false
实例代码:
获取
Uriuri=newUri(");
FtpWebRequestlistRequest=(FtpWebRequest)WebRequest.Create(uri);
listRequest.Method=WebRequestMethods.Ftp.ListDirectoryDetails;
//listRequest.Method=WebRequestMethods.Ftp.ListDirectory;
stringftpUser="";
stringftpPassWord="";
listRequest.Credentials=newNetworkCredential(ftpUser,ftpPassWord);
FtpWebResponselistResponse=(FtpWebResponse)listRequest.GetResponse();
StreamresponseStream=listResponse.GetResponseStream();
StreamReaderreadStream=newStreamReader(responseStream,System.Text.Encoding.Default);
if(readStream!
=null)
{
MessageBox.Show(readStream.ReadToEnd());
}
MessageBox.Show(string.Format("状态:
{0},{1}",listResponse.StatusCode,listResponse.StatusDescription));
listResponse.Close();
responseStream.Close();
readStream.Close();
通过WebRequestMethods.Ftp.ListDirectoryDetails(详细列表)或者WebRequestMethods.Ftp.ListDirectory(简短列表)返回的结果是不一样的.请看图
利用WebRequestMethods.Ftp.ListDirectoryDetails,readStream.ReadToEnd()返回的字符串比较复杂(不同类型的Ftp会有不同返回形式的返回结果),要把里面的文件夹和文件区分别列出来比较繁琐,代码比较多.
大概的调用方法如下:
stringdataString=readStream.ReadToEnd();
DirectoryListParserparser=newDirectoryListParser(dataString);
FileStruct[]fs=parser.FullListing;
返回的FileStruct有一个属性IsDirectory,可以区分文件夹和文件
DirectoryListParser类代码如下:
using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
namespace WindowsApplicationFTP
{
public struct FileStruct
{
public string Flags;
public string Owner;
public bool IsDirectory;
public string CreateTime;
public string Name;
}
public enum FileListStyle
{
UnixStyle,
WindowsStyle,
Unknown
}
public class DirectoryListParser
{
private List
public FileStruct[] FullListing
{
get
{
return _myListArray.ToArray();
}
}
public FileStruct[] FileList
{
get
{
List
foreach(FileStruct thisstruct in _myListArray)
{
if(!
thisstruct.IsDirectory)
{
_fileList.Add(thisstruct);
}
}
return _fileList.ToArray();
}
}
public FileStruct[] DirectoryList
{
get
{
List
foreach(FileStruct thisstruct in _myListArray)
{
if(thisstruct.IsDirectory)
{
_dirList.Add(thisstruct);
}
}
return _dirList.ToArray();
}
}
public DirectoryListParser(string responseString)
{
_myListArray = GetList(responseString);
}
private List
{
List
string[] dataRecords = datastring.Split('\n');
FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);
foreach (string s in dataRecords)
{
if (_directoryListStyle !
= FileListStyle.Unknown && s !
= "")
{
FileStruct f = new FileStruct();
f.Name = "..";
switch (_directoryListStyle)
{
case FileListStyle.UnixStyle:
f = ParseFileStructFromUnixStyleRecord(s);
break;
case FileListStyle.WindowsStyle:
f = ParseFileStructFromWindowsStyleRecord(s);
break;
}
if (f.Name !
= "" && f.Name !
= "." && f.Name !
= "..")
{
myListArray.Add(f);
}
}
}
return myListArray;
}
private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)
{
///Assuming the record style as
/// 02-03-04 07:
46PM
FileStruct f = new FileStruct();
string processstr = Record.Trim();
string dateStr = processstr.Substring(0,8);
processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();
string timeStr = processstr.Substring(0, 7);
processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();
f.CreateTime = dateStr + " " + timeStr;
if (processstr.Substring(0,5) == "
{
f.IsDirectory = true;
processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();
}
else
{
string[] strs = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
processstr = strs[1];
f.IsDirectory = false;
}
f.Name = processstr; //Rest is name
return f;
}
public FileListStyle GuessFileListStyle(string[] recordList)
{
foreach (string s in recordList)
{
if(s.Length > 10
&& Regex.IsMatch(s.Substring(0,10),"(-|d)((-|r)(-|w)(-|x)){3}"))
{
return FileListStyle.UnixStyle;
}
else if (s.Length > 8
&& Regex.IsMatch(s.Substring(0, 8), "[0-9]{2}-[0-9]{2}-[0-9]{2}"))
{
return FileListStyle.WindowsStyle;
}
}
return FileListStyle.Unknown;
}
private FileStruct ParseFileStructFromUnixStyleRecord(string record)
{
///Assuming record style as
/// dr-xr-xr-x 1 owner group 0 Nov 25 2002 bussys
FileStruct f = new FileStruct();
if (record[0] == '-' || record[0] == 'd')
{// its a valid file record
string processstr = record.Trim();
f.Flags = processstr.Substring(0, 9);
f.IsDirectory = (f.Flags[0] == 'd');
processstr = (processstr.Substring(11)).Trim();
_cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //skip one part
f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
f.CreateTime = getCreateTimeString(record);
int fileNameIndex = record.IndexOf(f.CreateTime)+f.CreateTime.Length;
f.Name = record.Substring(fileNameIndex).Trim(); //Rest of the part is name
}
else
{
f.Name = "";
}
return f;
}
private string getCreateTimeString(string record)
{
//Does just basic datetime string validation for demo, not an accurate check
//on date and time fields
string month = "(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)";
string space = @"(\040)+";
string day = "([0-9]|[1-3][0-9])";
string year = "[1-2][0-9]{3}";
string time = "[0-9]{1,2}:
[0-9]{2}";
Regex dateTimeRegex = new Regex(month+space+day+space+"("+year+"|"+time+")", RegexOptions.IgnoreCase);
Match match = dateTimeRegex.Match(record);
return match.Value;
}
private string _cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)
{
int pos1 = s.IndexOf(c, startIndex);
string retString = s.Substring(0,pos1);
s = (s.Substring(pos1)).Trim();
return retString;
}
}
}
2.取ftp登陆身份验证完成后的欢迎信息
关键知识说明:
a.FtpWebResponse.WelcomeMessage属性获取身份验证完成时FTP服务器发送的消息
实例代码:
获取
Uriuri=newUri("
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 文件传输 协议 FTP 操作 实现 汇总