如何将一个文件夹的内容分别打开到不同的富文本框?

how to open the content of a folder in to different rich text boxes?

我正在尝试打开文件对话框并将文件夹内的文件打开到不同的富文本框?但我不确定我还需要添加什么?能不能帮个忙啊

            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
            tabPage1.Text = openFileDialog1.SafeFileName;
        }

OpenFileDialog默认只打开一个文件。尝试将其 MultiSelect 属性 更改为 true。这样的事情会做:

openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    for (int i = 0; i < openFileDialog1.FileNames.Length; ++i) {
        RichTextBox rtb = Controls.Cast<Control>().Single(x => x.Name == "richTextBox" + (i + 1).ToString()) as RichTextBox;
        rtb.Text = File.ReadAllText(openFileDialog1.FileNames[i]);
    }
    tabPage1.Text = openFileDialog1.SafeFileName; //again, I wonder what you want to do with this. If needed be, consider to update this dynamically too
}           

旧答案:

openFileDialog1.Multiselect = true; //important: set this to true
richTextBox1.Text = ""; //and you may want to reset this every time
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    foreach(var filename in openFileDialog1.FileNames) //get file names here
        richTextBox1.Text += File.ReadAllText(filename); //you may want to add enter per file
    tabPage1.Text = openFileDialog1.SafeFileName; //but I wonder what you want to do with this....?
}           

如果您想允许您的用户 select 一个文件夹,然后打开该文件夹中的前 5 个文件,每个文件都在不同的 richtextbox 中,那么您不需要 OpenFileDialog,但是 FolderBrowserDialog

// First prepare two list with the richtextboxes and the tabpages
List<RichTextBox> myBoxes = new List<RichTextBox>()
{ richTextBox1, richTextBox2, richTextBox3, richTextBox4, richTextBox5 };
List<TabPage> myPages = new List<TabPage>()
{ tabPage1, tabPage2, tabPage3, tabPage4, tabPage5};


// Now open the folderbrowser dialog 
// (see link above for some of its properties)
FolderBrowserDialog fbd = new FolderBrowserDialog();
if(fbd.ShowDialog() == DialogResult.OK)
{
    int i = 0;
    foreach(string file in Directory.GetFiles(fbd.SelectedPath))
    {        
        myBoxes[i].Text = File.ReadAllText(file);
        myPages[i].Text = Path.GetFileName(file);
        i++;

        // Added a warning if the folder contains more than 5 files
        if(i >= 5)
        { 
           MessageBox.Show("Too many files in folder, only 5 loaded");
           break;
        }
     }
 }