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

API standards et tierces Java Discussion :

[Windows]lecture des fichier lnk (raccourcis) [FAQ]


Sujet :

API standards et tierces Java

  1. #1
    Membre habitué
    Profil pro
    Inscrit en
    Novembre 2002
    Messages
    154
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2002
    Messages : 154
    Points : 143
    Points
    143
    Par défaut [Windows]lecture des fichier lnk (raccourcis)
    Salut à tous, je marchais trankillement dans la rue et il m'est venue une question existentielle : comment faire pour lire un fichier .lnk, c'est à dire le genre de fichier se trouvant sur le bureau ou dans le menu démarrer (les raccourcis koi). En java pure, je me dis que c'est impossible. So, existe-il une librairie ou un exemple de code en C/C++/C# qui permette de répondre à ce problème.

    Merci à tous
    Bonne chance, Bonne journée, bonne année bonne santée et etc ...
    Youpi la vie est belle ! Et vive la fraicheur

  2. #2
    Membre actif
    Inscrit en
    Juillet 2003
    Messages
    407
    Détails du profil
    Informations forums :
    Inscription : Juillet 2003
    Messages : 407
    Points : 252
    Points
    252
    Par défaut
    je crois que ca depend du fichier
    est ce que le raccourci est un lien d'un fichier que java peut lire comme .doc , .txt , ....

    pour les exécutable , je ne crois pas

    il faut tester pour les fichier qui peuvent etre lu (.txt , .doc )
    ;-) cordialement

  3. #3
    Membre expérimenté
    Avatar de RanDomX
    Profil pro
    sans
    Inscrit en
    Mars 2003
    Messages
    579
    Détails du profil
    Informations personnelles :
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : sans

    Informations forums :
    Inscription : Mars 2003
    Messages : 579
    Points : 1 407
    Points
    1 407
    Par défaut
    ben il suffit de le rahjouter dans le path non ??? ( pas le classpath )

  4. #4
    duj
    duj est déconnecté
    Membre confirmé

    Profil pro
    Inscrit en
    Juillet 2003
    Messages
    141
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Juillet 2003
    Messages : 141
    Points : 474
    Points
    474
    Par défaut
    Tu as certainement déjà essayé en passant le nom du link ?
    Que c'est -il passé?
    Parfois, Google fait des miracles

  5. #5
    Membre à l'essai
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    28
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Juin 2003
    Messages : 28
    Points : 19
    Points
    19
    Par défaut
    Salut.
    Avant tout, je précise que je suis l'auteur de la question. J'étais pas sur mon ordinateur quand j'ai écris la question et c le username de celui qui utilise la machine qui s'est mis. Bref, tant pis.

    Tout ca pour dire que j'ai résolu mon problème.

    1. Le raccourci windows est un fichier comme les autres, c'est à dire qu'il peut etre lu via un flux (FileInputStream).

    2. J'ai effectivement essayé d'exécuter directement le fichier .lnk (résultat : bah, dla merde koi ! ).

    3. J'ai cherché s'il n'existait pas un truc déjà fait (genre un ptit programme C++ ou autre. Mais c'était un peu compliqué à mon goût.

    4. Donc, je suis partis sur la lecture du fichier lui-même, c'est à dire octet par octet. Car il faut savoir qu'un fichier .lnk répond à un format très précis, il ne s'agit pas d'un fichier contenant du texte mais d'un fichier binaire formaté.

    FORMAT
    ----------
    Header
    Shell Item Id List
    File Location Info
    Description
    Relative Path
    Working directory
    Command Line Arguments
    Icon Filename
    Additional Info


    Header
    --------
    - 4 octets -> indique à windows qu'il s'agit d'un raccourci
    -> 4C 00 00 00 toujours

    - 16 octets -> GUID
    -> 01 14 02 00 00 00 00 00 C0 00 00 00 00 00 00 46
    - 1 dword (int) -> flag
    -> bit 0 : la liste des items est elle présente ??
    -> bit 1 : la cible ? fichier ou répertoire ?
    -> bit 2 : le raccourci a-t-il une description ?
    -> bit 3 : le raccourci a-t-il un chemin relatif ?
    -> bit 4 : le raccouci a-t-il un répertoire de travail ?
    -> bit 5 : le raccourci a t-il des arguments ?
    -> bit 6 : le raccouci a-t-il une icone particulière
    -> les autres bits, on s'en fout

    - 1 dword -> un autre flag avec des indic sur la cible(je met de coté)
    - 1 qword (long) -> date de création
    - 1 qword (long) -> date de modification
    - 1 qword (long) -> date de dernier accès
    - 1 dword -> taille du fichier cible
    - 1 dword -> le numéro de l'icone (si le bit 6 est à 1 dans le flag) sinon 0
    - 1 dword -> affichage de la fenetre (1:NORMAL, 2:MINI, 3:MAXI)
    - 1 dword -> la HOT KEY
    - 2 dword -> toujours à 00...00


    Shell Item Id List
    --------------------

    Cette section du fichier .lnk n'est présente que si le bit 0 du flag est positionné à 1. Elle contient plein d'information dont je n'ai pas besoin, donc je saute

    - 1 word (short) -> taille de la liste (ca me permet de skipper les octets)


    File Location Infos
    ---------------------

    C'est la section qui, comme son nom l'indique, contient des informations sur la location du fichier. Les différents offset commencent à partir du début de cette section. Si la cible est un répertoire, cette section ne contient que le premier dword qui vaudra 0.

    - 1 dword -> sa taille.
    - 1 dword qui vaut toujours 1C
    - 1 dword -> fichier en local ou en partage réseau ??
    - 1 dword -> deplacement vers la table du volume local (??)
    - 1 dword -> offset pour récupérer le chemin de base
    - 1 dword -> deplacement vers la table du volume réseau(??)
    - 1 dword -> offset pour récupérer le chemin final

    Table du volume local :
    --------------------------
    - 1 dword -> taille de cette structure
    - 1 dword -> Type du volume (2 pour removable, 3 disk Dur, 5 CD)
    - 1 dword -> numéro de série du volume
    - 1 dword -> 0x10 toujours
    - ASCII (String) -> label du volume

    Table du volume réseau :
    -----------------------------
    - 1 dword -> taille de cette structure
    - 1 dword -> toujours 0x02
    - 1 dword -> 0x14
    - 1 dword -> 0x00
    - 1 dword -> 0x20000
    - ASCII (String) -> Label du share

    En combinant le chemin de base avec le chemin final, on retrouve le chemin de la cible sur le volume local. Pour un fichier sur le réseau, il suffit de combiner le nom du partage (share) avec le chemin final.


    Description :
    ---------------
    Seulement si le bit 2 est à 1 -> tout d'abord, un word (short) pour la taille de la description puis la description elle-même (les caractères sont codés sur 2 octets).

    Chemin relatif :
    ------------------
    Seulement si le bit 3 est à 1 -> tout d'abord, un word (short) pour la taille du chemin relatif puis le chemin lui-même (les caractères sont codés sur 2 octets).

    Répertoire de travail :
    -------------------------
    Seulement si le bit 4 est à 1 -> tout d'abord, un word (short) pour la taille du chemin du répertoire de travail puis le chemin du répertoire de travail lui-même (les caractères sont codés sur 2 octets).

    les arguments :
    ------------------
    Seulement si le bit 5 est à 1 -> tout d'abord, un word (short) pour la taille de la ligne d'arguments puis la ligne d'argument elle-même (les caractères sont codés sur 2 octets).

    Le fichier d'icone :
    ---------------------
    Seulement si le bit 6 est à 1 -> tout d'abord, un word (short) pour la taille du chemin vers l'icone puis le chemin vers l'icone elle-même (les caractères sont codés sur 2 octets).

    Informations complémentaires
    -----------------------------------
    - un dword -> toujours à 00 00 00 00



    Voilà pour le format....ouf.....

    En tout cas, merci pour les différentes réponses.

    Au final, j'ai créé une classe qui lit les informations d'un fichier .lnk.

    Pour le code de cette classe, je le mettrai demain.

  6. #6
    Membre habitué
    Profil pro
    Inscrit en
    Novembre 2002
    Messages
    154
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2002
    Messages : 154
    Points : 143
    Points
    143
    Par défaut
    Bon bah, comme prévu, je fous mon bout de code qui permet de lire un shortcut. Attention, y'a certainement des choses que j'ai aps géré car j'en avais pas besoin (la table réseau), donc soyez indulgents...

    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
     
     
    public class WindowsShortcut 
    {
      private String filename = null;
      private boolean hasRelativePath = false;
      private boolean hasDescription = false;
      private boolean hasWorkingDirectory = false;
      private boolean hasCommandLineArgument = false;
      private boolean hasAnIcon = false;
      private boolean shellItemPresent = false;
      private boolean fileOnLocalDisk = false;
      private int volumeTableOffset = 0;
      private int pathOffset = 0;
      private int networkTableOffset = 0;
      private int finalPathOffset = 0;
      private String path = null;
      private String finalPath = null;
      private String description = null;
      private String relativePath = null;
      private String workingDirectory = null;
      private String arguments = null;
     
     
      /**
       * Initialise l'objet SHORTCUT
       * @param filename le fichier .lnk dont on veut récupérer les informations
       */
      public WindowsShortcut(String filename) {
        this.filename = filename;
      }
     
      /**
       * Effectue la lecture du fichier .lnk passé au constructeur
       * @throws IOException si le fichier ne peut etre lu
       */
      public void processShortcut() throws IOException {
        DataInputStream in = new DataInputStream(new FileInputStream(filename));
     
        // Lecture du header
        processHeader(in);
     
        // Si la liste des items est présente, on s'en occupe
        if (shellItemPresent) {
          processShellItem(in);
        }
     
        // Lecture des informations sur la location du fichier
        processFileLocationInfo(in);
     
        // Si le fichier est en local, on traite la table de volume local
        if (fileOnLocalDisk) {
          processLocalVolumeTable(in);
        }
        // Sinon, on s'occupe de celle réseau
        else {
          processNetworkVolumeTable(in);
        }
     
        // On traite le chemin de base
        processPath(in);
     
        // On traite le chemin final
        processfinalPath(in);
     
        // Si le raccourci a une description, on s'en occupe
        if (hasDescription) {
          description = processString(in);
        }
     
        // Si le raccourci a un chemin relatif, on s'en occupe
        if (hasRelativePath) {
          relativePath = processString(in);
        }
     
        // Si le raccourci a un répertoire de travail, on s'en occupe
        if (hasWorkingDirectory) {
          workingDirectory = processString(in);
     
          // Cas particulier pour traiter le répertoire de travail c:\
          if (workingDirectory.equals("%HOMEDRIVE%%HOMEPATH%")) {
            workingDirectory = "C:\\";
          }
        }
     
        // Si il y a des arguments, on les récupère
        if (hasCommandLineArgument) {
          arguments = processString(in);
        }
     
        // Fermeture du flux vers le fichier .lnk
        in.close();
      }
     
      private String processString(DataInputStream in) throws IOException {
        int length = mYReadShort(in);
     
        StringBuffer buf = new StringBuffer(length);
        byte temp = 1;
     
        for (int i = 0; i < length; i++) {
          buf.append( (char) (mYReadShort(in)));
        }
     
        return buf.toString();
      }
     
      private void processfinalPath(DataInputStream in) throws IOException {
        StringBuffer buf = new StringBuffer();
        byte temp = 1;
     
        while ( (temp = in.readByte()) != 0) {
          buf.append( (char) temp);
        }
     
        finalPath = buf.toString();
      }
     
      private void processPath(DataInputStream in) throws IOException {
        StringBuffer buf = new StringBuffer();
        byte temp = 1;
     
        while ( (temp = in.readByte()) != 0) {
          buf.append( (char) temp);
        }
        path = buf.toString();
      }
     
      private void processLocalVolumeTable(DataInputStream in) throws IOException {
        int structureLocalVolumeLenght = mYReadInt(in);
        int driveType = mYReadInt(in);;
     
        // Volume Serial Number
        in.readInt();
     
        // Volume name offset (always 0x10)
        in.readInt();
     
        in.skipBytes(structureLocalVolumeLenght - 16);
      }
     
      private void processNetworkVolumeTable(DataInputStream in) throws IOException {
        int structureLocalVolumeLenght = mYReadInt(in);;
        int driveType = mYReadInt(in);;
     
        // Volume Serial Number
        in.readInt();
     
        // Volume name offset (always 0x10)
        in.readInt();
     
        in.skipBytes(structureLocalVolumeLenght - 16);
      }
     
      private void processFileLocationInfo(DataInputStream in) throws IOException {
        int dataStructureInfo = mYReadInt(in);;
        int dataStructureEndOffset = mYReadInt(in);;
        fileOnLocalDisk = ( mYReadInt(in) == 1 ? true : false);
        volumeTableOffset = mYReadInt(in);
        pathOffset = mYReadInt(in);
        networkTableOffset = mYReadInt(in);
        finalPathOffset = mYReadInt(in);
      }
     
      private void processHeader(DataInputStream in) throws IOException {
        //read first 4 bytes, can test if they are 4C 00 00 00
        mYReadInt(in);
     
        // GUID 16 bytes, current is 01 14 02 00 00 00 00 00 C0 00 00 00 00 00 46
        mYReadLong(in);
        mYReadLong(in);
     
        // read shortcut flags 1 dword (double word -> 4 bytes -> 1 Int)
        processFlag(mYReadInt(in));
     
        // read target file flags 1 dword (idem)
        mYReadInt(in);
     
        // Read dates creation, modification, last access
        mYReadLong(in);
        mYReadLong(in);
        mYReadLong(in);
     
        // Read the length of the file
        mYReadInt(in);
     
        // Read the index of the icon, 0 if no custom icon
        mYReadInt(in);
     
        // Read the state of the program windows (1 : normal, 2 mini, 3 max)
        mYReadInt(in);
     
        // Read the Hot Key
        mYReadInt(in);
     
        // Read the 2 last dword of the header
        mYReadLong(in);
      }
     
      private void processShellItem(DataInputStream in) throws IOException {
        int itemListLength = mYReadShort(in);
     
        in.skipBytes(itemListLength);
      }
     
      private void processFlag(int flag) {
        if ( (flag & 1) == 1) {
          shellItemPresent = true;
        }
        if ( (flag & 4) == 4) {
          hasDescription = true;
        }
        if ( (flag & 8) == 8) {
          hasRelativePath = true;
        }
        if ( (flag & 16) == 16) {
          hasWorkingDirectory = true;
        }
        if ( (flag & 32) == 32) {
          hasCommandLineArgument = true;
        }
        if ( (flag & 64) == 64) {
          hasAnIcon = true;
        }
      }
     
      public String toString() {
            return "Raccourci du fichier " + filename + " : \n" + "Une description :  " +
                 (hasDescription ? "OUI\n" : "NON\n") +
                 "Un répertoire de travail :  " +
                 (hasWorkingDirectory ? "OUI\n" : "NON\n") +
             "Des arguments :  " + (hasCommandLineArgument ? "OUI\n" : "NON\n") +
                 "Une chemin relatif :  " + (hasRelativePath ? "OUI\n" : "NON\n") +
                 "une icone :  " + (hasAnIcon ? "OUI\n" : "NON\n") +
                 "Item :  " + (shellItemPresent ? "OUI\n" : "NON\n") +
                 "LE CHEMIN D'ACCES : " + path +
                 "\nLE CHEMIN FINAL : " + finalPath +
                 "\nLA DESCRIPTION : " + description +
                 "\nCHEMIN RELATIF : " + relativePath +
                 "\nREPERTOIRE DE TRAVAIL : " + workingDirectory +
                 "\nARGUMENTS : " + arguments;
     
      }
     
      public String getWorkingDirectory() {
        return workingDirectory;
      }
     
      public String getPath() {
        return path;
      }
     
      public String getDescription() {
        return description;
      }
     
      public String getArguments() {
        return arguments;
      }
     
      private int mYReadInt(DataInputStream in) throws IOException {
        byte a = in.readByte();
        byte b = in.readByte();
        byte c = in.readByte();
        byte d = in.readByte();
     
        return ( (d & 0xFF) << 24) | ( (c & 0xFF) << 16) | ( (b & 0xFF) << 8) |
            (a & 0xFF);
      }
     
      private int mYReadShort(DataInputStream in) throws IOException {
        byte a = in.readByte();
        byte b = in.readByte();
     
        int ret = 0;
     
        return ret | ( (b & 0xFF) << 8) | (a & 0xFF);
      }
     
      private long mYReadLong(DataInputStream in) throws IOException {
        byte a = in.readByte();
        byte b = in.readByte();
        byte c = in.readByte();
        byte d = in.readByte();
        byte e = in.readByte();
        byte f = in.readByte();
        byte g = in.readByte();
        byte h = in.readByte();
     
        return ( (h & 0xFF) << 56) | ( (g & 0xFF) << 48) | ( (f & 0xFF) << 40) |
            ( (e & 0xFF) << 32) |
            ( (d & 0xFF) << 24) | ( (c & 0xFF) << 16) | ( (b & 0xFF) << 8) |
            (a & 0xFF);
      }
     
      public static void main(String[] args) {
        WindowsShortcut test = new WindowsShortcut(
            "C:\\Documents and Settings\\Administrator\\Desktop\\Scrabble® 2003 Edition.lnk");
     
        try {
          test.processShortcut();
          System.out.println(test);
        }
        catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    Voilà
    Bonne chance, Bonne journée, bonne année bonne santée et etc ...
    Youpi la vie est belle ! Et vive la fraicheur

  7. #7
    Membre à l'essai
    Profil pro
    Inscrit en
    Mars 2007
    Messages
    19
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2007
    Messages : 19
    Points : 16
    Points
    16
    Par défaut
    Bonjour,

    Mon application veut copier des fichiers à partir de leur raccourci windows.
    Après de rapides recherches, j'ai trouvé ce fil, avec ces explications sur le format des fichiers '.lnk', et ce code qui permet d'accéder aux informations contenues dans ces fichiers. (Au passage, je suis impressionné par la vitesse à laquelle ça a été codé : bravo )

    J'ai facilement adapté le code a mes besoins, et quelques essais m'ont montré que ça fonctionnait bien ... sauf en ce qui concerne les raccourcis qui m'intéressent, et après des essais sur une plus large échelle, quelques autres raccourcis. Je ne comprends pas pourquoi, et quelles sont les particularités des raccourcis pour lesquels je n'obtient pas le chemin de la cible.

    voici ci dessous ce que j'obtiens :

    Raccourci du fichier E:\Courrier\Section_1\15.doc.lnk :
    Une description : OUI
    Un répertoire de travail : NON
    Des arguments : NON
    Une chemin relatif : OUI
    une icone : NON
    Item : OUI
    LE CHEMIN D'ACCES : E:\
    LE CHEMIN FINAL :
    LA DESCRIPTION :
    CHEMIN RELATIF : □□□□□□□□□???????????????????????????
    REPERTOIRE DE TRAVAIL : null
    ARGUMENTS : null


    J'ai fait de multiples recherches, et hormis des codes faisant appel à JNI , avec des dll, je n'ai rien trouvé de plus simple ni de plus intéressant que celui de ce fil.
    Je n'ai pas non plus réussit a ouvrir avec un éditeur hexadécimal les fichiers 'lnk', car c'est toujours la cible qui s'ouvre.

    Quelqu'un a-t'il une idée ?

  8. #8
    Membre expert
    Avatar de ®om
    Profil pro
    Inscrit en
    Janvier 2005
    Messages
    2 815
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2005
    Messages : 2 815
    Points : 3 080
    Points
    3 080
    Par défaut
    Ah merci pour la description du header, tu as trouvé ça où?

    Pour trier mes photos de plusieurs manières différentes simultanément, je copie physiquement à partir de mon appareil photo en tri par date, et ma copine fait des liens pour trier par évènements (dans des sous-répertoires).
    Sauf que depuis que je suis passé à linux, les liens ne fonctionnent plus (évidemment), il faut donc que je les parse et que je les recrée sous linux (ln -s).

    Ça me servira

  9. #9
    Membre à l'essai
    Profil pro
    Inscrit en
    Mars 2007
    Messages
    19
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2007
    Messages : 19
    Points : 16
    Points
    16
    Par défaut
    pour la description, je l'ai retrouvé ici:

    http://www.wotsit.org/list.asp?search=lnk&button=GO%21

    Finalement j'ai réussit a ouvrir les fichiers '.lnk' avec ultraedit : il y a une option a cocher dans les préférences

  10. #10
    Membre à l'essai
    Profil pro
    Inscrit en
    Mars 2007
    Messages
    19
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2007
    Messages : 19
    Points : 16
    Points
    16
    Par défaut
    Maintenant que je peux visualiser les fichiers *.lnk en hexa, j'ai constaté que ceux qui ne sont pas déchiffrés par le code de TIAPS, sont ceux dont les cibles sont situées sur mon disque E : le path est alors écrit sous forme d'URL dans le code hexa : exemple : 'Ordi3\\E.Courrier\document.doc'.

    Alors que ceux dont les cibles situés sur mon disque C sont lus par le code de TIAPS et sont notés dans le code hexa sous la forme d'un chemin classique : 'C:\Courrier\document.doc'

  11. #11
    Nouveau Candidat au Club
    Profil pro
    Inscrit en
    Octobre 2009
    Messages
    1
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2009
    Messages : 1
    Points : 1
    Points
    1
    Par défaut une version csharp (vite fait à partir de la version java)
    ( à Tiaps pour le code java)

    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
     
    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
     
    namespace WindowsShortcut
    {
     
     
    	public class WindowsShortcut
    	{
    		private String filename = null;
    		private bool hasRelativePath = false;
    		private bool hasDescription = false;
    		private bool hasWorkingDirectory = false;
    		private bool hasCommandLineArgument = false;
    		private bool hasAnIcon = false;
    		private bool shellItemPresent = false;
    		private bool fileOnLocalDisk = false;
    		private int volumeTableOffset = 0;
    		private int pathOffset = 0;
    		private int networkTableOffset = 0;
    		private int finalPathOffset = 0;
    		private String path = null;
    		private String finalPath = null;
    		private String description = null;
    		private String relativePath = null;
    		private String workingDirectory = null;
    		private String arguments = null;
     
     
    		/**
                     * Initialise l'objet SHORTCUT
                     * @param filename le fichier .lnk dont on veut récupérer les informations
                     */
    		public WindowsShortcut(String filename)
    		{
    			this.filename = filename;
    		}
     
    		/**
                     * Effectue la lecture du fichier .lnk passé au constructeur
                     * @throws IOException si le fichier ne peut etre lu
                     */
    		public void processShortcut()
    		{
    //			FileStream inStream = new FileStream(new FileStream(filename, FileMode.Open, FileAccess.Read));
    			FileStream inStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
     
    			// Lecture du header
    			processHeader(inStream);
     
    			// Si la liste des items est présente, on s'en occupe
    			if (shellItemPresent)
    			{
    				processShellItem(inStream);
    			}
     
    			// Lecture des informations sur la location du fichier
    			processFileLocationInfo(inStream);
     
    			// Si le fichier est en local, on traite la table de volume local
    			if (fileOnLocalDisk)
    			{
    				processLocalVolumeTable(inStream);
    			}
    			// Sinon, on s'occupe de celle réseau
    			else
    			{
    				processNetworkVolumeTable(inStream);
    			}
     
    			// On traite le chemin de base
    			processPath(inStream);
     
    			// On traite le chemin final
    			processfinalPath(inStream);
     
    			// Si le raccourci a une description, on s'en occupe
    			if (hasDescription)
    			{
    				description = processString(inStream);
    			}
     
    			// Si le raccourci a un chemin relatif, on s'en occupe
    			if (hasRelativePath)
    			{
    				relativePath = processString(inStream);
    			}
     
    			// Si le raccourci a un répertoire de travail, on s'en occupe
    			if (hasWorkingDirectory)
    			{
    				workingDirectory = processString(inStream);
     
    				// Cas particulier pour traiter le répertoire de travail c:\
    				if (workingDirectory == ("%HOMEDRIVE%%HOMEPATH%"))
    				{
    					workingDirectory = "C:\\";
    				}
    			}
     
    			// Si il y a des arguments, on les récupère
    			if (hasCommandLineArgument)
    			{
    				arguments = processString(inStream);
    			}
     
    			// Fermeture du flux vers le fichier .lnk
    			inStream.Close();
    		}
     
    		private String processString(FileStream inStream)
    		{
    			int length = mYReadShort(inStream);
     
    			//StringBuffer buf = new StringBuffer(length);
    			String buf = "";
    			byte temp = 1;
     
    			for (int i = 0; i < length; i++)
    			{
    				buf = buf + ((char)(mYReadShort(inStream)));
    			}
     
    			return buf;
    		}
     
    		private void processfinalPath(FileStream inStream)
    		{
    			//StringBuffer buf = new StringBuffer();
    			String buf = "";
    			byte temp = 1;
     
    			//while ((temp = inStream.readByte()) != 0)
    			while ((temp = (byte)inStream.ReadByte()) != 0)
    			{
    				//buf.append((char)temp);
    				buf = buf + ((char)temp);
    			}
     
    			finalPath = buf;
    		}
     
    		private void processPath(FileStream inStream)
    		{
    			//StringBuffer buf = new StringBuffer();
    			String buf = "";
    			byte temp = 1;
     
    			//while ((temp = inStream.readByte()) != 0)
    			while ((temp = (byte)inStream.ReadByte()) != 0)
    			{
    				//buf.append((char)temp);
    				buf = buf + ((char)temp);
    			}
    			path = buf;
    		}
     
    		private void processLocalVolumeTable(FileStream inStream)
    		{
    			int structureLocalVolumeLenght = mYReadInt(inStream);
    			int driveType = mYReadInt(inStream); ;
     
    			// Volume Serial Number
    			//inStream.readInt();
    			inStream.ReadByte(); inStream.ReadByte(); inStream.ReadByte(); inStream.ReadByte();
     
    			// Volume name offset (always 0x10)
    			//inStream.readInt();
    			inStream.ReadByte(); inStream.ReadByte(); inStream.ReadByte(); inStream.ReadByte();
     
    			inStream.Seek(structureLocalVolumeLenght - 16, SeekOrigin.Current);
    			//inStream.skipBytes(structureLocalVolumeLenght - 16);
    		}
     
    		private void processNetworkVolumeTable(FileStream inStream)
    		{
    			int structureLocalVolumeLenght = mYReadInt(inStream);
    			int driveType = mYReadInt(inStream);
     
    			// Volume Serial Number
    			//inStream.readInt();
    			inStream.ReadByte(); inStream.ReadByte(); inStream.ReadByte(); inStream.ReadByte();
     
    			// Volume name offset (always 0x10)
    			//inStream.readInt();
    			inStream.ReadByte(); inStream.ReadByte(); inStream.ReadByte(); inStream.ReadByte();
     
    			//inStream.skipBytes(structureLocalVolumeLenght - 16);
    			inStream.Seek(structureLocalVolumeLenght - 16, SeekOrigin.Current);
    		}
     
    		private void processFileLocationInfo(FileStream inStream)
    		{
    			int dataStructureInfo = mYReadInt(inStream); ;
    			int dataStructureEndOffset = mYReadInt(inStream); ;
    			fileOnLocalDisk = (mYReadInt(inStream) == 1 ? true : false);
    			volumeTableOffset = mYReadInt(inStream);
    			pathOffset = mYReadInt(inStream);
    			networkTableOffset = mYReadInt(inStream);
    			finalPathOffset = mYReadInt(inStream);
    		}
     
    		private void processHeader(FileStream inStream)
    		{
    			//read first 4 bytes, can test if they are 4C 00 00 00
    			mYReadInt(inStream);
     
    			// GUID 16 bytes, current is 01 14 02 00 00 00 00 00 C0 00 00 00 00 00 46
    			mYReadLong(inStream);
    			mYReadLong(inStream);
     
    			// read shortcut flags 1 dword (double word -> 4 bytes -> 1 Int)
    			processFlag(mYReadInt(inStream));
     
    			// read target file flags 1 dword (idem)
    			mYReadInt(inStream);
     
    			// Read dates creation, modification, last access
    			mYReadLong(inStream);
    			mYReadLong(inStream);
    			mYReadLong(inStream);
     
    			// Read the length of the file
    			mYReadInt(inStream);
     
    			// Read the index of the icon, 0 if no custom icon
    			mYReadInt(inStream);
     
    			// Read the state of the program windows (1 : normal, 2 mini, 3 max)
    			mYReadInt(inStream);
     
    			// Read the Hot Key
    			mYReadInt(inStream);
     
    			// Read the 2 last dword of the header
    			mYReadLong(inStream);
    		}
     
    		private void processShellItem(FileStream inStream)
    		{
    			int itemListLength = mYReadShort(inStream);
     
    			//inStream.skipBytes(itemListLength);
    			inStream.Seek(itemListLength, SeekOrigin.Current);
    		}
     
    		private void processFlag(int flag)
    		{
    			if ((flag & 1) == 1)
    			{
    				shellItemPresent = true;
    			}
    			if ((flag & 4) == 4)
    			{
    				hasDescription = true;
    			}
    			if ((flag & 8) == 8)
    			{
    				hasRelativePath = true;
    			}
    			if ((flag & 16) == 16)
    			{
    				hasWorkingDirectory = true;
    			}
    			if ((flag & 32) == 32)
    			{
    				hasCommandLineArgument = true;
    			}
    			if ((flag & 64) == 64)
    			{
    				hasAnIcon = true;
    			}
    		}
     
    		public String ToString()
    		{
    			return "Raccourci du fichier " + filename + " : \n" + "Une description :  " +
    				 (hasDescription ? "OUI\n" : "NON\n") +
    				 "Un répertoire de travail :  " +
    				 (hasWorkingDirectory ? "OUI\n" : "NON\n") +
    			 "Des arguments :  " + (hasCommandLineArgument ? "OUI\n" : "NON\n") +
    				 "Une chemin relatif :  " + (hasRelativePath ? "OUI\n" : "NON\n") +
    				 "une icone :  " + (hasAnIcon ? "OUI\n" : "NON\n") +
    				 "Item :  " + (shellItemPresent ? "OUI\n" : "NON\n") +
    				 "LE CHEMIN D'ACCES : " + path +
    				 "\nLE CHEMIN FINAL : " + finalPath +
    				 "\nLA DESCRIPTION : " + description +
    				 "\nCHEMIN RELATIF : " + relativePath +
    				 "\nREPERTOIRE DE TRAVAIL : " + workingDirectory +
    				 "\nARGUMENTS : " + arguments;
     
    		}
     
    		public String getWorkingDirectory()
    		{
    			return workingDirectory;
    		}
     
    		public String getPath()
    		{
    			return path;
    		}
     
    		public String getDescription()
    		{
    			return description;
    		}
     
    		public String getArguments()
    		{
    			return arguments;
    		}
     
    		private int mYReadInt(FileStream inStream)
    		{
    			byte a = (byte)inStream.ReadByte();
    			byte b = (byte)inStream.ReadByte();
    			byte c = (byte)inStream.ReadByte();
    			byte d = (byte)inStream.ReadByte();
     
    			return ((d & 0xFF) << 24) | ((c & 0xFF) << 16) | ((b & 0xFF) << 8) |
    				(a & 0xFF);
    		}
     
    		private int mYReadShort(FileStream inStream)
    		{
    			byte a = (byte)inStream.ReadByte();
    			byte b = (byte)inStream.ReadByte();
     
    			int ret = 0;
     
    			return ret | ((b & 0xFF) << 8) | (a & 0xFF);
    		}
     
    		private long mYReadLong(FileStream inStream)
    		{
    			byte a = (byte)inStream.ReadByte();
    			byte b = (byte)inStream.ReadByte();
    			byte c = (byte)inStream.ReadByte();
    			byte d = (byte)inStream.ReadByte();
    			byte e = (byte)inStream.ReadByte();
    			byte f = (byte)inStream.ReadByte();
    			byte g = (byte)inStream.ReadByte();
    			byte h = (byte)inStream.ReadByte();
     
    			return ((h & 0xFF) << 56) | ((g & 0xFF) << 48) | ((f & 0xFF) << 40) |
    				((e & 0xFF) << 32) |
    				((d & 0xFF) << 24) | ((c & 0xFF) << 16) | ((b & 0xFF) << 8) |
    				(a & 0xFF);
    		}
     
    		public static void Main(String[] args)
    		{
    			//WindowsShortcut test = new WindowsShortcut("C:\\temp\\l.lnk");
    			WindowsShortcut test = new WindowsShortcut("C:\\temp\\temp.lnk");
     
    			try
    			{
    				test.processShortcut();
    				System.Console.WriteLine(test.ToString());
    			}
    			catch (IOException e)
    			{
    				System.Console.WriteLine(e.ToString());
    			}
    		}
    	}
    }

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

Discussions similaires

  1. Lecture des fichiers LOG de Windows
    Par Nono40 dans le forum Codes sources à télécharger
    Réponses: 0
    Dernier message: 23/02/2013, 11h53
  2. Lecture des fichiers .sh sous Windows
    Par vg-matrix dans le forum Administration système
    Réponses: 3
    Dernier message: 12/08/2011, 17h15
  3. [POI] Problème de lecture des fichiers Word
    Par Dari dans le forum Documents
    Réponses: 9
    Dernier message: 05/07/2007, 14h08
  4. Lecture des fichiers INI
    Par jamfr73 dans le forum Linux
    Réponses: 2
    Dernier message: 13/04/2006, 01h03
  5. Lecture des fichiers INDEX.DAT ?
    Par rpoulin dans le forum Langage
    Réponses: 4
    Dernier message: 02/11/2005, 07h46

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