C#-连接到FTP服务器
我想用FTPWebRequest构建一个小型FTP客户端,我只是想获得一些帮助,以便连接和获取标题信息,向用户展示我认为我可以从中了解应用程序的其余部分。这篇文章很好,你可以在这里找到如何在.NET中构建一个简单的FTP客户端 此外,我可能会给你一些建议,例如,你想检查文件是否在FTP服务器上可用,在这种情况下,你可以只检查它的大小 以下是负责这项工作的职能:C#-连接到FTP服务器,c#,ftpwebrequest,C#,Ftpwebrequest,我想用FTPWebRequest构建一个小型FTP客户端,我只是想获得一些帮助,以便连接和获取标题信息,向用户展示我认为我可以从中了解应用程序的其余部分。这篇文章很好,你可以在这里找到如何在.NET中构建一个简单的FTP客户端 此外,我可能会给你一些建议,例如,你想检查文件是否在FTP服务器上可用,在这种情况下,你可以只检查它的大小 以下是负责这项工作的职能: public bool IsFtpFileExists(string remoteUri, out long remFi
public bool IsFtpFileExists(string remoteUri, out long remFileSize)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(BuildServerUri(remoteUri));
FtpWebResponse response;
request.Method = WebRequestMethods.Ftp.GetFileSize;
request.Credentials = new NetworkCredential(Username, Password);
try
{
response = (FtpWebResponse)request.GetResponse();
remFileSize = response.ContentLength;
return true;
}
catch (WebException we)
{
response = we.Response as FtpWebResponse;
if (response != null && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
remFileSize = 0;
return false;
}
throw;
}
}
下面是获取目录信息的示例。GetDirectoryInformation方法位于代码示例的底部。这应该包括基于Windows和Unix的Ftp。还有一个比较完整的
class-Ftp
{
公共结构文件结构
{
公共字符串标志;
公共字符串所有者;
公共字符串组;
公共图书馆主任;
公共日期时间;
公共字符串名称;
}
公共枚举文件列表样式
{
UnixStyle,
窗口样式,
不为人知
}
私有列表GetList(字符串数据字符串)
{
List myListArray=新列表();
string[]dataRecords=datastring.Split('\n');
FileListStyle\u directoryListStyle=GuessFileListStyle(数据记录);
foreach(数据记录中的字符串s)
{
if(_directoryListStyle!=FileListStyle.Unknown&&s!=“”)
{
FileStruct f=newfilestruct();
f、 Name=“…”;
开关(_directoryListStyle)
{
case FileListStyle.UnixStyle:
f=从UnixStyleRecord解析文件结构;
打破
案例FileListStyle.WindowsStyle:
f=ParseFileStructFromWindowsStyleRecord;
打破
}
如果(!(f.Name==“|f.Name==”))
{
添加(f);
}
}
}
返回mylistaray;
}
私有文件结构ParseFileStructFromWindowsStyleRecord(字符串记录)
{
///假设记录样式为
///02-03-11 07:46下午
FileStruct f=newfilestruct();
字符串processstr=Record.Trim();
字符串dateStr=processstr.Substring(0,8);
processstr=(processstr.Substring(8,processstr.Length-8)).Trim();
字符串timeStr=processstr.Substring(0,7);
processstr=(processstr.Substring(7,processstr.Length-7)).Trim();
f、 CreateTime=DateTime.Parse(dateStr+“”+timeStr);
if(processstr.Substring(0,5)==“”)
{
f、 IsDirectory=true;
processstr=(processstr.Substring(5,processstr.Length-5)).Trim();
}
其他的
{
字符串[]strs=processstr.Split(新字符[]{''});
processstr=strs[1].Trim();
f、 IsDirectory=false;
}
f、 Name=processstr;//Rest是Name
返回f;
}
公共FileListStyle猜测FileListStyle(字符串[]记录列表)
{
foreach(记录列表中的字符串s)
{
如果(s.Length>10&&Regex.IsMatch(s.Substring(0,10),“(-d)(-r)(-w)(-x)(-r)(-w)(-w)(-x)(-r)(-r)(-w)(-x)”)
{
返回FileListStyle.UnixStyle;
}
if(s.Length>8&&Regex.IsMatch(s.Substring(0,8),“[0-9][0-9]-[0-9][0-9]-[0-9][0-9]”)
{
返回FileListStyle.WindowsStyle;
}
}
返回FileListStyle。未知;
}
私有文件结构ParseFileStructFromUnixStyleRecord(字符串记录)
{
///假设记录样式为
///dr-xr-xr-x 1所有者组0 2011年2月25日bussys
FileStruct f=newfilestruct();
字符串processstr=record.Trim();
f、 Flags=processstr.Substring(0,9);
f、 IsDirectory=(f.Flags[0]='d');
processstr=(processstr.Substring(11)).Trim();
_cutSubstringFromStringWithTrim(参考processstr',0);//跳过一部分
f、 Owner=_cutSubstringFromStringWithTrim(参考processstr,,,0);
f、 Group=_cutSubstringFromStringWithTrim(参考PROCESSTR,,,0);
_cutSubstringFromStringWithTrim(参考processstr',0);//跳过一部分
DateTime createTime=DateTime.Now;
var dateString=_cutSubstringFromStringWithTrim(参考processstr',8);
TryParse(dateString,out createTime);
f、 CreateTime=CreateTime;
f、 Name=processstr;//部件的其余部分是Name
返回f;
}
私有字符串_cutSubstringFromStringWithTrim(参考字符串s、字符c、整数起始索引)
{
int pos1=s.IndexOf(c,startIndex);
string retString=s.Substring(0,pos1);
s=(s.Substring(pos1)).Trim();
返回字符串;
}
公共列表GetDirectoryInformation(字符串ftpUri,网络凭据NetworkCredential)
{
List directoryInfo=新列表();
尝试
{
FtpWebRequest ftpClientRequest=WebRequest.Create(ftpUri)作为FtpWebRequest;
ftpClientRequest.Method=WebRequestMethods.Ftp.ListDirectoryDetails;
ftpClientRequest.Proxy=null;
ftpClientRequest.Credentials=网络凭据;
FtpWebResponse response=ftpClientRequest.GetResponse()作为FtpWebResponse;
流动
class Ftp
{
public struct FileStruct
{
public string Flags;
public string Owner;
public string Group;
public bool IsDirectory;
public DateTime CreateTime;
public string Name;
}
public enum FileListStyle
{
UnixStyle,
WindowsStyle,
Unknown
}
private List<FileStruct> GetList(string datastring)
{
List<FileStruct> myListArray = new List<FileStruct>();
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 == ".."))
{
myListArray.Add(f);
}
}
}
return myListArray; ;
}
private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)
{
///Assuming the record style as
/// 02-03-11 07:46PM <DIR> Append
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 = DateTime.Parse(dateStr + " " + timeStr);
if (processstr.Substring(0, 5) == "<DIR>")
{
f.IsDirectory = true;
processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();
}
else
{
string[] strs = processstr.Split(new char[] { ' ' });
processstr = strs[1].Trim();
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)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))
{
return FileListStyle.UnixStyle;
}
if (s.Length > 8 && Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))
{
return FileListStyle.WindowsStyle;
}
}
return FileListStyle.Unknown;
}
private FileStruct ParseFileStructFromUnixStyleRecord(string record)
{
///Assuming record style as
/// dr-xr-xr-x 1 owner group 0 Feb 25 2011 bussys
FileStruct f = new FileStruct();
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.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
_cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //skip one part
DateTime createTime = DateTime.Now;
var dateString = _cutSubstringFromStringWithTrim(ref processstr, ' ', 8);
DateTime.TryParse(dateString, out createTime);
f.CreateTime = createTime;
f.Name = processstr; //Rest of the part is name
return f;
}
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;
}
public List<FileStruct> GetDirectoryInformation(string ftpUri, NetworkCredential networkCredential)
{
List<FileStruct> directoryInfo = new List<FileStruct>();
try
{
FtpWebRequest ftpClientRequest = WebRequest.Create(ftpUri) as FtpWebRequest;
ftpClientRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftpClientRequest.Proxy = null;
ftpClientRequest.Credentials = networkCredential;
FtpWebResponse response = ftpClientRequest.GetResponse() as FtpWebResponse;
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
string datastring = sr.ReadToEnd();
response.Close();
directoryInfo = GetList(datastring);
return directoryInfo;
}
catch (Exception e)
{
return directoryInfo;
}
}
}