Domanda

I'm trying to create an array of file list contained within a folder along with their attributes. The array would contain the attributes of the files as the column header. For example;

[Name,   size, Path     ]
[File A, 234,  c:\temp  ]
[File B, 632,  c:\temp\a]
[File C, 3455, c:\temp\a]

I wanted to read the attributes of each file without hard-coding the attribute names, by reading the properties of the FileInfo type. So here is what I did;

FileInfo[] files = IOUtil.GetFileList(); //<< returnes an array of FileInfo

//Get a list of public properties for the FileInfo type
Type t = typeof(FileInfo);
foreach (var p in t.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
   Console.Write(p.Name);
   // outputs names such as: Module, Assembly, RuntimeTypeHandle, MethodBase, Type, Type, String etc.
}

//loop through the files from FileInfo[] and read the attributes
foreach (FileInfo f in files){
  foreach (var attr in f.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
  {
    Console.Write(attr.PropertyType.Name + ", "); //print the attribute names again
   // outputs names such as: Name, Length, DirectoryName, Directory, IsReadOnly, Exists, FullName, Extension etc.
  }
}

I understand that in the first foreach I'm getting the properties of a type and in the second I'm getting the properties of an instant, but shouldn't they both contains the same properties? Can anyone explain why the properties in each list are different?

È stato utile?

Soluzione

You have small bug or misunderstaing. Here you enumerate properties of Type:

Type t = typeof(FileInfo);
t.GetType().GetProperties(...)

while here you enumerate properties of FileInfo:

FileInfo f = ...
f.GetType().GetProperties(...)

Of course Type is not the object itself but the description of its... type. They are not the same - as blueprint of a car is not a car.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top