Zebra0.com

csharp files

The Directory command is used to retrieve an array of all the files in a directory.

  1. Start a new project called directory.
  2. Add a listbox named lstFiles.
  3. Find a folder on your computer with some files that you can use.
  4. If necessary, create a folder call C:/mydata and copy a few files to it.
  5. Write the code in form load as shown below, changing the Directory statement to the folder on your computer with the files.
// Programmer: Janet Joy
// Get all of the files in a directory
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace directory
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Get an array of all the files in the directory.
            string[] files = Directory.GetFiles(@"c:\MyData\");
            // Add each file to the combo box.
            foreach(String s in files)
            {
                lstFiles.Items.Add(s);
            }
        }
    }
}

When you run the program you will see a list of all the files in the folder:

End of lesson, Next lesson: