Monday, August 13, 2007

LINQ file info code

 Here is a LINQ sample in C# based on the VB.Net How Do I? videos. To set this up create a simple windows form application, add a DataGridView and dock it to the form.

Place the following code in the form load event handler:

System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

      watch.Start();

           var files = (from  file in Directory.GetFiles(Application.StartupPath)
              select file);

           var fileInfo = (from file in files
                          select new FileInfo(file));

           var myFiles = from file in fileInfo
                         select new FileOps { Creation = file.CreationTime, Name = file.Name };

           dataGridView1.DataSource = myFiles.ToList();

           watch.Stop();

           TimeSpan ts = watch.Elapsed;

           MessageBox.Show(String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
               ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10));

 

To use the object initializers with anonymous types add the following class nested in the form class:

public class FileOps
  {
      public string Name { get; set; }
      public DateTime Creation { get; set; }
  }

 

You'll notice we start looking in the application startup directory, just replace it with the directory of your choice to try other directories. You can comment out the timing code if you just want to run the sample without a message box.

Enjoy................

1 comment:

Sabine said...

Interesting to know.