Haven’t written anything on here for a while – so I am going to start getting back on it.
Here’s some nice code to get a directory listing from FTP. You get back a list of FTPListDetail objects which can be used to pass to further implementations, such as a download / downloadasync etc. It uses some nice regex to parse the FTP response.
///<summary>
/// Returns a directory listing of the remote FTP host.
///</summary>
///<returns></returns>
public IEnumerable<FTPListDetail> GetDirectoryListing()
{
var result = new StringBuilder();
var request = GetWebRequest(WebRequestMethods.Ftp.ListDirectoryDetails);
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append(“\n”);
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf(‘\n’), 1);
var results = result.ToString().Split(‘\n’);
string regex =
@”^” + //# Start of line
@”(?<dir>[\-ld])” + //# File size
@”(?<permission>[\-rwx]{9})” + //# Whitespace \n
@”\s+” + //# Whitespace \n
@”(?<filecode>\d+)” +
@”\s+” + //# Whitespace \n
@”(?<owner>\w+)” +
@”\s+” + //# Whitespace \n
@”(?<group>\w+)” +
@”\s+” + //# Whitespace \n
@”(?<size>\d+)” +
@”\s+” + //# Whitespace \n
@”(?<month>\w{3})” + //# Month (3 letters) \n
@”\s+” + //# Whitespace \n
@”(?<day>\d{1,2})” + //# Day (1 or 2 digits) \n
@”\s+” + //# Whitespace \n
@”(?<timeyear>[\d:]{4,5})” + //# Time or year \n
@”\s+” + //# Whitespace \n
@”(?<filename>(.*))” + //# Filename \n
@”$”; //# End of line
foreach (var parsed in results)
{
var split = new Regex(regex)
.Match(parsed);
var dir = split.Groups["dir"].ToString();
var permission = split.Groups["permission"].ToString();
var filecode = split.Groups["filecode"].ToString();
var owner = split.Groups["owner"].ToString();
var group = split.Groups["group"].ToString();
var size = split.Groups["size"].ToString();
var month = split.Groups["month"].ToString();
var timeYear = split.Groups["timeyear"].ToString();
var day = split.Groups["day"].ToString();
var filename = split.Groups["filename"].ToString();
yield return new FTPListDetail()
{
Dir = dir,
Filecode = filecode,
Group = group,
FullPath = CurrentRemoteDirectory + “/” + filename,
Name = filename,
Owner = owner,
Permission = permission,
Size = size.ToInt() ?? 0,
Month = month,
Day = day,
YearTime = timeYear
};
};
}
}
}
///<summary>
/// Get the request using a specific URI
///</summary>
///<param name=”method”></param>
///<param name=”uri”></param>
///<returns></returns>
private FtpWebRequest GetWebRequest(string method, string uri)
{
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return null;
}
var reqFTP = (FtpWebRequest)FtpWebRequest.Create(serverUri);
reqFTP.Method = method;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(Connection.Username, Connection.Password);
reqFTP.Proxy = null;
reqFTP.KeepAlive = false;
reqFTP.UsePassive = false;
return reqFTP;
}
public class FTPListDetail
{
public bool IsDirectory
{
get
{
return !string.IsNullOrWhiteSpace(Dir) && Dir.EqualsIgnoreCase(“D”);
}
}
internal string Dir { get; set; }
public string Permission { get; set; }
public string Filecode { get; set; }
public string Owner { get; set; }
public string Group { get; set; }
public int Size { get; set; }
public string Name { get; set; }
public string FullPath { get; set; }
internal string Month { get; set; }
internal string Day { get; set; }
internal string YearTime { get; set; }
public DateTime Date
{
get
{
var month = DateTime.ParseExact(Month, “MMM”, CultureInfo.CurrentCulture).Month;
if (!YearTime.Contains(“:”))
{
return new DateTime(YearTime.ToInt() ?? 0, month, Day.ToInt() ?? 0);
}
else
{
var dateTime = YearTime.Split(new string[] { “:” }, StringSplitOptions.RemoveEmptyEntries);
if (dateTime.Count() == 2)
{
int hour = dateTime[0].ToInt() ?? 0;
int minute = dateTime[1].ToInt() ?? 0;
return new DateTime(DateTime.Now.Year, month, Day.ToInt() ?? 0, hour, minute, 0);
}
return new DateTime(DateTime.Now.Year, Month.ToInt() ?? 0, Day.ToInt() ?? 0);
}
}
}
public override string ToString()
{
return string.Format(“{0} {1} {2} {3} {4} {5} {6} {7}”,
Dir,
Permission,
Filecode,
Owner,
Group,
Size,
Date.ToShortDateString(),
Name
);
}
}