温馨提示×

winform怎么读取文件夹的文件

小亿
83
2024-05-17 10:16:17
栏目: 智能运维

在WinForm中,可以使用System.IO命名空间中的Directory类来读取文件夹中的文件。以下是一个简单的示例代码,演示如何读取文件夹中的文件并将文件名显示在ListBox控件中:

using System;
using System.IO;
using System.Windows.Forms;

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

        private void btnLoadFiles_Click(object sender, EventArgs e)
        {
            // 指定要读取的文件夹路径
            string folderPath = @"C:\path\to\folder";

            // 检查文件夹是否存在
            if (Directory.Exists(folderPath))
            {
                // 获取文件夹中的文件
                string[] files = Directory.GetFiles(folderPath);

                // 将文件名显示在ListBox控件中
                foreach (string file in files)
                {
                    listBoxFiles.Items.Add(Path.GetFileName(file));
                }
            }
            else
            {
                MessageBox.Show("文件夹不存在!");
            }
        }
    }
}

在上面的示例代码中,btnLoadFiles_Click方法会在单击按钮时读取指定文件夹中的文件,并将文件名显示在名为listBoxFiles的ListBox控件中。请确保替换folderPath变量中的路径为您要读取的文件夹路径。

0