Async
Async

Reputation: 17

C# : How to display all text files in a folder to a listbox in Windows form

So I'm currently practicing my skills by creating a sample queue-system storing data in a local textfile. I was wondering if I can display a list of tickets on a listbox (queue box).

1 textfile = 1 ticket.

Here is my sample code:

enter image description here

Problems: 1. It displays the ticket number together with the extension name (1005.txt)

  1. It kinda adds to the listbox all the textfiles in the folder. I only wanna show the textfiles as listitems so when I click refresh, it must display the same number of items and not adding duplicates.

Can anyone help me out? Thanks!

Upvotes: 1

Views: 2961

Answers (2)

Yang Kin
Yang Kin

Reputation: 96

private void refreshMainQueue_Click(object sender, EventArgs e)
        {
            /* Comment: I am using lower camelCase for naming convention. */

            /* Comment: Solve your Problem 2: Always clear the list box before populating records. */
            ticketBox.Items.Clear();

            DirectoryInfo dInfo = new DirectoryInfo(@"C:\SampleDirectory");
            FileInfo[] files = dInfo.GetFiles("*.txt");
            /* Comment: Only perform the below logic if there are Files within the directory. */
            if (files.Count() > 0)
            {
                /* Comment: Create an array that has the exact size of the number of files 
                 * in the directory to store the fileNames. */
                string[] fileNames = new string[files.Count()];

                for (int i = 0; i < files.Count(); i++)
                {
                    /* Comment: Solve your Problem 1: 
                     * Refer here to remove extension: https://stackoverflow.com/questions/4804990/c-sharp-getting-file-names-without-extensions */
                    fileNames[i] = Path.GetFileNameWithoutExtension(files[i].Name);
                }

                ticketBox.Items.AddRange(fileNames);
            }
        }

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

Try this code,

ticketBox.Items.Clear();
DirectoryInfo dinfo = new DirectoryInfo(@"C:\SampleDirectory");
FileInfo[] smFiles = dinfo.GetFiles("*.txt");
foreach (FileInfo fi in smFiles)
{
    ticketBox.Items.Add(Path.GetFileNameWithoutExtension(fi.Name));
}

Upvotes: 2

Related Questions