獲取ftp伺服器檔案和目錄列表
阿新 • • 發佈:2019-02-10
下面只是我從轉載地址提取的自己需要的部分,加了一下自己的變數。原版本功能更強大,請看連結
using System;
using System.Collections.Generic;using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.IO;
using System.Net;
namespace DataDownloader.Class
{
class FtpExplorer
{
private string username;
private string password;
private string uri;
public FtpExplorer(string username, string password, string uri)
{
this.username = username;
this.password = password;
this.uri = uri;
}
#region ftp下載瀏覽資料夾資訊
/// <summary>
/// 得到當前目錄下的所有目錄和檔案
/// </summary>
/// <param name="srcpath">瀏覽的目錄</param>
/// <returns></returns>
public List<FileStruct> GetFileList(string srcpath)
{
List<FileStruct> list = new List<FileStruct>();
FtpWebRequest reqFtp;
WebResponse response = null;
string ftpuri = string.Format("ftp://{0}/{1}", uri, srcpath);
try
{
reqFtp = (FtpWebRequest)FtpWebRequest.Create(ftpuri);
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(username, password);
reqFtp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
response = reqFtp.GetResponse();
list =ListFilesAndDirectories((FtpWebResponse)response).ToList();
response.Close();
}
catch
{
if (response != null)
{
response.Close();
}
}
return list;
}
#endregion
#region 列出目錄檔案資訊
/// <summary>
/// 列出FTP伺服器上面當前目錄的所有檔案和目錄
/// </summary>
public FileStruct[] ListFilesAndDirectories(FtpWebResponse Response)
{
//Response = Open(this.Uri, WebRequestMethods.Ftp.ListDirectoryDetails);
StreamReader stream = new StreamReader(Response.GetResponseStream(), Encoding.Default);
string Datastring = stream.ReadToEnd();
FileStruct[] list = GetList(Datastring);
return list;
}
/// <summary>
/// 列出FTP伺服器上面當前目錄的所有檔案
/// </summary>
//public FileStruct[] ListFiles()
//{
// FileStruct[] listAll = ListFilesAndDirectories();
// List<FileStruct> listFile = new List<FileStruct>();
// foreach (FileStruct file in listAll)
// {
// if (!file.IsDirectory)
// {
// listFile.Add(file);
// }
// }
// return listFile.ToArray();
//}
/// <summary>
/// 列出FTP伺服器上面當前目錄的所有的目錄
/// </summary>
//public FileStruct[] ListDirectories()
//{
// FileStruct[] listAll = ListFilesAndDirectories();
// List<FileStruct> listDirectory = new List<FileStruct>();
// foreach (FileStruct file in listAll)
// {
// if (file.IsDirectory)
// {
// listDirectory.Add(file);
// }
// }
// return listDirectory.ToArray();
//}
/// <summary>
/// 獲得檔案和目錄列表
/// </summary>
/// <param name="datastring">FTP返回的列表字元資訊</param>
private 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.ToArray();
}
/// <summary>
/// 從Windows格式中返回檔案資訊
/// </summary>
/// <param name="Record">檔案資訊</param>
private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)
{
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();
DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;
myDTFI.ShortTimePattern = "t";
f.CreateTime = DateTime.Parse(dateStr + " " + timeStr, myDTFI);
if (processstr.Substring(0, 5) == "<DIR>")
{
f.IsDirectory = true;
processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();
}
else
{
string[] strs = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // true);
processstr = strs[1];
f.IsDirectory = false;
}
f.Name = processstr;
return f;
}
/// <summary>
/// 判斷檔案列表的方式Window方式還是Unix方式
/// </summary>
/// <param name="recordList">檔案資訊列表</param>
private 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;
}
else 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;
}
/// <summary>
/// 從Unix格式中返回檔案資訊
/// </summary>
/// <param name="Record">檔案資訊</param>
private FileStruct ParseFileStructFromUnixStyleRecord(string Record)
{
FileStruct f = new FileStruct();
string processstr = Record.Trim();
f.Flags = processstr.Substring(0, 10);
f.IsDirectory = (f.Flags[0] == 'd');
processstr = (processstr.Substring(11)).Trim();
_cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳過一部分
f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
f.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
f.Size=_cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2];
int m_index = processstr.IndexOf(yearOrTime);
if (yearOrTime.IndexOf(":") >= 0) //time
{
processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());
}
f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', 8)+" "+yearOrTime);
f.Name = processstr; //最後就是名稱
return f;
}
/// <summary>
/// 按照一定的規則進行字串擷取
/// </summary>
/// <param name="s">擷取的字串</param>
/// <param name="c">查詢的字元</param>
/// <param name="startIndex">查詢的位置</param>
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;
}
#endregion
public string Username
{
get { return username; }
set { username = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public string Uri
{
get { return uri; }
set { uri = value; }
}
}
}