Tuesday, February 19, 2013

Programmatically obtain a list of files contained in a directory

If you ever need to programmatically obtain information about files contained within a given directory/folder, I've provided some sample code from a Windows Form Application I created that will provide you with that capability.  In this particular instance, my Windows App allows the user to select the directory he/she wishes to review and then populates a Grid View control with information about the files contained in the directory (i.e. in this simple example, the name of the file and the date the file was last modified):

using System.Windows.Forms;
using System.Data;
using System.IO;

public partial class Form1 : Form
{
        private FolderBrowserDialog m_fbd;

        ...

        /// <summary>
        /// When the button is clicked, the user will be prompted to select the input file to open via the OpenFileDialog
        /// control.  Once the user has selected the input file, the information in the file will be read, parsed, and then
        /// displayed in the grid view control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReviewFiles_Click(object sender, EventArgs e)
        {
            if (m_fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("FileName");
                dt.Columns.Add("LastModifiedDate");

                DirectoryInfo dir = new DirectoryInfo(m_fbd.SelectedPath);
                foreach (FileInfo file in dir.GetFiles("*.*"))
                {
                    DataRow row = dt.NewRow();
                    row["FileName"] = file.Name;
                    row["LastModifiedDate"] = file.LastWriteTime.ToString();
                    dt.Rows.Add(row);
                }
                dataGridView1.DataSource = dt;
            }
        }

If you would only like to display information about certain types of files, you can modify the parameter of the GetFiles method call appropriately.  In the following example, the code will only display information about  .pdf files contained in the selected directory:

foreach (FileInfo file in dir.GetFiles("*.pdf"))

Yes, I know...this example provides too much code to demonstrate how easy it is to programmatically obtain info about files in a given directory, but I thought it would be fun to add the additional code that could turn this into a nice utility if needed...

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.