Les Snippets

Connexion

Trier une liste de fichiers par date

Niveau requis pour utiliser/comprendre cette source : 1 ( Débutant )
Créé le 08/04/2006 23:03:03 et initié par Willi [Liste]
Date de mise à jour : 12/12/2006 23:04:47
Vue : 37310
Catégorie(s) : Date & Heure, Fichier / Disque
Langages dispo pour ce code :
- VB 2005
- PHP 5
- VB 2005, VB.NET 1.x
- C# 2.x
- VBScript
- VB6
- Windev
- C# 2.x
- Python



Langage : VB 2005
Date ajout : 08/04/2006
Posté par Willi [Liste]
DateMAJ : 09/04/2006
'Récupère une liste de fichiers
Dim MyFiles As String() = IO.Directory.GetFiles("C:\UnRepertoire", "*")


'Si fichiers trouvés
If MyFiles IsNot Nothing Then
   Dim MySortedFiles As New List(Of String)
   MySortedFiles.Add(MyFiles(0)) 

   'Tri les fichiers par date du plus ancien au plus récent
   'Dans la collection MySortedFiles
   For i As Integer = 1 To MyFiles.Length - 1
      Dim CurrentDate As Date = New IO.FileInfo(MyFiles(i)).LastWriteTime

      For j As Integer = 0 To MySorteFiles.Count - 1
         Dim NextDate As Date = New IO.FileInfo(MySorteFiles(j)).LastWriteTime
         'Compare les dates du fichier précédent avec date du fichier en cours
         If Date.Compare(CurrentDate, NextDate) < 0 Then
            MySorteFiles.Insert(j, MyFiles(i))
            Exit For
         ElseIf j = MySorteFiles.Count - 1 Then
            MySortFiles.Add(MyFiles(i))
            Exit For
         End If

      Next
   Next 


Remarque :
Ajouter la directive
Imports System.Collections.Generics
Langage : PHP 5
Date ajout : 10/04/2006
Posté par FhX [Liste]
<?php
// $dir est le nom du repertoire à scanner
// $orderby sert à choisir le sens de tri pour la date.
function sortDirectorybyDate($dir, $orderby) {
$dir = scandir($rep);
$files = array();
// Parcours des fichiers
 foreach ( $dir as $file ) {
   if (!preg_match('/^\./', $data)) { // On dégage les '.' et '..';
       $files['name'][] = $file;
       $files['date'][] = $filemtime($rep."/".$file);
  }
 }
 switch ( $sortby ) {
    case 'asc':
         asort($files, SORT_NUMERIC);
         break;
    case 'desc':
         arsort($files, SORT_NUMERIC);
         break;
 }
 return $files;
}
$rep = './dir';
$FilesSortedbyDate =  sortDirectorybyDate($rep, 'asc'); // Sens croissant
$FilesSortedbyDate =  sortDirectorybyDate($rep, 'desc'); // Sens décroissant
?>
 
 

Remarque :
Ne marche que pour PHP5 via scandir() !
Langage : VB.NET 1.x , VB 2005
Date ajout : 13/04/2006
Posté par NHenry [Liste]
Imports Microsoft.VisualBasic
'Récupère une liste de fichiers
Dim MyFiles As String() = System.IO.Directory.GetFiles("C:\UnRepertoire", "*")
'Liste trièe contenant les noms des fichiers
dim mLst as new System.Collections.SortedList
'Si fichiers trouvés
If MyFiles IsNot Nothing Then
   'Tri les fichiers par date du plus ancien au plus récent
   Dim i as Integer
   For i  = 0 To MyFiles.Length - 1
      Dim CurrentDate As Date = New IO.FileInfo(MyFiles(i)).LastWriteTime
      mLst.Add(Format(CurrentDate,"yyyy.MM.dd.hh.mm.ss"),MyFiles(i))
   Next 
End if
'Pour récupérer les fichier le plus ancien, prendre le premier élément. Pour le plus récent, le dernier.
Langage : C# 2.x
Date ajout : 16/04/2006
Posté par Bidou [Liste]

public class SortFileByCreationDate

{
  public static List<FileInfo> Sort(string path, string filter) 
  {
    FileInfo[] fi = new DirectoryInfo(path).GetFiles(filter); 
    List<FileInfo> fis = new List<FileInfo>();
    foreach (FileInfo file in fi) fis.Add(file); 
    fis.Sort(new CreationDateComparer());
    return fis; 
  }

