繁体   English   中英

如何通过对话框选择文件夹并处理它包含的所有文件

[英]How to select a folder through a dialog and process all the files it contains

我想从一个文件夹中逐个读取xlsx文件。 我目前正在使用按钮浏览单个文件,但我想使用此按钮浏览我有文件的文件夹。 因此,当我选择此文件夹时,程序应该自动逐个运行文件夹中的所有文件。

这是我的代码:

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   
    }
}

我想以这样的方式更改它,当我单击按钮并选择文件夹时,它会逐个运行文件夹中的所有文件。

你可以试试这个。 这会有所帮助

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

files数组包含文件夹中的所有文件。 为您的进程使用files数组...

这适用于所选文件夹中的每个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);
                //
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM