C# example: List files in a directory using ListView

ListView can be used to implement a file manager.Here i simply specify a hint to list files of a directory.
for this, first drag and drop a ListView control to your form. Set it's view property to Details. In the column property add a new column and set its text to "Filename".
now, use this reference to your code

using System.IO;         //This should be added to your code if you want to do file operations.

now in the load event of the form write the below code

         try
            {
// Check if directory is present or not
                if Directory.Exists( @"C:\Users\Public\Pictures\Sample Pictures") )
                {
                    DirectoryInfo di = new DirectoryInfo(@"C:\Users\Public\Pictures\Sample Pictures");
// here if '@' is not used then we need to write "C:\\Users\\Public\\Pictures\\Sample Pictures"

                    FileInfo[] files = di.GetFiles();
                    foreach (FileInfo f in files)
                    {
//filename(without path) is added to listview1

                        listView1.Items.Add(f.Name);
// to add full path name then use 'FullName' property instead of 'Name' property
                    }
                }
                else
                    MessageBox.Show("Folder doesn't exist");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"Error");
            }


The above code can be written simply as below


         try
            {
// Check if directory is present or not
           if Directory.Exists( @"C:\Users\Public\Pictures\Sample Pictures") )
           {                
                   
  foreach (FileInfo f in new DirectoryInfo(@"C:\Users\Public\Pictures\Sample Pictures").GetFiles())
                    {
//filename(without path) is added to listview1

                        listView1.Items.Add(f.Name);
                    }
                }
                else
                    MessageBox.Show("Folder doesn't exist");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"Error");
            }

Comments

Post a Comment