public static string FTPRegexDir = @"\s*(?<size>[0-9]*)\s*(?<month>(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\s*(?<day>[0-9]*)\s*(?<yearTime>([0-9]|:)*)\s*(?<fileName>.*)"; //FTP解析正則字串
public static string FTPRegexDD = @"^(\d+-\d+-\d+\s+\d+:\d+(?:AM|PM))\s+(<DIR>|\d+)\s+(.+)$"; //FTP解析正則字串
/// <summary>
/// 獲取當(dāng)前目錄下的目錄及文件
/// </summary>
/// param name="ftpfileList"></param>
/// <param name="dirName"></param>
/// <returns></returns>
public static List<ActFile> GetFtpFile(string dirName, int ilevel = 0)
{
var ftpfileList = new List<ActFile>();
return MethodInvoke($@"GetFtpFile({dirName})", () =>
{
string tempDir = dirName;
tempDir = tempDir.Replace("http://", "/");
if (Data.Left(tempDir, 1) == "/") { tempDir = Data.Right(tempDir, tempDir.Length - 1); }
if (Data.Right(tempDir, 1) == "/") { tempDir = Data.Left(tempDir, tempDir.Length - 1); }
string url = "ftp://" + ftpHostIP + ":" + ftpHostPort + "/"+ tempDir;
try
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(url));
ftpRequest.UseBinary = true;
ftpRequest.Credentials = new NetworkCredential(username, password);
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;//該方法可以得到文件名稱的詳細(xì)資源
StreamReader ftpFileListReader = new StreamReader(ftpRequest.GetResponse().GetResponseStream(), Encoding.UTF8);
while (!ftpFileListReader.EndOfStream)
{
string line = ftpFileListReader.ReadLine();
string firstChr = Data.Left(line, 1);
string fileSize = "";
string fileName = "";
bool isDirTemp = false;
if (firstChr == "d" || firstChr == "-")
{
Regex FtpListDirDetailsRegex = new Regex(FTPRegexDir, RegexOptions.Compiled | RegexOptions.IgnoreCase);
Match match = FtpListDirDetailsRegex.Match(line);
fileSize = match.Groups["size"].Value;
fileName = match.Groups["fileName"].Value;
}
else
{
Regex FtpListDirDetailsRegex = new Regex(FTPRegexDD, RegexOptions.Compiled | RegexOptions.IgnoreCase);
Match match = FtpListDirDetailsRegex.Match(line);
fileSize = match.Groups[2].Value;
fileName = match.Groups[3].Value;
}
if (firstChr == "d" || line.IndexOf("<DIR>") > -1)
{
fileSize = "0";
isDirTemp = true;
}
ftpfileList.Add(new ActFile { isDir = isDirTemp, name = fileName, path = "/" + tempDir, level = ilevel, size = fileSize, lineStr = line });
}
ftpFileListReader.Close();
}
catch (Exception ex)
{
ftpfileList.Add(new ActFile { isDir = true, name = "", path = "/" + tempDir, level = ilevel, size = "0", lineStr = "FTP連接錯(cuò)誤,錯(cuò)誤原因:" + Environment.NewLine + ex.Message });
}
return ftpfileList;
});
}