如何通过对话框select一个文件夹,并处理它包含的所有文件?

在我的程序中,我想从一个文件夹中逐一读取xlsx文件。 截至目前,我正在使用一个button浏览单个文件。 但是,然后我想用这个button浏览我有文件的文件夹。 所以当我select这个文件夹时,程序应该自动运行文件夹中的所有文件。 这是我之前做的。

class RatWalk { public List steps = new List(); // reads data from excel file public void LoadFromFile(String fileName) { steps.Clear(); XlsFile file = new XlsFile(fileName); try { //everything I want to do } catch { } } private void InitializeComponent() { EventHandler handler = new EventHandler(OnClick); button.Text = "Browse for the XLS file"; // button properties this.Controls.Add(button); } // Browses for the file and loads the selected Excel file private void OnClick(object sender, EventArgs e) { OpenFileDialog fileDialog = new OpenFileDialog(); if (fileDialog.ShowDialog() != DialogResult.OK) return; ratWalk.LoadFromFile(fileDialog.FileName); // Whatever I want to do } 

在这里,我想改变它,当我点击button,select文件夹,它应该运行文件夹中的所有文件一个接一个。

请让我知道如何做到这一点。

谢谢。

你可以试试这个。 这将是有益的

  FolderBrowserDialog fi = new FolderBrowserDialog(); DialogResult result = fi.ShowDialog(); if (result == DialogResult.OK) { string[] files = Directory.GetFiles(fi.SelectedPath); } 

文件数组包含文件夹中的所有文件。 使用您的过程中的文件数组…

这将适用于所选文件夹中的每个xlsx文件:

 string selectedFolder = string.Empty; FolderBrowserDialog selectFolderDialog = new FolderBrowserDialog(); if (selectFolderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { selectedFolder = selectFolderDialog.SelectedPath; DirectoryInfo dir = new DirectoryInfo(selectedFolder); foreach (var file in dir.GetFiles("*.xlsx")) { ratWalk.LoadFromFile(file.FullName); // } }