C# ,显示指定目录下所有txt文件到listBox1中

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 listbox内容
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //窗体加载时让列表框2显示一组目录            
            listBox2.Items.Add("c:\\");
            listBox2.Items.Add("c:\\1\\");
            listBox2.Items.Add("d:\\");


        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (listBox2.Text == string.Empty) 
            {
                MessageBox.Show("没有选中目录");
                return;
            } 
            
            listBox1.Items.Clear();
            if (!Directory.Exists(listBox2.Text))
            {
                MessageBox.Show("目录不存在");
                return;
            }
            DirectoryInfo theFolder = new DirectoryInfo(listBox2.Text);            
            //遍历文件夹
            foreach (FileInfo file in theFolder.GetFiles("*.txt"))
            {                
                listBox1.Items.Add(file.Name);
            }

        }
    }
}

猜你喜欢

转载自blog.csdn.net/laocooon/article/details/121685566