// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Globalization; namespace E { public static class FTP { public class Entry { public string ParentURL { get; set; } public string Filename { get; set; } public long Size { get; set; } public DateTime Time { get; set; } public bool Directory { get; set; } } public static string ListRaw(string url) { FtpWebRequest req = (FtpWebRequest)WebRequest.Create(url); req.Method = WebRequestMethods.Ftp.ListDirectoryDetails; using(FtpWebResponse resp = (FtpWebResponse)req.GetResponse()) { using(StreamReader sr = new StreamReader(resp.GetResponseStream())) { return sr.ReadToEnd(); } } } private static string ParseLine(string line, int ix, int n) { string res = ""; int ws = 0; for (int i = 1; i < line.Length; i++) { if ((line[i] == ' ') && (line[i - 1] != ' ')) { ws = ws + 1; } if ((ws >= ix) && (ws < (ix + n))) { res = res + line[i]; } } return res.Trim(); } private static DateTime ParseTime(string s) { DateTime dt; if(DateTime.TryParseExact(s, "MMM d yyyy ", new CultureInfo("en-US"), DateTimeStyles.AllowWhiteSpaces, out dt)) { return dt; } else if(DateTime.TryParseExact(s, "MMM d HH:mm ", new CultureInfo("en-US"), DateTimeStyles.AllowWhiteSpaces, out dt)) { return dt; } else { throw new Exception("Can not parse time: " + s); } } private static Entry Parse(string line, string url) { string protection = ParseLine(line, 0, 1); long size = long.Parse(ParseLine(line, 4, 1)); string time = ParseLine(line, 5, 3); string filename = ParseLine(line, 8, 100); return new Entry { ParentURL=url, Filename=filename, Size=size, Time=ParseTime(time), Directory=line[0]=='d' }; } public static IList List(string url) { IList res = new List(); string raw = ListRaw(url); StringReader sr = new StringReader(raw); string line; while((line = sr.ReadLine()) != null) { if(line.Length > 40) { res.Add(Parse(line, url)); } } return res; } public static IList ListRecursive(Queue urls) { List res = new List(); while(urls.Count > 0) { string url = urls.Dequeue(); IList tmp = List(url); foreach(Entry e in tmp) { if(e.Directory) { urls.Enqueue(url + e.Filename + "/"); } } res.AddRange(tmp); } return res; } public static IList ListRecursive(string url) { Queue urls = new Queue(); urls.Enqueue(url); return ListRecursive(urls); } } public class Program { public static void Main(string[] args) { Console.WriteLine(FTP.ListRaw("ftp://ftp.dkuug.dk/pub/Xorg/")); foreach(FTP.Entry e in FTP.List("ftp://ftp.dkuug.dk/pub/Xorg/")) { Console.WriteLine(e.Filename + " " + e.Size + " " + e.Time + " " + e.Directory); } foreach(FTP.Entry e in FTP.ListRecursive("ftp://ftp.dkuug.dk/pub/Xorg/contrib/utilities/")) { Console.WriteLine(e.ParentURL + e.Filename + " " + e.Size + " " + e.Time + " " + e.Directory); } } } }