共計 711 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 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 變量中的路徑為您要讀取的文件夾路徑。
丸趣 TV 網(wǎng) – 提供最優(yōu)質的資源集合!
正文完
發(fā)表至: 網(wǎng)站制作
2024-05-20