LINQ to filesystem
Edit on GitHubThe past few hours, I've been experimenting with LINQ. As a sample application, I'm trying to create a small photo album website, which shows me all images in a specific folder on my webserver.
What does LINQ have to do with that? Everyone has used a loop over all files in a folder, and I decided to try LINQ for that matter. Here's how:
[code:c#]
var rootFolder = "C:\\";
var selectedImages = from file in Directory.GetFiles(rootFolder, "*.jpg")
select new { Path = file,
Name = new FileInfo(file).Name,
CreationDate = new FileInfo(file).CreationTime,
DirectoryName = new FileInfo(file).DirectoryName
};
[/code]
There you go! A collection named "selectedImages", filled with anonymous class instances containg a file Path, Name, CreationDate and DirectoryName. This collection can now be bound to, for example, a GridView:
[code:c#]
this.gridView1.DataSource = selectedImages;
this.gridView1.DataBind();
[/code]
EDIT: (mental note to myself: add LINQ keywords to syntax highlighter...) - done!
This is an imported post. It was imported from my old blog using an automated tool and may contain formatting errors and/or broken images.
2 responses