Beispiel #1
0
        /* List Directory Contents in Detail (Name, Size, Created, etc.) */
        public List <Item> DirectoryListDetailed(string directory)
        {
            try
            {
                /* Create an FTP Request */
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
                /* Log in to the FTP Server with the User Name and Password Provided */
                ftpRequest.Credentials = new NetworkCredential(user, pass);
                /* When in doubt, use these options */
                ftpRequest.UseBinary  = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive  = true;
                /* Specify the Type of FTP Request */
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                /* Establish Return Communication with the FTP Server */
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                /* Establish Return Communication with the FTP Server */
                ftpStream = ftpResponse.GetResponseStream();
                /* Get the FTP Server's Response Stream */
                StreamReader ftpReader = new StreamReader(ftpStream);
                /* Store the Raw Response */
                var directoryRaw = new List <string>(); //string directoryRaw = null;
                /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
                //try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } }
                try { while (ftpReader.Peek() != -1)
                      {
                          directoryRaw.Add(ftpReader.ReadLine());
                      }
                      directoryRaw.ToArray(); }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                /* Resource Cleanup */
                ftpReader.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
                /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
                try
                {
                    Regex regex = new Regex(@"^([d-])([rwxt-]{3}){3}\s+\d{1,}\s+.*?(\d{1,})\s+(\w+\s+\d{1,2}\s+(?:\d{4})?)(\d{1,2}:\d{2})?\s+(.+?)\s?$",
                                            RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

                    // Получаем список корневых файлов и папок
                    // Используется LINQ to Objects и регулярные выражения
                    List <Item> list = directoryRaw.Select(s =>
                    {
                        Match match = regex.Match(s);
                        if (match.Length > 5)
                        {
                            // Устанавливаем тип, чтобы отличить файл от папки (используется также для установки рисунка);
                            string type = match.Groups[1].Value == "d" ? "<dir>" : null;

                            // Размер задаем только для файлов, т.к. для папок возвращается размер ярлыка 4кб, а не самой папки
                            string size = null;
                            if (type != "<dir>")
                            {
                                //size = (Int32.Parse(match.Groups[3].Value.Trim()) / 1024).ToString() + " кБ";
                                size = Operations.SizeConverter(Double.Parse(match.Groups[3].Value.Trim()));
                            }
                            return(new Item(match.Groups[6].Value, type, size, directory));
                        }
                        else
                        {
                            return(new Item());
                        }
                    }).ToList();
                    return(list);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString() + ": \n" + ex.Message);
                }
                //try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; }
                //catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            /* Return an Empty string Array if an Exception Occurs */
            return(new List <Item>());
        }