温馨提示×

winform怎么读取文件夹的文件

小亿
161
2024-05-17 10:16:17
栏目: 智能运维
Windows服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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变量中的路径为您要读取的文件夹路径。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:matlab怎么读取文件夹所有文件

0