如何在不同的富文本框中打开文件夹的内容?

时间:2016-02-20 18:06:55

标签: c# file dialog richtextbox

我试图打开文件对话框并将文件夹中的文件打开到不同的富文本框中?但我不确定还需要添加什么?你能不能请一个新的血液。

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

2 个答案:

答案 0 :(得分:2)

如果您想允许用户选择一个文件夹,然后打开该文件夹中存在的前5个文件,每个文件位于不同的richtextbox中,那么您不需要OpenFileDialog,而是{{ 3}}

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

答案 1 :(得分:1)

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