IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Web & réseau Delphi Discussion :

Récupérer un ou des fichiers sur serveur FTP en filtrant par type d'extension


Sujet :

Web & réseau Delphi

  1. #1
    Membre du Club
    Homme Profil pro
    Inscrit en
    Octobre 2006
    Messages
    74
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Tarn et Garonne (Midi Pyrénées)

    Informations professionnelles :
    Secteur : Services à domicile

    Informations forums :
    Inscription : Octobre 2006
    Messages : 74
    Points : 50
    Points
    50
    Par défaut Récupérer un ou des fichiers sur serveur FTP en filtrant par type d'extension
    Bonjour

    J'utilise le composant Indy et une TListView (voir image ci-après) pour lister tous les fichiers sur un serveur FTP.

    Je voudrais savoir comment :

    - trier les fichiers par leurs types d'extensions au lieu de les avoir alphabétiquement ?
    - telecharger uniquement les fichiers d'un ou plusieurs type d'extensions (exemple - tous les fichiers zip ou jpg) ? (directement sur le serveur ou dans le TlistView)

    Merci d'avance pour votre aide

    A vous lire
    Cordialement
    Beauserge

    Nom : image TlistView Ftp.jpg
Affichages : 1573
Taille : 95,8 Ko

  2. #2
    Membre expérimenté
    Avatar de retwas
    Homme Profil pro
    Développeur Java/Delphi
    Inscrit en
    Mars 2010
    Messages
    698
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Côte d'Or (Bourgogne)

    Informations professionnelles :
    Activité : Développeur Java/Delphi
    Secteur : Finance

    Informations forums :
    Inscription : Mars 2010
    Messages : 698
    Points : 1 608
    Points
    1 608
    Billets dans le blog
    4
    Par défaut
    Tu peux utiliser une TList et la méthode Sort.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    procedure TForm2.Button1Click(Sender: TObject);
    var
       Liste  : TList<string>;
       i      : integer;
    begin
       Liste := TList<string>.Create;
     
       try
          Liste.Add('a.b');
          Liste.Add('a.c');
          Liste.Add('b.e');
          Liste.Add('d.r');
          Liste.Add('a.k');
          Liste.Add('z.a');
     
          Liste.Sort(TComparer<string>.Construct(function(const Left, Right: string): integer
                                                 var
                                                    ExtLeft, ExtRight: string;
                                                 begin
                                                    ExtLeft  := ExtractFileExt(Left);
                                                    ExtRight := ExtractFileExt(Right);
     
                                                    if ExtLeft = ExtRight then
                                                    begin
                                                       if Left < Right then
                                                          Result := -1
                                                       else
                                                          if Left > Right then
                                                             Result := 1
                                                          else
                                                             Result := 0;
                                                    end
                                                    else
                                                       if ExtLeft < ExtRight then
                                                          Result := -1
                                                       else
                                                          if ExtLeft > ExtRight then
                                                             Result := 1
                                                          else
                                                             Result := 0;
                                                 end));
     
          for i := 0 to Liste.Count - 1 do
             Memo1.Lines.Add(Liste[i]);
       finally
          Liste.Free;
       end;
    end;
    Pour télécharger que les fichiers d'une extension, tu parcours la liste et si l'extension correspond tu télécharges.

    Tu peux aussi prendre les listes de Spring4D ou les FluentQuery de Malcolm Groves pour pouvoir "requêter" dans ta liste.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
       for MonFichier in ObjectQuery<string>
                           .Select
                           .From(Liste)
                           .Where(function(aNom: string) : boolean
                                  begin
                                     Result := ExtractFileExt(aNom) = '.zip'
                                  end) do
       begin
          // téléchargement que des fichiers zip
          // ...
       end;

  3. #3
    Membre du Club
    Homme Profil pro
    Inscrit en
    Octobre 2006
    Messages
    74
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Tarn et Garonne (Midi Pyrénées)

    Informations professionnelles :
    Secteur : Services à domicile

    Informations forums :
    Inscription : Octobre 2006
    Messages : 74
    Points : 50
    Points
    50
    Par défaut
    Bonjour Retwas

    dans le code pour trier la listview, ça ne passe pas.
    erreur ; attendu mais < trouvé ???

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    var
       Liste  : TList<string>;
    A te lire
    Beauserge

  4. #4
    Expert éminent
    Avatar de Lung
    Profil pro
    Analyste-programmeur
    Inscrit en
    Mai 2002
    Messages
    2 664
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Analyste-programmeur
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2002
    Messages : 2 664
    Points : 6 967
    Points
    6 967
    Par défaut
    Citation Envoyé par Beauserge Voir le message
    dans le code pour trier la listview, ça ne passe pas.
    erreur ; attendu mais < trouvé ???
    Quelle est ta version de delphi ?
    L'urgent est fait, l'impossible est en cours, pour les miracles prévoir un délai. ___ Écrivez dans un français correct !!

    C++Builder 5 - Delphi 6#2 Entreprise - Delphi 2007 Entreprise - Delphi 2010 Architecte - Delphi XE Entreprise - Delphi XE7 Entreprise - Delphi 10 Entreprise - Delphi 10.3.2 Entreprise - Delphi 10.4.2 Entreprise - Delphi 11.1 Entreprise
    OpenGL 2.1 - Oracle 10g - Paradox - Interbase (XE) - PostgreSQL (15.4)

  5. #5
    Membre du Club
    Homme Profil pro
    Inscrit en
    Octobre 2006
    Messages
    74
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Tarn et Garonne (Midi Pyrénées)

    Informations professionnelles :
    Secteur : Services à domicile

    Informations forums :
    Inscription : Octobre 2006
    Messages : 74
    Points : 50
    Points
    50
    Par défaut
    Je possède la Version DELPHI 7 perso

  6. #6
    Membre expérimenté
    Avatar de retwas
    Homme Profil pro
    Développeur Java/Delphi
    Inscrit en
    Mars 2010
    Messages
    698
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Côte d'Or (Bourgogne)

    Informations professionnelles :
    Activité : Développeur Java/Delphi
    Secteur : Finance

    Informations forums :
    Inscription : Mars 2010
    Messages : 698
    Points : 1 608
    Points
    1 608
    Billets dans le blog
    4
    Par défaut
    Citation Envoyé par Beauserge Voir le message
    Je possède la Version DELPHI 7 perso
    Dans ce cas tu n'as pas les listes de générique ..

  7. #7
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 457
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 457
    Points : 24 870
    Points
    24 870
    Par défaut
    La fonction TIdFTP.List contient un paramètre ASpecifier qui gère le filtre
    Tu as un vieux Delphi, donc possible un vieux Indy, à vérifier

    J'utilise massivement cette fonctionnalité du List que j'ai inclus sous le nom de FileFilter dans ma classe

    Exemple d'utilisation


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
      with TSLTFTP.Create() do
      try
        ConnectionInfo.Host := 'ftp.server.com';
        ConnectionInfo.User := 'MonUtilisateur';
        ConnectionInfo.Password := 'MonPassword';
        ConnectionInfo.Directory := '/Dossier';
        FileFilter := '*.jpg';
     
        if Connect() then
        begin
          for I := 0 to FileCount - 1 do
          begin
            if FileSizes[I] > 0 then
            begin
              if Get(Files[I], Stream) then
              begin
                Stream.Seek(0, soBeginning);
                ...
              end
            end;
          end;
        end;
      finally
        Free();
      end;
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    //------------------------------------------------------------------------------
    (*                SoLuTions is an Versatile Library for Delphi                 -
     *                                                                             -
     *  Copyright ou © ou Copr. "SLT Solutions", (2006)                            -
     *  contributeur : ShaiLeTroll (2006) - Migration TNMFTP vers TIdFTP lors du passge de Delphi 5 à Delphi 7
     *  contributeur : ShaiLeTroll (2006) - Séparation FTP et SFTP, pour supprimer la dépendance à SecureBlackBox et ne conserver que IdFTP fourni avec Delphi 7
     *  contributeur : ShaiLeTroll (2012) - Renommage Fichier et Correction XE2    -
     *  contributeur : ShaiLeTroll (2012) - Documentation Insight                  -
     *                                                                             -
     *                                                                             -
     * Ce logiciel est un programme informatique servant à aider les développeurs  -
     * Delphi avec une bibliothèque polyvalente, adaptable et fragmentable.        -
     *                                                                             -
     * Ce logiciel est régi par la licence CeCILL-C soumise au droit français et   -
     * respectant les principes de diffusion des logiciels libres. Vous pouvez     -
     * utiliser, modifier et/ou redistribuer ce programme sous les conditions      -
     * de la licence CeCILL-C telle que diffusée par le CEA, le CNRS et l'INRIA    -
     * sur le site "http://www.cecill.info".                                       -
     *                                                                             -
     * En contrepartie de l'accessibilité au code source et des droits de copie,   -
     * de modification et de redistribution accordés par cette licence, il n'est   -
     * offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,   -
     * seule une responsabilité restreinte pèse sur l'auteur du programme,  le     -
     * titulaire des droits patrimoniaux et les concédants successifs.             -
     *                                                                             -
     * A cet égard  l'attention de l'utilisateur est attirée sur les risques       -
     * associés au chargement,  à l'utilisation,  à la modification et/ou au       -
     * développement et à la reproduction du logiciel par l'utilisateur étant      -
     * donné sa spécificité de logiciel libre, qui peut le rendre complexe à       -
     * manipuler et qui le réserve donc à des développeurs et des professionnels   -
     * avertis possédant  des  connaissances  informatiques approfondies.  Les     -
     * utilisateurs sont donc invités à charger  et  tester  l'adéquation  du      -
     * logiciel à leurs besoins dans des conditions permettant d'assurer la        -
     * sécurité de leurs systèmes et ou de leurs données et, plus généralement,    -
     * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.          -
     *                                                                             -
     * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez      -
     * pris connaissance de la licence CeCILL-C, et que vous en avez accepté les   -
     * termes.                                                                     -
     *                                                                             -
     *----------------------------------------------------------------------------*)
    unit SLT.Common.FTP;
     
    interface
     
    {*$DEFINE DEBUG_SLT_FTP*}
     
    uses System.Classes, System.SysUtils,
      IdFTP, IdReplyRFC;
     
    type
      { Forward class declarations }
      TSLTFTP = class;
      TSLTFTPConnectionInfo = class;
     
      { class declarations }
     
      /// <summary>Encapsule une connection FTP avec un emplacement de travail prédéfini</summary>
      TSLTFTP = class(TObject)
      private
        // Membres privés
        FConnection: TIdFTP;
        FConnectionInfo: TSLTFTPConnectionInfo;
        FFiles: TStrings;
        FFileFilter: string;
     
        function InitializeFiles(): Boolean;
        function ChangeDirectory(const ADirectory: string): Boolean; overload;
        function ChangeDirectory(const ADirectory: string; out AOldDirectory: string): Boolean; overload;
     
        {$IFDEF DEBUG_SLT_FTP}
        procedure OutputDebugFTP(const Msg: string); inline;
        {$ENDIF DEBUG_SLT_FTP}
     
      protected
        // Accesseurs
        procedure SetConnectionInfo(Value: TSLTFTPConnectionInfo);
        function GetFileCount(): Integer;
        function GetFile(Index: Integer): TFileName;
        function GetFileSize(Index: Integer): Int64;
        function GetFileDate(Index: Integer): TDateTime;
        procedure SetFileFilter(const Value: string);
      public
        // Constructeurs
        constructor Create();
        destructor Destroy(); override;
     
        // Méthodes
        function Connect(): Boolean;
        function Disconnect(): Boolean;
     
        function Get(const ASourceFile: string; ADest: TStream; const ASourceDirectory: string = ''): Boolean;
        function Put(const ASource: TStream; const ADestFile: string; const ADestDirectory: string = ''): Boolean;
        function RenameFile(const ASourceFile: string; const ADestFile: string): Boolean;
        function MoveFile(const ASourceFile: string; const ADestFile: string; const ASourceDirectory: string = ''; const ADestDirectory: string = ''): Boolean;
        function MoveFileTo(const AFile: string; const ADestDirectory: string; AReplaceExisting: Boolean = False): Boolean;
        function DeleteFile(const AFile: string; const ADirectory: string = ''): Boolean;
        function CreateDirectory(const ADirectory: string): Boolean;
        function ExistsDirectory(const ADirectory: string): Boolean;
     
        // Propriétés
        property ConnectionInfo: TSLTFTPConnectionInfo read FConnectionInfo write SetConnectionInfo;
        property FileCount: Integer read GetFileCount;
        property Files[Index: Integer]: TFileName read GetFile;
        property FileSizes[Index: Integer]: Int64 read GetFileSize;
        property FileDates[Index: Integer]: TDateTime read GetFileDate;
        property FileFilter: string read FFileFilter write SetFileFilter;
      end;
     
      /// <summary>Décrit un emplacement FTP</summary>
      TSLTFTPConnectionInfo = class(TPersistent)
      public
        const
          DEFAULT_PORT_FTP = 21;
          DEFAULT_PASSIVE_FTP = IdFTP.Id_TIdFTP_Passive;
      private
        // Membres privés
        FHost: string;
        FPort: Word;
        FDirectory: TFileName;
        FUser: string;
        FPassword: string;
        FPassive: Boolean;
      public
        // Constructeurs
        constructor Create();
     
        // Méthodes - Redéfinition de TPersistent
        procedure Assign(Source: TPersistent); override;
        // Méthodes - Redéfinition de TObject
        function ToString(): string; override;
     
        // Propriétés
        property Host: string read FHost write FHost;
        property Port: Word read FPort write FPort default DEFAULT_PORT_FTP;
        property Directory: TFileName read FDirectory write FDirectory;
        property User: string read FUser write FUser;
        property Password: string read FPassword write FPassword;
        property Passive: Boolean read FPassive write FPassive;
      end;
     
    implementation
     
    {$IFDEF DEBUG_SLT_FTP}
    uses
      SLT.Common.Tracing;
    {$ENDIF DEBUG_SLT_FTP}
     
    { TSLTFTP }
     
    //------------------------------------------------------------------------------
    function TSLTFTP.ChangeDirectory(const ADirectory: string): Boolean;
    begin
      FConnection.ChangeDir(ADirectory);
      Result := SameText(FConnection.RetrieveCurrentDir, ADirectory);
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.ChangeDirectory(const ADirectory: string; out AOldDirectory: string): Boolean;
    var
      OldD: string;
    begin
      OldD := FConnection.RetrieveCurrentDir;
      Result := ChangeDirectory(ADirectory);
      if Result then
        AOldDirectory := OldD;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.Connect(): Boolean;
    begin
      Result := False;
     
      Disconnect();
     
      FConnection.Host := FConnectionInfo.Host;
      FConnection.Port := FConnectionInfo.Port;
      FConnection.Username := FConnectionInfo.User;
      FConnection.Password := FConnectionInfo.Password;
      FConnection.Passive := FConnectionInfo.Passive;
     
      try
        FConnection.Connect();
        if FConnection.Connected then
        begin
          if FConnectionInfo.Directory <> '' then
            Result := ChangeDirectory(FConnectionInfo.Directory)
          else
            Result := True;
        end
        else
          Abort;
      except
        on E: Exception do
        begin
          {$IFDEF DEBUG_SLT_FTP}OutputDebugFTP('Connect : ' + E.Message);{$ENDIF DEBUG_SLT_FTP}
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    constructor TSLTFTP.Create();
    begin
      inherited Create();
     
      FConnection := TIdFTP.Create(nil);
      FConnectionInfo := TSLTFTPConnectionInfo.Create();
      FFileFilter := '.';
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.CreateDirectory(const ADirectory: string): Boolean;
    begin
      if FConnection.Connected then
      begin
        try
          // Si le dossier existe déjà, il ne faut pas le créer sinon exception
          if not ExistsDirectory(ADirectory) then
            FConnection.MakeDir(ADirectory);
     
          Result := True;
        except
          on E: Exception do
          begin
            {$IFDEF DEBUG_SLT_FTP}OutputDebugFTP('CreateDirectory : ' + E.Message);{$ENDIF DEBUG_SLT_FTP}
            Result := False;
          end;
        end;
      end
      else
        Result := False;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.DeleteFile(const AFile: string; const ADirectory: string = ''): Boolean;
    var
      lDel: string;
    begin
      if FConnection.Connected then
      begin
        try
          if ADirectory <> '' then
            lDel := ADirectory + '/' + AFile
          else
            lDel := AFile;
     
          if FConnection.Size(lDel) >= 0 then
            FConnection.Delete(lDel);
     
          Result := True;
        except
          on E: Exception do
          begin
            {$IFDEF DEBUG_SLT_FTP}OutputDebugFTP('DeleteFile : ' + E.Message);{$ENDIF DEBUG_SLT_FTP}
            Result := False;
          end;
        end;
      end
      else
        Result := False;
    end;
     
    //------------------------------------------------------------------------------
    destructor TSLTFTP.Destroy();
    begin
      Disconnect();
     
      FreeAndNil(FConnectionInfo);
      FreeAndNil(FConnection);
     
      inherited Destroy();
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.Disconnect(): Boolean;
    begin
      FreeAndNil(FFiles);
     
      try
        if FConnection.Connected then
        begin
          FConnection.Disconnect();
          Result := not FConnection.Connected;
        end
        else
          Result := True;
      except
        on E: Exception do
        begin
          {$IFDEF DEBUG_SLT_FTP}OutputDebugFTP('Disconnect : ' + E.Message);{$ENDIF DEBUG_SLT_FTP}
          Result := False;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.ExistsDirectory(const ADirectory: string): Boolean;
    const
      ERROR_FILE_UNAVAILABLE = 550;
    var
      OldDirectory: string;
    begin
      Result := False;
     
      // Même technique que FileZilla, changement de répertoire pour en tester l'existence
      if FConnection.Connected then
      begin
        try
          OldDirectory := FConnection.RetrieveCurrentDir;
          try
            try
              Result := ChangeDirectory(ADirectory);
            except
              on E: EIdReplyRFCError do
                if E.ErrorCode <> ERROR_FILE_UNAVAILABLE then
                  raise;
            end;
          finally
            if not ChangeDirectory(OldDirectory) then
              Abort;
          end;
        except
          on E: Exception do
          begin
            {$IFDEF DEBUG_SLT_FTP}OutputDebugFTP('ExistsDirectory : ' + E.Message);{$ENDIF DEBUG_SLT_FTP}
            Result := False;
          end;
        end;
      end
      else
        Result := False;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.Get(const ASourceFile: string; ADest: TStream; const ASourceDirectory: string = ''): Boolean;
    var
      OldDirectory: string;
    begin
      if FConnection.Connected then
      begin
        try
          if ASourceDirectory <> '' then
            if not ChangeDirectory(ASourceDirectory, OldDirectory) then
              Abort;
     
          try
            FConnection.Get(ASourceFile, ADest);
            Result := True;
          finally
            if (ASourceDirectory <> '') and (OldDirectory <> '') then
              if not ChangeDirectory(OldDirectory) then
                Abort;
          end;
        except
          on E: Exception do
          begin
            {$IFDEF DEBUG_SLT_FTP}OutputDebugFTP('Get : ' + E.Message);{$ENDIF DEBUG_SLT_FTP}
            raise;
          end;
        end;
      end
      else
        Result := False;
    end;
     
     
    //------------------------------------------------------------------------------
    function TSLTFTP.GetFile(Index: Integer): TFileName;
    begin
      if InitializeFiles() then
        Result := FFiles.Strings[Index]
      else
        Result := '';
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.GetFileCount(): Integer;
    begin
      if InitializeFiles() then
        Result := FFiles.Count
      else
        Result := 0;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.GetFileDate(Index: Integer): TDateTime;
    begin
      if InitializeFiles() then
        Result := FConnection.FileDate(Files[Index])
      else
        Result := 0;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.GetFileSize(Index: Integer): Int64;
    begin
      if InitializeFiles() then
        Result := FConnection.Size(Files[Index])
      else
        Result := 0;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.InitializeFiles(): Boolean;
    var
      TmpList: TStrings;
    begin
      Result := False;
      if FConnection.Connected then
      begin
        if not Assigned(FFiles) then
        begin
          TmpList := TStringList.Create();
          try
            try
              FConnection.List(TmpList, FFileFilter, False);
              if TmpList.Count > 0 then
              begin
                FFiles := TmpList;
                Exit(True);
              end;
            except
              on E: Exception do
              begin
                {$IFDEF DEBUG_SLT_FTP}OutputDebugFTP('InitializeFiles : ' + E.Message);{$ENDIF DEBUG_SLT_FTP}
                Result := False;
              end;
            end;
          finally
            if not Result then
              TmpList.Free();
          end;
        end;
      end;
     
      Result := Assigned(FFiles) and (FFiles.Count > 0);
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.MoveFile(const ASourceFile: string; const ADestFile: string; const ASourceDirectory: string = ''; const ADestDirectory: string = ''): Boolean;
    var
      lSrc, lDst: string;
    begin
      if FConnection.Connected then
      begin
        try
          if ASourceDirectory <> '' then
            lSrc := ASourceDirectory + '/' + ASourceFile
          else
            lSrc := ASourceFile;
     
          if ADestDirectory <> '' then
            lDst := ADestDirectory + '/' + ADestFile
          else
            lDst := ADestFile;
     
          FConnection.Rename(lSrc, lDst);
          Result := True;
        except
          on E: Exception do
          begin
            {$IFDEF DEBUG_SLT_FTP}OutputDebugFTP('MoveFile : ' + E.Message);{$ENDIF DEBUG_SLT_FTP}
            Result := False;
          end;
        end;
      end
      else
        Result := False;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.MoveFileTo(const AFile: string; const ADestDirectory: string; AReplaceExisting: Boolean = False): Boolean;
    begin
      if AReplaceExisting then
        DeleteFile(AFile, ADestDirectory);
     
      Result := MoveFile(AFile, AFile, '', ADestDirectory);
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.Put(const ASource: TStream; const ADestFile: string; const ADestDirectory: string = ''): Boolean;
    var
      OldDirectory: string;
    begin
      if FConnection.Connected then
      begin
        try
          if ADestDirectory <> '' then
            if not ChangeDirectory(ADestDirectory, OldDirectory) then
              Abort;
     
          try
            FConnection.Put(ASource, ADestFile);
            Result := True;
          finally
            if (ADestDirectory <> '') and (OldDirectory <> '') then
              if not ChangeDirectory(OldDirectory) then
                Abort;
          end;
        except
          on E: Exception do
          begin
            {$IFDEF DEBUG_SLT_FTP}OutputDebugFTP('Put : ' + E.Message);{$ENDIF DEBUG_SLT_FTP}
            Result := False;
          end;
        end;
      end
      else
        Result := False;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTP.RenameFile(const ASourceFile, ADestFile: string): Boolean;
    begin
      if FConnection.Connected then
      begin
        try
          FConnection.Rename(ASourceFile, ADestFile);
          Result := True;
        except
          on E: Exception do
          begin
            {$IFDEF DEBUG_SLT_FTP}OutputDebugFTP('RenameFile : ' + E.Message);{$ENDIF DEBUG_SLT_FTP}
            Result := False;
          end;
        end;
      end
      else
        Result := False;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTFTP.SetConnectionInfo(Value: TSLTFTPConnectionInfo);
    begin
      FConnectionInfo.Assign(Value);
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTFTP.SetFileFilter(const Value: string);
    begin
      if not SameText(FFileFilter, Value) then
      begin
        FFileFilter := Value;
        FreeAndNil(FFiles);
      end;
    end;
     
    //------------------------------------------------------------------------------
    {$IFDEF DEBUG_SLT_FTP}
    procedure TSLTFTP.OutputDebugFTP(const Msg: string);
    begin
      TSLTDebugLogger.OutputDebugString('[SLT.FTP]', Format('%0:s : %1:s', [ConnectionInfo.Host, Msg]));
    end;
    {$ENDIF DEBUG_SLT_FTP}
     
     
    { TSLTFTPConnectionInfo }
     
    //------------------------------------------------------------------------------
    procedure TSLTFTPConnectionInfo.Assign(Source: TPersistent);
    begin
      if Source is TSLTFTPConnectionInfo then
      begin
        with TSLTFTPConnectionInfo(Source) do
        begin
          Self.FHost := FHost;
          Self.FPort := FPort;
          Self.FDirectory := FDirectory;
          Self.FUser := FUser;
          Self.FPassword := FPassword;
        end;
      end
      else
        inherited Assign(Source);
    end;
     
    //------------------------------------------------------------------------------
    constructor TSLTFTPConnectionInfo.Create();
    begin
      inherited Create();
     
      FPort := DEFAULT_PORT_FTP;
      Passive := DEFAULT_PASSIVE_FTP;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTFTPConnectionInfo.ToString(): string;
     
      function ExcludeFirstPathDelimiter(const S: string): string;
      begin
        if IsDelimiter(S, '/', 1) then
          Result := Copy(S, 2, Length(S) - 1)
        else
          Result := S;
      end;
     
    begin
      // Concaténation des informations de connexion sous la forme d'une URL "ftp://user@ftpserver/url-path"
      Result := Format('ftp://%s@%s/%s', [User, Host, ExcludeFirstPathDelimiter(Directory)]);
    end;
     
    end.
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  8. #8
    Membre du Club
    Homme Profil pro
    Inscrit en
    Octobre 2006
    Messages
    74
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Tarn et Garonne (Midi Pyrénées)

    Informations professionnelles :
    Secteur : Services à domicile

    Informations forums :
    Inscription : Octobre 2006
    Messages : 74
    Points : 50
    Points
    50
    Par défaut
    Bonjour ShaiLeTroll

    J'ai à priori la version Indy 10 pour Delphi 7.

    Je te remercie pour ton code mais je ne vois pas comment l'utiliser dans mon programme - (code ci dessous)

    A+
    Beauserge



    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    unit MainForm;
     
    interface
     
    uses
      Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
      ImgList, StdCtrls, ComCtrls, ToolWin, IdBaseComponent, IdComponent,
      IdTCPConnection, IdTCPClient, IdFTP,
      Buttons, ExtCtrls, Commctrl, ActnList, ShellAPI, IniFiles, FTPSiteInfo,
      ConfigureApplicationForm, ConfigureSiteForm, ApplicationConfiguration,
      Menus, IdFTPCommon, Wininet;
     
    type
      TfrmMain = class(TForm)
        FTP: TIdFTP;
        sbMain: TStatusBar;
        ilNormalImages: TImageList;
        ControlBar1: TControlBar;
        ToolBar7: TToolBar;
        btnConnect: TToolButton;
        btnBack: TToolButton;
        btnUpAFolder: TToolButton;
        btnHome: TToolButton;
        ToolBar9: TToolBar;
        Panel5: TPanel;
        cbFTPAddress: TComboBox;
        btnSiteOptions: TToolButton;
        ToolBar10: TToolBar;
        Panel6: TPanel;
        edUserName: TEdit;
        ToolBar11: TToolBar;
        Panel7: TPanel;
        edPassword: TEdit;
        ToolBar12: TToolBar;
        btnNewFolder: TToolButton;
        btnDeleteFolder: TToolButton;
        ToolButton20: TToolButton;
        btnUploadFile: TToolButton;
        btnDownloadFile: TToolButton;
        ToolBar13: TToolBar;
        btnAbout: TToolButton;
        ToolBar14: TToolBar;
        btnViewingStyle: TToolButton;
        Panel8: TPanel;
        edFolder: TEdit;
        btnGo: TBitBtn;
        ActionList1: TActionList;
        actConnectDisconnect: TAction;
        lbStatus: TListBox;
        pbProgress: TProgressBar;
        lbDirectory: TListBox;
        Splitter1: TSplitter;
        Splitter2: TSplitter;
        SaveFile: TSaveDialog;
        lvFiles: TListView;
        actChangeDirUP: TAction;
        actHome: TAction;
        actBack: TAction;
        actCreateFolder: TAction;
        actDeleteFileFolder: TAction;
        ToolButton1: TToolButton;
        actDownloadFile: TAction;
        actUploadFile: TAction;
        actAbout: TAction;
        actHelp: TAction;
        actConfigureSite: TAction;
        actConfigureApplication: TAction;
        OpenDialog: TOpenDialog;
        tvFolders: TTreeView;
        puUpload: TPopupMenu;
        puDownload: TPopupMenu;
        Active1: TMenuItem;
        BinaryNottext1: TMenuItem;
        ASCIIText1: TMenuItem;
        BinaryNottext2: TMenuItem;
        Button1: TButton;
        PageControl1: TPageControl;
        TabSheet1: TTabSheet;
        Button2: TButton;
        Edit1: TEdit;
        Edit2: TEdit;
        Edit4: TEdit;
        Edit5: TEdit;
        Edit6: TEdit;
        Edit7: TEdit;
        Edit8: TEdit;
        Edit9: TEdit;
        Edit10: TEdit;
        Edit3: TEdit;
        ListBox1: TListBox;
        Memo1: TMemo;
        Button3: TButton;
        procedure FTPAfterClientLogin(Sender: TObject);
        procedure FTPDisconnected(Sender: TObject);
        procedure FormShow(Sender: TObject);
        procedure FTPStatus(ASender: TObject; const AStatus: TIdStatus;
          const AStatusText: String);
        procedure actConnectDisconnectExecute(Sender: TObject);
        procedure FormCreate(Sender: TObject);
        procedure btnGoClick(Sender: TObject);
        procedure edFolderKeyPress(Sender: TObject; var Key: Char);
        procedure lbStatusDrawItem(Control: TWinControl; Index: Integer;
          Rect: TRect; State: TOwnerDrawState);
        procedure FTPWorkBegin(Sender: TObject; AWorkMode: TWorkMode;
          const AWorkCountMax: Integer);
        procedure FTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode);
        procedure FTPWork(Sender: TObject; AWorkMode: TWorkMode;
          const AWorkCount: Integer);
        procedure actChangeDirUPExecute(Sender: TObject);
        procedure actDownloadFileExecute(Sender: TObject);
        procedure lbDirectoryDblClick(Sender: TObject);
        procedure actDeleteFileFolderExecute(Sender: TObject);
        procedure actCreateFolderExecute(Sender: TObject);
        procedure actUploadFileExecute(Sender: TObject);
        procedure lbDirectoryKeyPress(Sender: TObject; var Key: Char);
        procedure FormDestroy(Sender: TObject);
        procedure actBackExecute(Sender: TObject);
        procedure actHomeExecute(Sender: TObject);
        procedure actHelpExecute(Sender: TObject);
        procedure actConfigureSiteExecute(Sender: TObject);
        procedure actConfigureApplicationExecute(Sender: TObject);
        procedure cbFTPAddressChange(Sender: TObject);
        procedure BinaryNottext1Click(Sender: TObject);
        procedure Button1Click(Sender: TObject);
        procedure Button2Click(Sender: TObject);
        procedure FormClose(Sender: TObject; var Action: TCloseAction);
     
      private
        { Private declarations }
        FLastDirStack : TStringList;
        FRootDir      : String;
        FHelpFile     : String;
        Sites         : TFTPSiteList;
        ApplicationConfig : TApplicationConfig;
     
        procedure DisplayFTP;
        function GetHelpFile: String;
        procedure LoadDefaultValues;
        procedure StoreDefaultValues;
        procedure InitLogColors;
      public
        { Public declarations }
        procedure Alignementcolonnelistbox; // pour alignement colonne lisbox
        procedure SetControls;
        procedure Log(Msg : String; Color : TColor = clBlack);
        procedure ChangeFTPDir(NewDir : String);
        property HelpFile : String read GetHelpFile;
      end;
     
    var
      frmMain: TfrmMain;
      Ini    : TIniFile;
     
    implementation
     
    {$R *.DFM}
     
    { TfrmMain }
     
    procedure TfrmMain.SetControls;
    begin
      if FTP.Connected then
        begin
          actConnectDisconnect.Caption := 'Disconnect';
          sbMain.Panels[0].Text := 'Online';
        end
      else
        begin
          actConnectDisconnect.Caption := 'Connect';
          sbMain.Panels[0].Text := 'Offline';
        end;
     
      actConnectDisconnect.Hint := actConnectDisconnect.Caption;
     
      actConnectDisconnect.Checked := FTP.Connected;
      btnGo.Enabled                := FTP.Connected;
      actChangeDirUP.Enabled       := FTP.Connected;
      actBack.Enabled              := FTP.Connected and (FLastDirStack.Count > 0);
      actHome.Enabled              := FTP.Connected;
      actCreateFolder.Enabled      := FTP.Connected;
      actDeleteFileFolder.Enabled  := FTP.Connected;
      actUploadFile.Enabled        := FTP.Connected;
      actDownloadFile.Enabled      := FTP.Connected;
      actConfigureSite.Enabled     := (not FTP.Connected) and (cbFTPAddress.Text <> '');
      edFolder.Enabled             := FTP.Connected;
      cbFTPAddress.Enabled         := not FTP.Connected;
      edUserName.Enabled           := not FTP.Connected;
      edPassword.Enabled           := not FTP.Connected;
      actConnectDisconnect.Enabled := (cbFTPAddress.Text <> '');
    end;
     
    procedure TfrmMain.FTPAfterClientLogin(Sender: TObject);
    begin
      SetControls;
      FLastDirStack.Clear;
     
      if cbFTPAddress.ItemIndex > -1 then
        begin
          ChangeFTPDir(Sites[cbFTPAddress.ItemIndex].RootDir);
        end;
     
      DisplayFtp;
      FRootDir := FTP.RetrieveCurrentDir;
    end;
     
    procedure TfrmMain.FTPDisconnected(Sender: TObject);
    begin
      SetControls;
      lvFiles.Items.Clear;
      tvFolders.Items.Clear;
    end;
     
    procedure TfrmMain.FormShow(Sender: TObject);
    var
      r: TRect;
    begin
      sbMain.ControlStyle := sbMain.ControlStyle + [csAcceptsControls];
     
      sbMain.Perform(SB_GETRECT, 1, Integer(@R));
     
      pbProgress.Parent := sbMain;
      pbProgress.Top    := r.Top;
      pbProgress.Left   := r.Left;
      pbProgress.Width  := r.Right - r.Left;
      pbProgress.Height := r.Bottom - r.Top;
      pbProgress.Visible:= false;
    end;
     
    procedure TfrmMain.FTPStatus(ASender: TObject; const AStatus: TIdStatus;
      const AStatusText: String);
    var
      Clr : TColor;
    begin
      sbMain.Panels[2].Text := AStatusText;
      clr := ApplicationConfig.LogColors.Colors['Default'];
      case AStatus of
        hsStatusText    : Clr := ApplicationConfig.LogColors.Colors['hsStatusText'];
        hsResolving     : Clr := ApplicationConfig.LogColors.Colors['hsResolving'];
        hsConnecting    : Clr := ApplicationConfig.LogColors.Colors['hsConnecting'];
        hsDisconnecting : Clr := ApplicationConfig.LogColors.Colors['hsDisconnecting'];
        hsConnected     : Clr := ApplicationConfig.LogColors.Colors['hsConnected'];
        hsDisconnected  : Clr := ApplicationConfig.LogColors.Colors['hsDisconnected'];
        ftpTransfer     : Clr := ApplicationConfig.LogColors.Colors['ftpTransfer'];
        ftpReady        : Clr := ApplicationConfig.LogColors.Colors['ftpReady'];
        ftpAborted      : Clr := ApplicationConfig.LogColors.Colors['ftpAborted'];
      end;
      Log(AStatusText, clr);
    end;
     
    procedure TfrmMain.actConnectDisconnectExecute(Sender: TObject);
    begin
      if FTP.Connected then
        begin
          FTP.Disconnect;
        end
      else
        begin
          lbStatus.Items.Clear;
          if cbFTPAddress.ItemIndex = -1 then
            FTP.Host := cbFTPAddress.Text
          else
            FTP.Host := TFTPSiteInfo(cbFTPAddress.Items.Objects[cbFTPAddress.ItemIndex]).Address;
          FTP.Username := edUserName.Text;
          FTP.Password := edPassword.Text;
     
          FTP.Connect;
          LvFiles.SortType:=StText; // trier la listbox par ordre alphabétique
           end;
    end;
     
    procedure TfrmMain.DisplayFTP;
    var
      i, c : Integer;
      s : String;
    begin
      lbDirectory.Items.Clear;
      FTP.List(lbDirectory.Items, '', false);
     
      edFolder.Text := FTP.RetrieveCurrentDir;
     
      tvFolders.Items.Clear;
      lvFiles.Items.Clear;
     
      for c := 0 to lbDirectory.Items.Count -1 do
        begin
          s := lbDirectory.Items[c];
          i := FTP.Size(s);
          if i = -1 then
            begin
            // Directory
              tvFolders.Items.Add(nil, s);
            end
          else
            begin
            // File
              lvFiles.Items.Add.Caption := s;
            end;
        end;
      SetControls;
    end;
     
    procedure TfrmMain.FormCreate(Sender: TObject);
    begin
      Ini := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
      ApplicationConfig := TApplicationConfig.Create;
     
      Sites := TFTPSiteList.Create;
     
      LoadDefaultValues;
     
      FLastDirStack := TStringList.Create;
      edFolder.Text := '/';
      lbDirectory.Visible := false;
      SetControls;
      actHelp.Enabled := FileExists(HelpFile);
      // cache le pageControl à l'ouverture du programme
      PageControl1.visible:=false;
     
       // restauration des stats à l'ouverture de l'application
      ListBox1.Items.LoadFromFile(ExtractFilePath(Application.ExeName)+'fichierstats.txt');
      Alignementcolonnelistbox; // pour alignement colonne lisbox
    end;
     
    procedure TfrmMain.btnGoClick(Sender: TObject);
    begin
      if btnGo.Enabled then
        begin
          ChangeFTPDir(edFolder.Text);
        end;
    end;
     
    procedure TfrmMain.edFolderKeyPress(Sender: TObject; var Key: Char);
    begin
      if Key=#13 then
        begin
          btnGo.Click;
          Key := #0;
        end;
    end;
     
    procedure TfrmMain.Log(Msg: String; Color: TColor);
    begin
      lbStatus.Items.AddObject(Msg, Pointer(Color));
      lbStatus.ItemIndex := lbStatus.Items.Count -1;
    end;
     
    procedure TfrmMain.lbStatusDrawItem(Control: TWinControl; Index: Integer;
      Rect: TRect; State: TOwnerDrawState);
    begin
    // This draws the items in the Process Log in colors to allow quick
    // visual inspection
      with Control as TListBox do
      begin
        Canvas.Brush.Color := Color;
     
        Canvas.FillRect(Rect); 
        Canvas.Font.Color := TColor(Items.Objects[Index]);
        Canvas.TextOut(Rect.Left + 2, Rect.Top, Items[Index]);
      end;
    end;
     
    procedure TfrmMain.FTPWorkBegin(Sender: TObject; AWorkMode: TWorkMode;
      const AWorkCountMax: Integer);
    begin
      pbProgress.Max := AWorkCountMax;
      pbProgress.Position := 0;
      pbProgress.Visible := true;
      Log('Work begin ' + IntToStr(AWorkCountMax), clPurple);
    end;
     
    procedure TfrmMain.FTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode);
    begin
      pbProgress.Visible := false;
      Log('Work end', clPurple);
    end;
     
    procedure TfrmMain.FTPWork(Sender: TObject; AWorkMode: TWorkMode;
      const AWorkCount: Integer);
    begin
      pbProgress.Position := AWorkCount;
      Log('Work ' + IntToStr(AWorkCount), clPurple);
    end;
     
    procedure TfrmMain.ChangeFTPDir(NewDir: String);
    begin
      FLastDirStack.Add(FTP.RetrieveCurrentDir);
      FTP.ChangeDir(NewDir);
      DisplayFTP;
    end;
     
    procedure TfrmMain.actChangeDirUPExecute(Sender: TObject);
    begin
      FTP.ChangeDirUp;
      DisplayFTP;
    end;
     
    procedure TfrmMain.actDownloadFileExecute(Sender: TObject);
    var
      i : Integer;
      ext,  s : String;
      b : boolean;
    begin
      if lvFiles.Focused then
        begin
          if Assigned(lvFiles.Selected) then
            lbDirectory.ItemIndex := lbDirectory.Items.IndexOf(lvFiles.Selected.Caption)
          else
            lbDirectory.ItemIndex := -1;
        end
      else
          if Assigned(tvFolders.Selected) then
            lbDirectory.ItemIndex := lbDirectory.Items.IndexOf(tvFolders.Selected.Text)
          else
            lbDirectory.ItemIndex := -1;
     
      i := lbDirectory.ItemIndex;
      if i <> -1 then
        begin
          s := lbDirectory.Items[i];
          i := FTP.Size(s);
          if i = -1 then
            begin
            // Directory
              ChangeFTPDir(s);
            end
          else
            begin
              // File
              ext := ExtractFileExt(s);
              SaveFile.Filter := ext + ' files|*' + ext + '|All Files|*.*';
              SaveFile.FileName := s;
              if SaveFile.Execute then
                begin
                  b := true;
                  if FileExists(SaveFile.FileName) then
                    if MessageDlg('File exists overwrite?', mtWarning, [mbYes,mbNo], 0) = mrYes then
                      DeleteFile(SaveFile.FileName);
     
                  if ASCIIText1.Checked then
                    FTP.TransferType := ftASCII
                  else
                    FTP.TransferType := ftBinary;
     
                  if b then
                    FTP.Get(s, SaveFile.FileName, True, FTP.ResumeSupported);
                end;
            end;
        end
      else
        MessageDlg('You must first select a file to download from the site.', mtWarning, [mbOK], 0);
    end;
     
    procedure TfrmMain.lbDirectoryDblClick(Sender: TObject);
    begin
      actDownloadFile.Execute;
    end;
     
    procedure TfrmMain.actDeleteFileFolderExecute(Sender: TObject);
    var
      i : Integer;
      s : String;
    begin
      i := lbDirectory.ItemIndex;
      if i <> -1 then
        begin
          s := lbDirectory.Items[i];
          if MessageDlg('Are you sure you want to delete %s?', mtWarning, [mbYes,mbNo], 0) = mrYes then
            FTP.Delete(s);
          DisplayFTP;
        end
      else
        MessageDlg('You must first select a file or folder to delete from the site.', mtWarning, [mbOK], 0);
    end;
     
    procedure TfrmMain.actCreateFolderExecute(Sender: TObject);
    var
      s : String;
    begin
      s := 'New Folder';
      if InputQuery('New folder', 'New folder name:', s) then
        begin
          FTP.MakeDir(s);
          ChangeFTPDir(s);
        end;
    end;
     
    procedure TfrmMain.actUploadFileExecute(Sender: TObject);
    begin
      if OpenDialog.Execute then
        begin
          if BinaryNottext1.Checked then
            FTP.TransferType := ftASCII
          else
            FTP.TransferType := ftBinary;
          FTP.Put(OpenDialog.FileName, ExtractFileName(OpenDialog.FileName));
          DisplayFTP;
        end;
    end;
     
    procedure TfrmMain.lbDirectoryKeyPress(Sender: TObject; var Key: Char);
    begin
      case Key of
        #13:
          actDownloadFile.Execute;
        #8:
          actBack.Execute;
      end;
    end;
     
    procedure TfrmMain.FormDestroy(Sender: TObject);
    begin
      FLastDirStack.Free;
      StoreDefaultValues;
      Ini.Free;
      Sites.Free;
      ApplicationConfig.Free;
    end;
     
    procedure TfrmMain.actBackExecute(Sender: TObject);
    var
      s : String;
    begin
      if FLastDirStack.Count > 0 then
        begin
          s := FLastDirStack[FLastDirStack.Count -1];
          ChangeFTPDir(s);
          // Delete S
          FLastDirStack.Delete(FLastDirStack.Count -1);
          // Delete the jump from S
          FLastDirStack.Delete(FLastDirStack.Count -1);
          SetControls;
        end;
    end;
     
    procedure TfrmMain.actHomeExecute(Sender: TObject);
    begin
      ChangeFTPDir(FRootDir);
    end;
     
    procedure TfrmMain.actHelpExecute(Sender: TObject);
    begin
      if actHelp.Enabled then
        ShellExecute(handle, 'OPEN', PChar(HelpFile), '', '', SW_SHOWNORMAL);
    end;
     
    function TfrmMain.GetHelpFile: String;
    begin
      if FHelpFile = '' then
        FHelpFile := ExpandFileName(ExtractFilePath(ParamStr(0)) + '..\Help\index.htm');
      Result := FHelpFile;
    end;
     
    procedure TfrmMain.LoadDefaultValues;
    var
      i, c : Integer;
      s : String;
      site : TFTPSiteInfo;
    begin
      InitLogColors;
      ApplicationConfig.LoadFromIni(Ini);
     
      Sites.Clear;
      c := Ini.ReadInteger('SITES', 'Count', 0);
      for i := 0 to c -1 do
        begin
          site := TFTPSiteInfo.Create;
          s := 'Site' + IntToStr(i) + '.';
          site.Name     := Ini.ReadString('SITES', s + 'Name', '');
          site.Address  := Ini.ReadString('SITES', s + 'Address', '');
          site.UserName := Ini.ReadString('SITES', s + 'UserName', '');
          site.Password := Ini.ReadString('SITES', s + 'Password', '');
          site.RootDir  := Ini.ReadString('SITES', s + 'RootDir', '');
          Sites.Add(Site);
        end;
     
      cbFTPAddress.Items.Clear;
      for i := 0 to Sites.Count -1 do
        begin
          cbFTPAddress.Items.AddObject(Sites[i].Name, Sites[i]);
        end;
    end;
     
    procedure TfrmMain.StoreDefaultValues;
    var
      i : Integer;
      s : String;
      site : TFTPSiteInfo;
    begin
      for i := 0 to Sites.Count -1 do
        begin
          site := Sites[i];
          s := 'Site' + IntToStr(i) + '.';
          Ini.WriteString('SITES', s + 'Name', site.Name);
          Ini.WriteString('SITES', s + 'Address', site.Address);
          Ini.WriteString('SITES', s + 'UserName', site.UserName);
          Ini.WriteString('SITES', s + 'Password', site.Password);
          Ini.WriteString('SITES', s + 'RootDir', site.RootDir);
        end;
     
      ApplicationConfig.SaveToIni(Ini);
     
      Ini.WriteInteger('SITES', 'Count', Sites.Count);
      s := cbFTPAddress.Text;
      cbFTPAddress.OnChange := nil;
      try
        cbFTPAddress.ItemIndex := sites.IndexOfName(s);
        if cbFTPAddress.ItemIndex = -1 then
          cbFTPAddress.ItemIndex := sites.IndexOfAddress(s);
      finally
        cbFTPAddress.OnChange := cbFTPAddressChange;
      end;
    end;
     
    procedure TfrmMain.actConfigureSiteExecute(Sender: TObject);
    begin
      if ConfigureSite(cbFTPAddress.ItemIndex, Sites) then
        begin
          StoreDefaultValues;
          LoadDefaultValues;
        end;
    end;
     
    procedure TfrmMain.actConfigureApplicationExecute(Sender: TObject);
    begin
      if ConfigureApplication(ApplicationConfig) then
        StoreDefaultValues;
    end;
     
    procedure TfrmMain.cbFTPAddressChange(Sender: TObject);
    var
      i : Integer;
    begin
      i := cbFTPAddress.ItemIndex;
      if i = -1 then
        begin
          edUserName.Text := '';
          edPassword.Text := '';
        end
      else
        begin
          edUserName.Text := TFTPSiteInfo(cbFTPAddress.Items.Objects[i]).UserName;
          edPassword.Text := TFTPSiteInfo(cbFTPAddress.Items.Objects[i]).Password;
        end;
     
      actConfigureSite.Enabled     := (cbFTPAddress.Text <> '');
      actConnectDisconnect.Enabled := (cbFTPAddress.Text <> '');
    end;
     
    procedure TfrmMain.InitLogColors;
    begin
      with ApplicationConfig.LogColors do
        begin
          Colors['Default']         := clBlack;
          Colors['hsStatusText']    := clBlack;
          Colors['hsResolving']     := clBlack;
          Colors['hsConnecting']    := clBlack;
          Colors['hsDisconnecting'] := clBlack;
          Colors['hsConnected']     := clBlue;
          Colors['hsDisconnected']  := clBlue;
          Colors['ftpTransfer']     := clBlue;
          Colors['ftpReady']        := clGreen;
          Colors['ftpAborted']      := clRed;
        end;
    end;
     
    function FtpDownloadFile(strHost, strUser, strPwd: string;
      Port: Integer; ftpDir, ftpFile, TargetFile: string; 
      ProxyUser,ProxyPassword:string; 
      ALabel:TLabel=nil;AProgressBar: TProgressBar=nil): Boolean; 
     
      function FmtFileSize(Size: Int64): string; 
      begin 
        if Size >= $E8D4A51000 then 
          Result := Format('%.2f', [Size / $3B9ACA00]) + ' To' 
        else 
        if Size >= $3B9ACA00 then 
          Result := Format('%.2f', [Size / $3B9ACA00]) + ' Go' 
        else 
        if Size >= $F4240 then 
          Result := Format('%.2f', [Size / $F4240]) + ' Mo' 
        else 
        if Size < 1000 then 
          Result := IntToStr(Size) + ' bytes' 
        else 
          Result := Format('%.2f', [Size / 1000]) + ' Ko'; 
      end; 
     
    const 
      READ_BUFFERSIZE = 4096;  // ou 256, 512, ... 
    var 
      hNet, hFTP, hFile: HINTERNET;
      buffer: array[0..READ_BUFFERSIZE - 1] of Char; 
      bufsize, dwBytesRead: DWORD; 
      fileSize:Int64; 
      sRec: TWin32FindData; 
      bSuccess: Boolean;
      PC:integer; //Pourcentage de téléchargement 
      UnFichier:TFileStream; 
    begin 
      Result := False; 
     
      { Ouvre une session internet } 
      hNet := InternetOpen('Nom du programme', // Agent 
        INTERNET_OPEN_TYPE_PRECONFIG, // AccessType 
        PChar(ProxyUser),  // Nom utilisateur pour le Proxy 
        PChar(ProxyPassword), // Mot de passe Proxy 
        0); // ou INTERNET_FLAG_ASYNC / INTERNET_FLAG_OFFLINE 
     
      { 
        l'agent contient le nom de l'application ou de 
        l'entité appelant les fonctions Internet 
      } 
     
     
      { Le Handle de connexion est-il valide?} 
      if hNet = nil then 
      begin 
        ShowMessage('Impossible d''accéder à WinInet.Dll'); 
        Exit; 
      end; 
     
      {Connexion au serveur FTP} 
      hFTP := InternetConnect(hNet, // Handle de InternetOpen 
        PChar(strHost), // serveur FTP 
        port,//ou bien (INTERNET_DEFAULT_FTP_PORT), 
        PChar(StrUser), // username 
        PChar(strPwd),  // password 
        INTERNET_SERVICE_FTP, // FTP, HTTP, ou Gopher? 
        INTERNET_FLAG_PASSIVE, // flag: 0 ou INTERNET_FLAG_PASSIVE 
        0);// Nombre défini par l'utilisateur pour un callback 
     
      if hFTP = nil then 
      begin 
        InternetCloseHandle(hNet); 
        ShowMessage(Format('L''hôte "%s" n''est pas disponible',[strHost])); 
        Exit; 
      end; 
     
      { Changer de répertoire } 
      bSuccess := FtpSetCurrentDirectory(hFTP, PChar(ftpDir)); 
     
      if not bSuccess then 
      begin 
        InternetCloseHandle(hFTP); 
        InternetCloseHandle(hNet); 
        ShowMessage(Format('Ne peut accéder au répertoire %s.',[ftpDir])); 
        Exit; 
      end; 
     
      { Lecture de la taille du fichier } 
      if FtpFindFirstFile(hFTP, PChar(ftpFile), sRec, 0, 0) <> nil then 
      begin 
        fileSize := sRec.nFileSizeLow; 
      end else 
      begin 
        InternetCloseHandle(hFTP); 
        InternetCloseHandle(hNet); 
        ShowMessage(Format('Cannot find file ',[ftpFile])); 
        Exit; 
      end; 
     
      { Ouvre le fichier } 
      hFile := FtpOpenFile(hFTP, // Handle d'une session ftp 
          PChar(ftpFile), // Nom du fichier 
          GENERIC_READ, // dwAccess 
          FTP_TRANSFER_TYPE_BINARY, // dwFlags 
          0); // Ceci est le contexte utiliser pour les Callback. 
     
      if hFile = nil then 
      begin 
        InternetCloseHandle(hFTP); 
        InternetCloseHandle(hNet); 
        Exit; 
      end; 
     
      { Créer un nouveau fichier local } 
      if FileExists(TargetFile) then DeleteFile(TargetFile); 
      UnFichier:=TFileStream.Create(TargetFile,fmCreate);
      try 
     
      dwBytesRead := 0;
      bufsize := READ_BUFFERSIZE; 
     
      while (bufsize > 0) do 
      begin 
        Application.ProcessMessages; 
     
        if not InternetReadFile(hFile, 
          @buffer, // addresse d'un buffer qui reçoit les données 
          READ_BUFFERSIZE, // Nombre d'octets à lire et à placer dans le buffer 
          bufsize)  // Nombre d'octets effectivement lus 
            then Break; //On a fini de recevoir quelque chose 
          if (bufsize > 0) and (bufsize <= READ_BUFFERSIZE) 
          then bufsize:=UnFichier.Write(buffer, bufsize); 
     
        dwBytesRead := dwBytesRead + bufsize; 
     
        { Montrer Progression } 
        PC:=Round(dwBytesRead * 100 / fileSize); 
        if Assigned(AProgressBar) 
        then AProgressBar.Position :=PC; 
        if Assigned(ALabel) 
        then ALabel.Caption := Format('%s of %s / %d %%',[FmtFileSize(dwBytesRead),FmtFileSize(fileSize) ,PC]); 
      end; 
        Result := True; 
      finally 
        UnFichier.Free; 
        InternetCloseHandle(hFile); 
        InternetCloseHandle(hFTP); 
        InternetCloseHandle(hNet); 
      end; 
     
    end;

  9. #9
    Membre du Club
    Homme Profil pro
    Inscrit en
    Octobre 2006
    Messages
    74
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Tarn et Garonne (Midi Pyrénées)

    Informations professionnelles :
    Secteur : Services à domicile

    Informations forums :
    Inscription : Octobre 2006
    Messages : 74
    Points : 50
    Points
    50
    Par défaut
    Pour en conclure avec mon problème de récupération de fichiers, j'ai trouvé la solution.

    Avec le composant Indy TIDHTTP et en utilisant les flux TFileStream pour récupérer chaque fichier sur mon serveur, ça fonctionne impec.

    Merci à tous ceux qui ont participé à cette question ....

    Beauserge

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 7
    Dernier message: 18/05/2011, 20h06
  2. mettre des fichiers sur serveur
    Par chflb dans le forum JPA
    Réponses: 0
    Dernier message: 21/08/2008, 12h05
  3. + de 2000 fichiers sur serveur FTP
    Par _seb_ dans le forum WinDev
    Réponses: 4
    Dernier message: 17/09/2007, 10h59
  4. Erreur programme d'envoi fichier sur serveur ftp
    Par batssa dans le forum Langage
    Réponses: 3
    Dernier message: 17/08/2007, 14h30
  5. Réponses: 2
    Dernier message: 20/08/2004, 17h10

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo