Lire les informations sur les fichiers en C#

En C#, nous pouvons récupérer diverses informations relatives aux fichiers. Nous allons modifier notre explorateur de classes pour lui permettre d'afficher ces informations.

Nous allons donc ajouter à la classe ClassInfo (dans le fichier ClassInfo.cs) une méthode statique qui nous permettra de récupérer par exemple une chaîne de caractères avec les informations du fichier dont nous donnons le nom complet (avec le chemin) en argument.

  1. public static String getFileInfos(String classPath)
  2. {
  3. FileSystemInfo f = new FileInfo(classPath);
  4. StringBuilder str = new StringBuilder(f.Name);
  5. str.Append("\n\nInfos :");
  6. str.Append("\nCreation time : ");
  7. str.Append(f.CreationTime);
  8. str.Append("\nLast access : ");
  9. str.Append(f.LastAccessTime);
  10. str.Append("\nAttributes : ");
  11. str.Append(f.Attributes);
  12. str.Append("\nFullName : ");
  13. str.Append(f.FullName);
  14. return str.ToString();
  15. }

Nous utilisons la classe FileSystemInfo pour manipuler les informations relatives au fichier. Comme FileSystemInfo est une classe abstraite, nous ne pouvons l'instancier (créer un objet de cette classe), nous instancions un objet  FileInfo qui dérive de FileSystemInfo, et que nous considérerons comme un objet FileSystemInfo.
Remarque : cette méthode retourne une chaîne de caractères formatée (elle présente des retours à la ligne générés par les séquences \n). Cette manière de procéder est pratique car nous pouvons y faire appel dans une application console ou une application graphique. Seulement, au niveau de l'analyse de l'application, cette méthode ne devrait retourner qu'une collection d'informations car elle fait partie du modèle (voir MVC). C'est aux classes qui font partie de la vue (la console, la fenêtre de notre application, la page Web, etc.) que revient la responsabilité de présenter les informations de telle ou telle manière.

Nous pouvons en profiter pour remarquer l'emploi de la classe StringBuilder, qui nous permet au moyen de la méthode Append() d'ajouter à chaque fois une chaîne de caractères. En effet, la concaténation de chaînes de caractères dans un String à l'aide de l'opérateur + est relativement coûteuse en ressources car elle nécessite à chaque fois la création d'un nouvel objet String.

Table des matières Haut

Le code complet

