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>
/// 获取当前目录下的目录及文件
/// </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("//", "/");
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;//该方法可以得到文件名称的详细资源
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连接错误,错误原因:" + Environment.NewLine + ex.Message });
}
return ftpfileList;
});
}