C#:如何将文件夹中的所有文本文件显示为Windows窗体中的列表框

时间:2017-08-09 02:42:34

标签: c# visual-studio listbox text-files

所以我现在通过创建一个在本地文本文件中存储数据的示例队列系统来练习我的技能。我想知道是否可以在列表框(队列框)上显示票证列表。

1 textfile = 1票。

以下是我的示例代码:

enter image description here

问题:  1.它显示票号和扩展名(1005.txt)

  1. 它有点在列表框中添加文件夹中的所有文本文件。我只想将文本文件显示为列表项,因此当我点击刷新时,它必须显示相同数量的项目而不添加重复项。
  2. 任何人都可以帮助我吗?谢谢!

2 个答案:

答案 0 :(得分:1)

试试这段代码,

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));
}

答案 1 :(得分:0)

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);
            }
        }