Processing Files Using Anonymous Types
Posted
Wed, Aug 19 2009 14:06
by
Deborah Kurata
Another use of anonymous types is for processing directories or files. For example, your application needs to collect a set of files and then process them based on a subset of the file properties.
[To begin with an overview of anonymous types, start here.]
Here is an example.
In C#:
// Query the set of files
var fileTemplateQuery = from FileInfo f in
new DirectoryInfo(@"C:\temp")
.GetFiles("*.*", SearchOption.AllDirectories)
where f.Extension.ToLower() == ".xml" ||
f.Extension.ToLower() == ".txt"
select new
{
DateLastModified = f.LastWriteTime,
Extension = f.Extension,
Size = f.Length,
FileName = f.Name
};
foreach (var f in fileTemplateQuery.OrderBy(file =>
file.DateLastModified))
// Do whatever you need to with the files
Debug.WriteLine(f.FileName);
In VB:
Dim fileTemplateQuery = From f As FileInfo In _
My.Computer.FileSystem.GetDirectoryInfo("C:\temp") _
.GetFiles("*.*", SearchOption.AllDirectories) _
Where f.Extension.ToLower = ".xml" OrElse _
f.Extension.ToLower = ".txt" _
Select New With _
{ _
.DateLastModified = f.LastWriteTime, _
.Extension = f.Extension, _
.Size = f.Length, _
.FileName = f.Name _
}
For Each f In _
fileTemplateQuery.OrderBy(Function(file) file.DateLastModified)
' Do whatever you need to with the files
Debug.WriteLine(f.FileName)
Next
This code uses Linq to find a specific set of files. In this case, it finds all of the files in C:\temp and its subdirectories where the extension is .xml or .txt. It then uses an anonymous type to retain the set of desired file properties.
The for/each statement loops through the set of anonymous types in order by date and performs whatever operation is required to process the files.
Enjoy!