Search code examples
c#textopenfiledialog

read file contents to an array


I have this code

private void button1_Click(object sender, EventArgs e)
{
    Stream myStream;

    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
    openFileDialog1.FilterIndex = 1;
    openFileDialog1.Multiselect = true;

    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        if ((myStream = openFileDialog1.OpenFile()) != null)
        {
            string strfilename = openFileDialog1.FileName;
            string filetext = File.ReadAllText(strfilename);

            richTextBox3.Text = filetext; // reads all text into one text box
        }
    }
}

I'm struggling on how to get each line of the text file to a different text box or possibly store it in an array, can some one help please!


Solution

  • File.ReadAllText will read all of the text in a file.

    string filetext = File.ReadAllText("The file path");
    

    If you want to store each line separately in an array, File.ReadAllLines can do that.

    string[] lines = File.ReadAllLines("The file path");