Reputation: 17
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:
Problems: 1. It displays the ticket number together with the extension name (1005.txt)
Can anyone help me out? Thanks!
Upvotes: 1
Views: 2961
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
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