  private class CreationDateComparer : IComparer<FileInfo> 
  {
    public int Compare(FileInfo f1, FileInfo f2) 
    {
      return DateTime.Compare(f1.LastWriteTime, f2.LastWriteTime); 
    }

  }
}

// Utilisation

List<FileInfo> fileSorted = SortFileByCreationDate.Sort(@"C:\WINDOWS\system", "*.*");

Langage : VBScript
Date ajout : 30/04/2006
Posté par JMO [Liste]

'Ce script (VBS) a pour but d'afficher, dans une MsgBox, la liste des fichiers
'd'un répertoire, triés par date de modification (du + récent au + ancien)
'
'Translation de VB6 en VBS du code (réponse) proposé par "michelxld" (forum VBFrance)
'http://www.vbfrance.com/infomsg/OUVERTURE-FICHIER-RECENT-2_720974.aspx (le 22/04/2006 06:19:25)
'Un grand MERCI à "rvblog" sans lequel ce script ne serait pas fonctionnel !!!"

Option Explicit
Const Path = "d:\test"
MsgBox ShowFolderList(Path),,"Liste des fichiers du répertoire """ & Path &vbCrLf&_
      """ triés par date de modification (du + récent au + ancien)" 
Function ShowFolderList(strPath)
Dim fso, Dossiers, fic, fichiers, strListe, f, r 
Dim Valeur, imax, z, Cible, liste 
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set Dossiers = fso.GetFolder(Path)
    Set fic = Dossiers.Files

    imax = 0
    For Each fichiers In fic
        Set f = fso.GetFile(fichiers)
        imax = imax + 1
        ReDim Preserve Tableau(2, imax)
        Tableau(1, imax) = f.Name
        Tableau(2, imax) = f.DateLastModified
        
        Valeur = 0
        For imax = 1 To imax - 1
            If CDate(Tableau(2, imax)) < CDate(Tableau(2, imax + 1)) Then
               For z = 1 To 2
                   Cible = Tableau(z, imax)
                   Tableau(z, imax) = Tableau(z, imax + 1)
                   Tableau(z, imax + 1) = Cible
               Next
               Valeur = 1
            End If
        Next
    Next

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Affichage du résultat des fichiers triés par date de modification
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    liste = ""
    For r = 1 To imax
        liste = liste & vbCrLf & r & "        " & Tableau(2, r) & "       " & Tableau(1, r)
    Next
    liste = vbCrLf& "N°       Date de modification        Nom du fichier" &vbCrLf& liste    
    ShowFolderList = liste
    
    Set fso      = Nothing          
    Set Dossiers = Nothing
    Set fic      = Nothing
    Set f        = Nothing

End Function


Langage : VB6
Date ajout : 11/05/2006
Posté par Gobillot [Liste]

 Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
 
 
 Private Function ListeFichier(strPath As String, Optional SortOrder As Integer = 0) As String()
     Dim Fich  As String
     Dim Name  As String
     Dim T()   As String
     Dim D()   As Date
     Dim dt    As Date
     Dim X()   As Long
     Dim P     As Long
     Dim G     As Long
     Dim M     As Long
     Dim nb    As Long
 
     If Right$(strPath, 1) <> "\" Then strPath = strPath & "\"
     Fich = Dir(strPath & "*.*", vbHidden Or vbSystem)
 
     Do Until Fich = ""
        Name = strPath & Fich
        dt = FileDateTime(Name)
        
        P = 1: G = nb: M = 0
 
        If nb > 0 Then
           While P < G
              M = (P + G) \ 2
              If dt > D(X(M)) Then P = M + 1 Else G = M
              Wend
           If P > M Then
              If dt > D(X(P)) Then P = P + 1
              End If
           Do While P <= nb
              If dt < D(X(P)) Then Exit Do
              If dt > D(X(P)) Then Exit Do
              P = P + 1
              Loop
           End If
 
        nb = nb + 1
        ReDim Preserve T(nb), D(nb), X(nb)
        If P < nb Then
           CopyMemory X(P + 1), X(P), (nb - P) * 4
           End If
        X(P) = nb
        T(nb) = Name
        D(nb) = dt
 
        Fich = Dir()
        Loop
 
     ReDim temp(nb) As String
     If SortOrder Then
        G = nb: M = -1
        Else
        G = 1: M = 1
        End If
     For P = 1 To nb
         temp(P) = T(X(G))
         G = G + M
         Next
     ListeFichier = temp
     Erase T, temp, D, X
 End Function
 
 
Langage : Windev
Date ajout : 17/08/2006
Posté par fabienlaps [Liste]
// Déclaration d'un tableau
ptabListeFic est un tableau dynamique de 1 par 2 chaine
// Procédure de récupération des fichiers du répertoire
 PROCEDURE RecupFichier(pChemin, pNomdufichier, pChange, pPointeur)
 
 TableauAjouteLigne(ptabListeFic,pNomdufichier,fDateHeure(pChemin+pNomdufichier))
 RENVOYER Vrai

// Liste les fichiers d'un répertoire
fListeFichier("C:\temp\*.*","RecupFichier") // RecupFichierest une procédure (CallBack) définie ci-dessus
// Trie des fichiers selon la date et l'heure
TableauTrie(ptabListeFic,ttColonne,"2")



Langage : C# 2.x
Date ajout : 11/12/2006
Posté par TDKFR [Liste]
DateMAJ : 12/12/2006

public class SortFileByCreationDate
{
   public static List<FileInfo> Sort(string path, string filter) 
   {
      FileInfo[] fi = new DirectoryInfo(path).GetFiles(filter);
      List<FileInfo> fis = new List<FileInfo>(); 
      fis.AddRange(fi);
      fis.Sort(new Comparison<FileInfo>(
             delegate(FileInfo f1, FileInfo f2) 
             {
                 return f1.LastWriteTime.CompareTo(f2.LastWriteTime);
             }));
      return fis; 
   }
}




Remarque :
Une autre manière de faire en C# 2.0. Code inspiré de celui posté par Bidou.
Langage : Python
Date ajout : 28/04/2007
Posté par pacificator [Liste]
import os
from stat import ST_CTIME
def get_files_by_date(directory):
 files = [(os.stat(f)[ST_CTIME], f) for f in os.listdir(directory) if os.path.isfile(f)]
 files.sort()
 return  [f for s,f in files]

Snippets en rapport avec : Fichier, Date, Tri, Liste, Trier



Codes sources en rapport avec : Fichier, Date, Tri, Liste, Trier

{Visual Basic, VB6, VB.NET, VB 2005} [VBSCRIPT] LISTE DES FICHIERS, D'UN RÉPERTOIRE, TRIÉS PAR DATE DE MODIFICATION (DU + RÉCENT AU + ANCIEN)
Ce script (VBS) a pour but d'afficher, dans une MsgBox, la liste des fichiers d'un répertoire, trié...

{PHP} TRI PAR TYPE DE FICHIER / EXTENSION
Fonction pour trier des noms de fichiers par type (et alphabétiquement au sein d'un type). Concrè...

{PHP} DIFFÉRENCE ENTRE DEUX DATE EN JOURS (LISTE RÉCUPÉRÉE DANS UN TABLEAU)
Salut J'ai cherché une fonction permettant de récupérer une liste de date entre deux dates donnée...

{Visual Basic, VB6, VB.NET, VB 2005} SCANLIST V4
Encore plus rapide que la version précédente et avec l'option html et le lien qui suit le fichier (e...

{Javascript / DHTML} TABLEAU GÉNÉRÉ ET TRIÉ PAR LE CLIENT
Le but ici est d'illustrer plusieurs techniques de développement javascript. La première concerne ...

{C / C++ / C++.NET} CHANGEUR DATE FICHIER (WIN32)
On choisit la date et on applique sur un ficihier ou tous les fichiers d'un dossier. J'avais fait...

{Visual Basic, VB6, VB.NET, VB 2005} TRI DES ITEMS DE LISTVIEW (DATE, NUMÉRIQUE OU PERSO)
Une petite source qui montre comment trier efficacement (et facilement) les colonnes de vos ListVi...

{Delphi} STATUTILS - LES STATISTIQUES
Bonsoir, voici une librairie de gestion basique de séries statistiques, StatUtils. Evidemment elle...

{C / C++ / C++.NET} CHANGER LA DATE DE CRÉATION/MODIFICATION DE FICHIERS AVEC UN ÉQUIVALENT DU "TOUCH" UNIX/MS-DOS
Salut à tous ! Je poste ici le code source d'un petit utilitaire qui me permet de changer la date...

{C / C++ / C++.NET} LISTER LES FICHIERS D'UN REPERTOIRE + FILTRES
Programmé sous Linux. Compatible windows. Liste les fichiers d'un répertoire come indiqué dans le...