Nous pouvons en profiter pour apporter quelques améliorations à notre code :

  • nous n'affichons plus les membres hérités gràce à l'ajout du drapeau BindingFlags.DeclaredOnly
  • nous affichons le nombre de membres gràce à la propriété .Length (une méthode qui se déguise en attribut).
  1. using System;
  2. using System.Collections;
  3. using System.Text;
  4. using System.Reflection;
  5. using System.Windows.Forms;
  6. using System.IO;
  7. namespace ClassExplorer
  8. {
  9. class ClassInfo
  10. {
  11. public static TreeNode[] getInfos(String classPath)
  12. {
  13. TreeNode classesTreeNode = new TreeNode("Classes");
  14. TreeNode enumsTreeNode = new TreeNode("Enums");
  15. TreeNode interfacesTreeNode = new TreeNode("Interfaces");
  16. Assembly assembly = Assembly.LoadFrom(classPath);
  17. Type[] types = assembly.GetTypes();
  18. foreach (Type type in types)
  19. {
  20. if (type.IsClass) classesTreeNode.Nodes.Add(getClassNode(type));
  21. else if (type.IsEnum) enumsTreeNode.Nodes.Add(type.Name);
  22. else if (type.IsInterface) interfacesTreeNode.Nodes.Add(type.Name);
  23. }
  24. TreeNode[] infos = { classesTreeNode, enumsTreeNode, interfacesTreeNode };
  25. return infos;
  26. }
  27. public static String getFileInfos(String classPath)
  28. {
  29. FileSystemInfo f = new FileInfo(classPath);
  30. StringBuilder str = new StringBuilder(f.Name);
  31. str.Append("\n\nInfos :");
  32. str.Append("\nCreation time : ");
  33. str.Append(f.CreationTime);
  34. str.Append("\nLast access : ");
  35. str.Append(f.LastAccessTime);
  36. str.Append("\nAttributes : ");
  37. str.Append(f.Attributes);
  38. str.Append("\nFullName : ");
  39. str.Append(f.FullName);
  40. return str.ToString();
  41. }
  42. public static String getFileName(String classPath)
  43. {
  44. FileSystemInfo f = new FileInfo(classPath);
  45. return f.Name;
  46. }
  47. private static TreeNode getClassNode(Type type)
  48. {
  49. TreeNode classNode = new TreeNode(type.Name);
  50. MethodInfo[] methodsInfos = type.GetMethods(
  51. BindingFlags.NonPublic |
  52. BindingFlags.Instance |
  53. BindingFlags.Public |
  54. BindingFlags.Static |
  55. BindingFlags.DeclaredOnly
  56. );
  57. if (methodsInfos.Length > 0)
  58. {
  59. TreeNode methodsNode = new TreeNode("Methods (" + methodsInfos.Length +")");
  60. foreach (MethodInfo methodInfo in methodsInfos)
  61. {
  62. methodsNode.Nodes.Add(getMethodNode(methodInfo));
  63. }
  64. classNode.Nodes.Add(methodsNode);
  65. }
  66. else classNode.Nodes.Add("No methods available");
  67. ConstructorInfo[] constructorsInfos = type.GetConstructors(
  68. BindingFlags.NonPublic |
  69. BindingFlags.Instance |
  70. BindingFlags.Public |
  71. BindingFlags.Static |
  72. BindingFlags.DeclaredOnly
  73. );
  74. if (constructorsInfos.Length > 0)
  75. {
  76. TreeNode constructorsNode = new TreeNode("Constructors (" + constructorsInfos.Length + ")");
  77. foreach (ConstructorInfo constructorInfo in constructorsInfos)
  78. {
  79. constructorsNode.Nodes.Add(getConstructorNode(constructorInfo));
  80. }
  81. classNode.Nodes.Add(constructorsNode);
  82. }
  83. else classNode.Nodes.Add("No constructors available");
  84. FieldInfo[] fieldsInfos = type.GetFields(
  85. BindingFlags.NonPublic |
  86. BindingFlags.Instance |
  87. BindingFlags.Public |
  88. BindingFlags.Static |
  89. BindingFlags.DeclaredOnly
  90. );
  91. if (fieldsInfos.Length > 0)
  92. {
  93. TreeNode fieldsNode = new TreeNode("Fields (" + fieldsInfos.Length + ")");
  94. foreach (FieldInfo fieldInfo in fieldsInfos)
  95. {
  96. fieldsNode.Nodes.Add(getFieldNode(fieldInfo));
  97. }
  98. classNode.Nodes.Add(fieldsNode);
  99. }
  100. else classNode.Nodes.Add("No fields available");
  101. PropertyInfo[] propsInfos = type.GetProperties(
  102. BindingFlags.NonPublic |
  103. BindingFlags.Instance |
  104. BindingFlags.Public |
  105. BindingFlags.Static |
  106. BindingFlags.DeclaredOnly
  107. );
  108. if (propsInfos.Length > 0)
  109. {
  110. TreeNode propsNode = new TreeNode("Properties (" + propsInfos.Length + ")");
  111. foreach (PropertyInfo propInfo in propsInfos)
  112. {
  113. propsNode.Nodes.Add(propInfo.Name);
  114. }
  115. classNode.Nodes.Add(propsNode);
  116. }
  117. else classNode.Nodes.Add("No properties available");
  118. return classNode;
  119. }
  120. private static TreeNode getConstructorNode(ConstructorInfo constructorInfo)
  121. {
  122. StringBuilder constrStr = new StringBuilder();
  123. if (constructorInfo.IsPrivate) constrStr.Append("Private ");
  124. else if (constructorInfo.IsStatic) constrStr.Append("Static ");
  125. else if (constructorInfo.IsPublic) constrStr.Append("Public ");
  126. constrStr.Append(constructorInfo.Name);
  127. TreeNode constructorNode = new TreeNode(constrStr.ToString());
  128. ParameterInfo[] paramInfos = constructorInfo.GetParameters();
  129. foreach (ParameterInfo paramInfo in paramInfos)
  130. {
  131. constructorNode.Nodes.Add(
  132. String.Format("{0} {1}", paramInfo.ParameterType.ToString(), paramInfo.Name)
  133. );
  134. }
  135. return constructorNode;
  136. }
  137. private static TreeNode getMethodNode(MethodInfo methodInfo)
  138. {
  139. StringBuilder methodStr = new StringBuilder();
  140. if (methodInfo.IsPrivate) methodStr.Append("Private ");
  141. else if (methodInfo.IsStatic) methodStr.Append("Static ");
  142. else if (methodInfo.IsPublic) methodStr.Append("Public ");
  143. methodStr.Append(methodInfo.Name);
  144. TreeNode methodNode = new TreeNode(methodStr.ToString());
  145. ParameterInfo[] paramInfos = methodInfo.GetParameters();
  146. foreach (ParameterInfo paramInfo in paramInfos)
  147. {
  148. methodNode.Nodes.Add(
  149. String.Format("{0} {1}", paramInfo.ParameterType.ToString(), paramInfo.Name)
  150. );
  151. }
  152. return methodNode;
  153. }
  154. private static TreeNode getFieldNode(FieldInfo fieldInfo)
  155. {
  156. StringBuilder fieldStr = new StringBuilder();
  157. if (fieldInfo.IsPrivate) fieldStr.Append("Private ");
  158. else if (fieldInfo.IsStatic) fieldStr.Append("Static ");
  159. else if (fieldInfo.IsPublic) fieldStr.Append("Public ");
  160. fieldStr.Append(fieldInfo.Name);
  161. TreeNode fieldNode = new TreeNode(fieldStr.ToString());
  162. return fieldNode;
  163. }
  164. }
  165. }

Document créé le 01/10/2006, dernière modification le 26/10/2018
Source du document imprimé : https://www.gaudry.be/csharp-fileinfo.html

L'infobrol est un site personnel dont le contenu n'engage que moi. Le texte est mis à disposition sous licence CreativeCommons(BY-NC-SA). Plus d'info sur les conditions d'utilisation et sur l'auteur.