)>}]
شركة التطبيقات المتكاملة لتصميم وبرمجة البرمجيات الخاصة ش.ش.و.
Integrated Applications Programming Company
Home » Code Library » Ftp (Ia.Cl.Model)

Public general use code classes and xml files that we've compiled and used over the years:

A wrapper class for .NET 2.0 FTP

    1: using System;
    2: using System.Collections.Generic;
    3: using System.IO;
    4: using System.Net;
    5: using System.Text.RegularExpressions;
    6: using static System.Net.WebRequestMethods;
    7:  
    8: namespace Ia.Cl.Model
    9: {
   10:     /// <summary publish="true">
   11:     /// A wrapper class for .NET 2.0 FTP
   12:     /// </summary>
   13:     /// <remarks> 
   14:     /// This class does not hold open an FTP connection but instead is stateless: for each FTP request it connects, performs the request and disconnects.
   15:     /// </remarks>
   16:     /// 
   17:     /// <remarks> 
   18:     /// Copyright � 2001-2024 Jasem Y. Al-Shamlan (info@ia.com.kw), Integrated Applications - Kuwait. All Rights Reserved.
   19:     ///
   20:     /// This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
   21:     /// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
   22:     ///
   23:     /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
   24:     /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
   25:     /// 
   26:     /// You should have received a copy of the GNU General Public License along with this library. If not, see http://www.gnu.org/licenses.
   27:     /// 
   28:     /// Copyright notice: This notice may not be removed or altered from any source distribution.
   29:     /// </remarks>
   30:     public class Ftp
   31:     {
   32:         private static bool usePassive;
   33:         private string hostName, userName, password, lastDirectory = string.Empty, currentDirectory = "/";
   34:  
   35:         ////////////////////////////////////////////////////////////////////////////
   36:  
   37:         /// <summary>
   38:         ///
   39:         /// </summary>
   40:         public Ftp()
   41:         {
   42:         }
   43:  
   44:         ////////////////////////////////////////////////////////////////////////////
   45:  
   46:         /// <summary>
   47:         ///
   48:         /// </summary>
   49:         public Ftp(string _hostName)
   50:         {
   51:             hostName = _hostName;
   52:         }
   53:  
   54:         ////////////////////////////////////////////////////////////////////////////
   55:  
   56:         /// <summary>
   57:         ///
   58:         /// </summary>
   59:         public Ftp(string _hostName, string _userName, string _password)
   60:         {
   61:             hostName = _hostName;
   62:             userName = _userName;
   63:             password = _password;
   64:  
   65:             usePassive = false;
   66:         }
   67:  
   68:         ////////////////////////////////////////////////////////////////////////////
   69:  
   70:         /// <summary>
   71:         ///
   72:         /// </summary>
   73:         public Ftp(string _hostName, string _userName, string _password, bool _usePassive)
   74:         {
   75:             hostName = _hostName;
   76:             userName = _userName;
   77:             password = _password;
   78:  
   79:             usePassive = _usePassive;
   80:         }
   81:  
   82:         ////////////////////////////////////////////////////////////////////////////
   83:  
   84:         /// <summary>
   85:         ///
   86:         /// </summary>
   87:         public List<string> ListDirectory(string directory)
   88:         {
   89:             System.Net.FtpWebRequest ftp = GetRequest(GetDirectory(directory));
   90:  
   91:             ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
   92:  
   93:             ftp.UsePassive = usePassive;
   94:  
   95:             string str = GetStringResponse(ftp);
   96:  
   97:             str = str.Replace("\r\n", "\r").TrimEnd('\r');
   98:  
   99:             List<string> result = new List<string>();
  100:  
  101:             result.AddRange(str.Split('\r'));
  102:  
  103:             return result;
  104:         }
  105:  
  106:         ////////////////////////////////////////////////////////////////////////////
  107:  
  108:         /// <summary>
  109:         ///
  110:         /// </summary>
  111:         public FtpDirectory ListDirectoryDetail(string directory)
  112:         {
  113:             System.Net.FtpWebRequest ftp = GetRequest(GetDirectory(directory));
  114:  
  115:             ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;
  116:  
  117:             ftp.UsePassive = usePassive;
  118:  
  119:             string str = GetStringResponse(ftp);
  120:  
  121:             str = str.Replace("\r\n", "\r").TrimEnd('\r');
  122:  
  123:             return new FtpDirectory(str, lastDirectory);
  124:         }
  125:  
  126:         ////////////////////////////////////////////////////////////////////////////
  127:  
  128:         /// <summary>
  129:         ///
  130:         /// </summary>
  131:         public bool Upload(string localFilename, string targetFilename)
  132:         {
  133:             if (!File.Exists(localFilename))
  134:             {
  135:                 throw (new ApplicationException("File " + localFilename + " not found"));
  136:             }
  137:  
  138:             FileInfo fi = new FileInfo(localFilename);
  139:  
  140:             return Upload(fi, targetFilename);
  141:         }
  142:  
  143:         ////////////////////////////////////////////////////////////////////////////
  144:  
  145:         /// <summary>
  146:         ///
  147:         /// </summary>
  148:         public bool Upload(FileInfo fi, string targetFilename)
  149:         {
  150:             string target;
  151:  
  152:             if (targetFilename.Trim() == "")
  153:             {
  154:                 target = this.CurrentDirectory + fi.Name;
  155:             }
  156:             else if (targetFilename.Contains("/"))
  157:             {
  158:                 target = AdjustDir(targetFilename);
  159:             }
  160:             else
  161:             {
  162:                 target = CurrentDirectory + targetFilename;
  163:             }
  164:  
  165:             string URI = Hostname + target;
  166:  
  167:             System.Net.FtpWebRequest ftp = GetRequest(URI);
  168:  
  169:             ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
  170:             ftp.UseBinary = true;
  171:  
  172:             ftp.UsePassive = usePassive;
  173:  
  174:             ftp.ContentLength = fi.Length;
  175:  
  176:             const int BufferSize = 2048;
  177:             byte[] content = new byte[BufferSize - 1 + 1];
  178:             int dataRead;
  179:  
  180:             using (FileStream fs = fi.OpenRead())
  181:             {
  182:                 using (Stream rs = ftp.GetRequestStream())
  183:                 {
  184:                     do
  185:                     {
  186:                         dataRead = fs.Read(content, 0, BufferSize);
  187:                         rs.Write(content, 0, dataRead);
  188:                     } while (!(dataRead < BufferSize));
  189:  
  190:                     // rs.Close();
  191:                 }
  192:             }
  193:  
  194:             ftp = null;
  195:  
  196:             return true;
  197:         }
  198:  
  199:         ////////////////////////////////////////////////////////////////////////////
  200:  
  201:         /// <summary>
  202:         ///
  203:         /// </summary>
  204:         public bool Download(string sourceFilename, string localFilename, bool PermitOverwrite)
  205:         {
  206:             FileInfo fi = new FileInfo(localFilename);
  207:  
  208:             return this.Download(sourceFilename, fi, PermitOverwrite);
  209:         }
  210:  
  211:         ////////////////////////////////////////////////////////////////////////////
  212:  
  213:         /// <summary>
  214:         ///
  215:         /// </summary>
  216:         public bool Download(FtpFileInfo file, string localFilename, bool PermitOverwrite)
  217:         {
  218:             return this.Download(file.FullName, localFilename, PermitOverwrite);
  219:         }
  220:  
  221:         ////////////////////////////////////////////////////////////////////////////
  222:  
  223:         /// <summary>
  224:         ///
  225:         /// </summary>
  226:         public bool Download(FtpFileInfo file, FileInfo localFI, bool PermitOverwrite)
  227:         {
  228:             return this.Download(file.FullName, localFI, PermitOverwrite);
  229:         }
  230:  
  231:         ////////////////////////////////////////////////////////////////////////////
  232:  
  233:         /// <summary>
  234:         ///
  235:         /// </summary>
  236:         public bool Download(string sourceFilename, FileInfo targetFI, bool PermitOverwrite)
  237:         {
  238:             if (targetFI.Exists && !(PermitOverwrite))
  239:             {
  240:                 throw (new ApplicationException("Target file already exists"));
  241:             }
  242:  
  243:             string target;
  244:  
  245:             if (sourceFilename.Trim() == "")
  246:             {
  247:                 throw (new ApplicationException("File not specified"));
  248:             }
  249:             else if (sourceFilename.Contains("/"))
  250:             {
  251:                 target = AdjustDir(sourceFilename);
  252:             }
  253:             else
  254:             {
  255:                 target = CurrentDirectory + sourceFilename;
  256:             }
  257:  
  258:             string URI = Hostname + target;
  259:  
  260:             System.Net.FtpWebRequest ftp = GetRequest(URI);
  261:  
  262:             ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
  263:             ftp.UseBinary = true;
  264:  
  265:             ftp.UsePassive = usePassive;
  266:  
  267:             using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
  268:             {
  269:                 using (Stream responseStream = response.GetResponseStream())
  270:                 {
  271:                     using (FileStream fs = targetFI.OpenWrite())
  272:                     {
  273:                         byte[] buffer = new byte[2048];
  274:                         int read = 0;
  275:  
  276:                         do
  277:                         {
  278:                             read = responseStream.Read(buffer, 0, buffer.Length);
  279:                             fs.Write(buffer, 0, read);
  280:                         } while (!(read == 0));
  281:  
  282:                         //responseStream.Close();
  283:                         //fs.Flush();
  284:                         //fs.Close();
  285:                     }
  286:  
  287:                     //responseStream.Close();
  288:                 }
  289:  
  290:                 //response.Close();
  291:             }
  292:  
  293:             return true;
  294:         }
  295:  
  296:         ////////////////////////////////////////////////////////////////////////////
  297:  
  298:         /// <summary>
  299:         ///
  300:         /// </summary>
  301:         public bool FtpDelete(string filename)
  302:         {
  303:             string URI = this.Hostname + GetFullPath(filename);
  304:  
  305:             System.Net.FtpWebRequest ftp = GetRequest(URI);
  306:  
  307:             ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
  308:  
  309:             ftp.UsePassive = usePassive;
  310:  
  311:             try
  312:             {
  313:                 string str = GetStringResponse(ftp);
  314:             }
  315:             catch (Exception)
  316:             {
  317:                 return false;
  318:             }
  319:  
  320:             return true;
  321:         }
  322:  
  323:         ////////////////////////////////////////////////////////////////////////////
  324:  
  325:         /// <summary>
  326:         ///
  327:         /// </summary>
  328:         public bool FtpFileExists(string filename)
  329:         {
  330:             // try to obtain filesize: if we get error msg containing "550" the file does not exist
  331:  
  332:             try
  333:             {
  334:                 long size = GetFileSize(filename);
  335:  
  336:                 return true;
  337:             }
  338:             catch (Exception ex)
  339:             {
  340:                 // only handle expected not-found exception
  341:                 if (ex is System.Net.WebException)
  342:                 {
  343:                     // file does not exist/no rights error = 550
  344:                     if (ex.Message.Contains("550"))
  345:                     {
  346:                         // clear
  347:                         return false;
  348:                     }
  349:                     else
  350:                     {
  351:                         throw;
  352:                     }
  353:                 }
  354:                 else
  355:                 {
  356:                     throw;
  357:                 }
  358:             }
  359:         }
  360:  
  361:         ////////////////////////////////////////////////////////////////////////////
  362:  
  363:         /// <summary>
  364:         ///
  365:         /// </summary>
  366:         public long GetFileSize(string filename)
  367:         {
  368:             string path;
  369:  
  370:             if (filename.Contains("/"))
  371:             {
  372:                 path = AdjustDir(filename);
  373:             }
  374:             else
  375:             {
  376:                 path = this.CurrentDirectory + filename;
  377:             }
  378:  
  379:             string URI = this.Hostname + path;
  380:             System.Net.FtpWebRequest ftp = GetRequest(URI);
  381:  
  382:             ftp.Method = System.Net.WebRequestMethods.Ftp.GetFileSize;
  383:  
  384:             ftp.UsePassive = usePassive;
  385:  
  386:             string tmp = this.GetStringResponse(ftp);
  387:  
  388:             return GetSize(ftp);
  389:         }
  390:  
  391:         ////////////////////////////////////////////////////////////////////////////
  392:  
  393:         /// <summary>
  394:         ///
  395:         /// </summary>
  396:         public bool FtpRename(string sourceFilename, string newName)
  397:         {
  398:             string source = GetFullPath(sourceFilename);
  399:  
  400:             if (!FtpFileExists(source))
  401:             {
  402:                 throw (new FileNotFoundException("File " + source + " not found"));
  403:             }
  404:  
  405:             string target = GetFullPath(newName);
  406:  
  407:             if (target == source)
  408:             {
  409:                 throw (new ApplicationException("Source and target are the same"));
  410:             }
  411:             else if (FtpFileExists(target))
  412:             {
  413:                 throw (new ApplicationException("Target file " + target + " already exists"));
  414:             }
  415:  
  416:             string URI = this.Hostname + source;
  417:  
  418:             System.Net.FtpWebRequest ftp = GetRequest(URI);
  419:  
  420:             ftp.Method = System.Net.WebRequestMethods.Ftp.Rename;
  421:             ftp.RenameTo = target;
  422:  
  423:             ftp.UsePassive = usePassive;
  424:  
  425:             try
  426:             {
  427:                 string str = GetStringResponse(ftp);
  428:             }
  429:             catch (Exception)
  430:             {
  431:                 return false;
  432:             }
  433:  
  434:             return true;
  435:         }
  436:  
  437:         ////////////////////////////////////////////////////////////////////////////
  438:  
  439:         /// <summary>
  440:         ///
  441:         /// </summary>
  442:         public bool FtpCreateDirectory(string dirpath)
  443:         {
  444:             string URI = this.Hostname + AdjustDir(dirpath);
  445:             System.Net.FtpWebRequest ftp = GetRequest(URI);
  446:  
  447:             ftp.Method = System.Net.WebRequestMethods.Ftp.MakeDirectory;
  448:  
  449:             ftp.UsePassive = usePassive;
  450:  
  451:             try
  452:             {
  453:                 string str = GetStringResponse(ftp);
  454:             }
  455:             catch (Exception)
  456:             {
  457:                 return false;
  458:             }
  459:  
  460:             return true;
  461:         }
  462:  
  463:         ////////////////////////////////////////////////////////////////////////////
  464:  
  465:         /// <summary>
  466:         ///
  467:         /// </summary>
  468:         public bool FtpDeleteDirectory(string dirpath)
  469:         {
  470:             string URI = this.Hostname + AdjustDir(dirpath);
  471:             System.Net.FtpWebRequest ftp = GetRequest(URI);
  472:  
  473:             ftp.Method = System.Net.WebRequestMethods.Ftp.RemoveDirectory;
  474:  
  475:             ftp.UsePassive = usePassive;
  476:  
  477:             try
  478:             {
  479:                 string str = GetStringResponse(ftp);
  480:             }
  481:             catch (Exception)
  482:             {
  483:                 return false;
  484:             }
  485:  
  486:             return true;
  487:         }
  488:  
  489:         ////////////////////////////////////////////////////////////////////////////
  490:  
  491:         /// <summary>
  492:         ///
  493:         /// </summary>
  494:         private FtpWebRequest GetRequest(string URI)
  495:         {
  496:             FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
  497:  
  498:             result.Credentials = GetCredentials();
  499:  
  500:             result.KeepAlive = false;
  501:  
  502:             return result;
  503:         }
  504:  
  505:         ////////////////////////////////////////////////////////////////////////////
  506:  
  507:         /// <summary>
  508:         ///
  509:         /// </summary>
  510:         private System.Net.ICredentials GetCredentials()
  511:         {
  512:             return new System.Net.NetworkCredential(Username, Password);
  513:         }
  514:  
  515:         ////////////////////////////////////////////////////////////////////////////
  516:  
  517:         /// <summary>
  518:         ///
  519:         /// </summary>
  520:         private string GetFullPath(string file)
  521:         {
  522:             if (file.Contains("/"))
  523:             {
  524:                 return AdjustDir(file);
  525:             }
  526:             else
  527:             {
  528:                 return this.CurrentDirectory + file;
  529:             }
  530:         }
  531:  
  532:         ////////////////////////////////////////////////////////////////////////////
  533:  
  534:         /// <summary>
  535:         ///
  536:         /// </summary>
  537:         private string AdjustDir(string path)
  538:         {
  539:             return ((path.StartsWith("/")) ? "" : "/").ToString() + path;
  540:         }
  541:  
  542:         ////////////////////////////////////////////////////////////////////////////
  543:  
  544:         /// <summary>
  545:         ///
  546:         /// </summary>
  547:         private string GetDirectory(string directory)
  548:         {
  549:             string URI;
  550:  
  551:             if (directory == "")
  552:             {
  553:                 //build from current
  554:                 URI = Hostname + this.CurrentDirectory;
  555:                 lastDirectory = this.CurrentDirectory;
  556:             }
  557:             else
  558:             {
  559:                 if (!directory.StartsWith("/"))
  560:                 {
  561:                     throw (new ApplicationException("Directory should start with /"));
  562:                 }
  563:  
  564:                 URI = this.Hostname + directory;
  565:  
  566:                 lastDirectory = directory;
  567:             }
  568:             return URI;
  569:         }
  570:  
  571:         ////////////////////////////////////////////////////////////////////////////
  572:  
  573:         /// <summary>
  574:         ///
  575:         /// </summary>
  576:         private string GetStringResponse(FtpWebRequest ftp)
  577:         {
  578:             //Get the result, streaming to a string
  579:             string result = "";
  580:  
  581:             using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
  582:             {
  583:                 long size = response.ContentLength;
  584:  
  585:                 using (Stream datastream = response.GetResponseStream())
  586:                 {
  587:                     using (StreamReader sr = new StreamReader(datastream))
  588:                     {
  589:                         result = sr.ReadToEnd();
  590:                         //sr.Close();
  591:                     }
  592:  
  593:                     //datastream.Close();
  594:                 }
  595:  
  596:                 //response.Close();
  597:             }
  598:  
  599:             return result;
  600:         }
  601:  
  602:         ////////////////////////////////////////////////////////////////////////////
  603:  
  604:         /// <summary>
  605:         ///
  606:         /// </summary>
  607:         private long GetSize(FtpWebRequest ftp)
  608:         {
  609:             long size;
  610:  
  611:             using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
  612:             {
  613:                 size = response.ContentLength;
  614:  
  615:                 //response.Close();
  616:             }
  617:  
  618:             return size;
  619:         }
  620:  
  621:         ////////////////////////////////////////////////////////////////////////////
  622:  
  623:         /// <summary>
  624:         ///
  625:         /// </summary>
  626:         public string Hostname
  627:         {
  628:             get
  629:             {
  630:                 if (hostName.StartsWith("ftp://"))
  631:                 {
  632:                     return hostName;
  633:                 }
  634:                 else
  635:                 {
  636:                     return "ftp://" + hostName;
  637:                 }
  638:             }
  639:             set
  640:             {
  641:                 hostName = value;
  642:             }
  643:         }
  644:  
  645:         ////////////////////////////////////////////////////////////////////////////
  646:  
  647:         /// <summary>
  648:         ///
  649:         /// </summary>
  650:         public string Username
  651:         {
  652:             get
  653:             {
  654:                 return (userName == "" ? "anonymous" : userName);
  655:             }
  656:             set
  657:             {
  658:                 userName = value;
  659:             }
  660:         }
  661:  
  662:         ////////////////////////////////////////////////////////////////////////////
  663:  
  664:         /// <summary>
  665:         ///
  666:         /// </summary>
  667:         public string Password
  668:         {
  669:             get
  670:             {
  671:                 return password;
  672:             }
  673:             set
  674:             {
  675:                 password = value;
  676:             }
  677:         }
  678:  
  679:         ////////////////////////////////////////////////////////////////////////////
  680:  
  681:         /// <summary>
  682:         ///
  683:         /// </summary>
  684:         public string CurrentDirectory
  685:         {
  686:             get
  687:             {
  688:                 //return directory, ensure it ends with /
  689:                 return currentDirectory + ((currentDirectory.EndsWith("/")) ? "" : "/").ToString();
  690:             }
  691:             set
  692:             {
  693:                 if (!value.StartsWith("/"))
  694:                 {
  695:                     throw (new ApplicationException("Directory should start with /"));
  696:                 }
  697:  
  698:                 currentDirectory = value;
  699:             }
  700:         }
  701:     }
  702:  
  703:     ////////////////////////////////////////////////////////////////////////////
  704:     ////////////////////////////////////////////////////////////////////////////
  705:  
  706:     /// <summary>
  707:     ///
  708:     /// </summary>
  709:     public class FtpFileInfo
  710:     {
  711:         private string _filename;
  712:         private string _path;
  713:         private DirectoryEntryTypes _fileType;
  714:         private long _size;
  715:         private DateTime _fileDateTime;
  716:         private string _permission;
  717:  
  718:         private static string[] _ParseFormats = new string[] {
  719:             "(?<dir>[\\-d])(?<permission>([\\-r][\\-w][\\-xs]){3})\\s+\\d+\\s+\\w+\\s+\\w+\\s+(?<size>\\d+)\\s+(?<timestamp>\\w+\\s+\\d+\\s+\\d{4})\\s+(?<name>.+)",
  720:             "(?<dir>[\\-d])(?<permission>([\\-r][\\-w][\\-xs]){3})\\s+\\d+\\s+\\d+\\s+(?<size>\\d+)\\s+(?<timestamp>\\w+\\s+\\d+\\s+\\d{4})\\s+(?<name>.+)",
  721:             "(?<dir>[\\-d])(?<permission>([\\-r][\\-w][\\-xs]){3})\\s+\\d+\\s+\\d+\\s+(?<size>\\d+)\\s+(?<timestamp>\\w+\\s+\\d+\\s+\\d{1,2}:\\d{2})\\s+(?<name>.+)",
  722:             "(?<dir>[\\-d])(?<permission>([\\-r][\\-w][\\-xs]){3})\\s+\\d+\\s+\\w+\\s+\\w+\\s+(?<size>\\d+)\\s+(?<timestamp>\\w+\\s+\\d+\\s+\\d{1,2}:\\d{2})\\s+(?<name>.+)",
  723:             "(?<dir>[\\-d])(?<permission>([\\-r][\\-w][\\-xs]){3})(\\s+)(?<size>(\\d+))(\\s+)(?<ctbit>(\\w+\\s\\w+))(\\s+)(?<size2>(\\d+))\\s+(?<timestamp>\\w+\\s+\\d+\\s+\\d{2}:\\d{2})\\s+(?<name>.+)",
  724:             "(?<timestamp>\\d{2}\\-\\d{2}\\-\\d{2}\\s+\\d{2}:\\d{2}[Aa|Pp][mM])\\s+(?<dir>\\<\\w+\\>){0,1}(?<size>\\d+){0,1}\\s+(?<name>.+)" };
  725:  
  726:         /// <summary/>
  727:         public string FullName
  728:         {
  729:             get
  730:             {
  731:                 return Path + Filename;
  732:             }
  733:         }
  734:  
  735:         /// <summary/>
  736:         public string Filename
  737:         {
  738:             get
  739:             {
  740:                 return _filename;
  741:             }
  742:         }
  743:  
  744:         /// <summary/>
  745:         public string Path
  746:         {
  747:             get
  748:             {
  749:                 return _path;
  750:             }
  751:         }
  752:  
  753:         /// <summary/>
  754:         public DirectoryEntryTypes FileType
  755:         {
  756:             get
  757:             {
  758:                 return _fileType;
  759:             }
  760:         }
  761:  
  762:         /// <summary/>
  763:         public long Size
  764:         {
  765:             get
  766:             {
  767:                 return _size;
  768:             }
  769:         }
  770:  
  771:         /// <summary/>
  772:         public DateTime FileDateTime
  773:         {
  774:             get
  775:             {
  776:                 return _fileDateTime;
  777:             }
  778:         }
  779:  
  780:         /// <summary/>
  781:         public string Permission
  782:         {
  783:             get
  784:             {
  785:                 return _permission;
  786:             }
  787:         }
  788:  
  789:         /// <summary/>
  790:         public string Extension
  791:         {
  792:             get
  793:             {
  794:                 int i = this.Filename.LastIndexOf(".");
  795:                 if (i >= 0 && i < (this.Filename.Length - 1))
  796:                 {
  797:                     return this.Filename.Substring(i + 1);
  798:                 }
  799:                 else
  800:                 {
  801:                     return "";
  802:                 }
  803:             }
  804:         }
  805:  
  806:         /// <summary/>
  807:         public string NameOnly
  808:         {
  809:             get
  810:             {
  811:                 int i = this.Filename.LastIndexOf(".");
  812:                 if (i > 0)
  813:                 {
  814:                     return this.Filename.Substring(0, i);
  815:                 }
  816:                 else
  817:                 {
  818:                     return this.Filename;
  819:                 }
  820:             }
  821:         }
  822:  
  823:         /// <summary/>
  824:         public enum DirectoryEntryTypes
  825:         {
  826:             /// <summary/>
  827:             File,
  828:  
  829:             /// <summary/>
  830:             Directory
  831:         }
  832:  
  833:         ////////////////////////////////////////////////////////////////////////////
  834:  
  835:         /// <summary>
  836:         ///
  837:         /// </summary>
  838:         public FtpFileInfo(string line, string path)
  839:         {
  840:             //parse line
  841:             Match m = GetMatchingRegex(line);
  842:  
  843:             if (m == null)
  844:             {
  845:                 //failed
  846:                 throw (new ApplicationException("Unable to parse line: " + line));
  847:             }
  848:             else
  849:             {
  850:                 _filename = m.Groups["name"].Value;
  851:                 _path = path;
  852:  
  853:                 Int64.TryParse(m.Groups["size"].Value, out _size);
  854:                 //_size = System.Convert.ToInt32(m.Groups["size"].Value);
  855:  
  856:                 _permission = m.Groups["permission"].Value;
  857:                 string _dir = m.Groups["dir"].Value;
  858:                 if (_dir != "" && _dir != "-")
  859:                 {
  860:                     _fileType = DirectoryEntryTypes.Directory;
  861:                 }
  862:                 else
  863:                 {
  864:                     _fileType = DirectoryEntryTypes.File;
  865:                 }
  866:  
  867:                 try
  868:                 {
  869:                     _fileDateTime = DateTime.Parse(m.Groups["timestamp"].Value);
  870:                 }
  871:                 catch (Exception)
  872:                 {
  873:                     _fileDateTime = Convert.ToDateTime(null);
  874:                 }
  875:             }
  876:         }
  877:  
  878:         ////////////////////////////////////////////////////////////////////////////
  879:  
  880:         /// <summary>
  881:         ///
  882:         /// </summary>
  883:         private Match GetMatchingRegex(string line)
  884:         {
  885:             Regex rx;
  886:             Match m;
  887:  
  888:             for (int i = 0; i <= _ParseFormats.Length - 1; i++)
  889:             {
  890:                 rx = new Regex(_ParseFormats[i]);
  891:                 m = rx.Match(line);
  892:                 if (m.Success)
  893:                 {
  894:                     return m;
  895:                 }
  896:             }
  897:  
  898:             return null;
  899:         }
  900:     }
  901:  
  902:     ////////////////////////////////////////////////////////////////////////////
  903:     ////////////////////////////////////////////////////////////////////////////
  904:  
  905:     /// <summary>
  906:     ///
  907:     /// </summary>
  908:     public class FtpDirectory : List<FtpFileInfo>
  909:     {
  910:         private const char slash = '/';
  911:  
  912:         ////////////////////////////////////////////////////////////////////////////
  913:  
  914:         /// <summary>
  915:         ///
  916:         /// </summary>
  917:         public FtpDirectory()
  918:         {
  919:         }
  920:  
  921:         ////////////////////////////////////////////////////////////////////////////
  922:  
  923:         /// <summary>
  924:         ///
  925:         /// </summary>
  926:         public FtpDirectory(string dir, string path)
  927:         {
  928:             foreach (string line in dir.Replace("\n", "").Split(System.Convert.ToChar('\r')))
  929:             {
  930:                 //parse
  931:                 if (line != "")
  932:                 {
  933:                     this.Add(new FtpFileInfo(line, path));
  934:                 }
  935:             }
  936:         }
  937:  
  938:         ////////////////////////////////////////////////////////////////////////////
  939:  
  940:         /// <summary>
  941:         ///
  942:         /// </summary>
  943:         public FtpDirectory GetFiles(string ext)
  944:         {
  945:             return this.GetFileOrDir(FtpFileInfo.DirectoryEntryTypes.File, ext);
  946:         }
  947:  
  948:         ////////////////////////////////////////////////////////////////////////////
  949:  
  950:         /// <summary>
  951:         ///
  952:         /// </summary>
  953:         public FtpDirectory GetDirectories()
  954:         {
  955:             return this.GetFileOrDir(FtpFileInfo.DirectoryEntryTypes.Directory, "");
  956:         }
  957:  
  958:         ////////////////////////////////////////////////////////////////////////////
  959:  
  960:         /// <summary>
  961:         ///
  962:         /// </summary>
  963:         private FtpDirectory GetFileOrDir(FtpFileInfo.DirectoryEntryTypes type, string ext)
  964:         {
  965:             FtpDirectory result = new FtpDirectory();
  966:  
  967:             foreach (FtpFileInfo fi in this)
  968:             {
  969:                 if (fi.FileType == type)
  970:                 {
  971:                     if (ext == "")
  972:                     {
  973:                         result.Add(fi);
  974:                     }
  975:                     else if (ext == fi.Extension)
  976:                     {
  977:                         result.Add(fi);
  978:                     }
  979:                 }
  980:             }
  981:  
  982:             return result;
  983:         }
  984:  
  985:         ////////////////////////////////////////////////////////////////////////////
  986:  
  987:         /// <summary>
  988:         ///
  989:         /// </summary>
  990:         public bool FileExists(string filename)
  991:         {
  992:             foreach (FtpFileInfo ftpfile in this)
  993:             {
  994:                 if (ftpfile.Filename == filename)
  995:                 {
  996:                     return true;
  997:                 }
  998:             }
  999:  
 1000:             return false;
 1001:         }
 1002:  
 1003:         ////////////////////////////////////////////////////////////////////////////
 1004:  
 1005:         /// <summary>
 1006:         ///
 1007:         /// </summary>
 1008:         public static string GetParentDirectory(string dir)
 1009:         {
 1010:             string tmp = dir.TrimEnd(slash);
 1011:  
 1012:             int i = tmp.LastIndexOf(slash);
 1013:  
 1014:             if (i > 0)
 1015:             {
 1016:                 return tmp.Substring(0, i - 1);
 1017:             }
 1018:             else
 1019:             {
 1020:                 throw (new ApplicationException("No parent for root"));
 1021:             }
 1022:         }
 1023:  
 1024:         ////////////////////////////////////////////////////////////////////////////
 1025:         ////////////////////////////////////////////////////////////////////////////
 1026:     }
 1027:  
 1028:     ////////////////////////////////////////////////////////////////////////////
 1029:     ////////////////////////////////////////////////////////////////////////////
 1030: }
 1031: